diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/pyproject.toml b/tasks/tasksmith-b1dd32dfa88b/tests/source/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..4ceaee8d3ec142cc2a975d2a206650a5486fc096 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/pyproject.toml @@ -0,0 +1,43 @@ +[tool.ruff] +line-length = 119 +target-version = "py39" + +[tool.ruff.lint] +preview = true +extend-select = [ + "B009", # static getattr + "B010", # static setattr + "CPY", # Copyright + "E", # PEP8 errors + "F", # PEP8 formatting + "I", # Import sorting + "TID251", # Banned API + "UP", # Pyupgrade + "W", # PEP8 warnings +] +ignore = [ + "E501", # Line length (handled by ruff-format) + "E741", # Ambiguous variable name + "W605", # Invalid escape sequence + "UP007", # X | Y type annotations +] + +[tool.ruff.lint.per-file-ignores] +"__init__.py" = [ + "F401", # Ignore seemingly unused imports (they're meant for re-export) +] +"manim_animations/*" = ["ALL"] + +[tool.ruff.lint.isort] +lines-after-imports = 2 +known-first-party = ["accelerate"] + +[tool.ruff.format] +exclude = [ + "manim_animations/*" +] + +[tool.ruff.lint.flake8-tidy-imports.banned-api] +"os.getenv".msg = "Use os.environ instead" +"os.putenv".msg = "Use os.environ instead" +"os.unsetenv".msg = "Use os.environ instead" diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/setup.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..4fa4bc5faf5e04b994423ebdf6a3a68a756092cc --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/setup.py @@ -0,0 +1,127 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from setuptools import find_packages, setup + + +extras = {} +extras["quality"] = [ + "black ~= 23.1", # hf-doc-builder has a hidden dependency on `black` + "hf-doc-builder >= 0.3.0", + "ruff ~= 0.11.2", +] +extras["docs"] = [] +extras["test_prod"] = ["pytest>=7.2.0,<=8.0.0", "pytest-xdist", "pytest-subtests", "parameterized", "pytest-order"] +extras["test_dev"] = [ + "datasets", + "diffusers", + "evaluate", + "torchdata>=0.8.0", + "torchpippy>=0.2.0", + "transformers", + "scipy", + "scikit-learn", + "tqdm", + "bitsandbytes", + "timm", +] +extras["testing"] = extras["test_prod"] + extras["test_dev"] +extras["deepspeed"] = ["deepspeed"] +extras["rich"] = ["rich"] + +extras["test_fp8"] = ["torchao"] # note: TE for now needs to be done via pulling down the docker image directly +extras["test_trackers"] = [ + "wandb", + "comet-ml", + "tensorboard", + "dvclive", + "mlflow", + "matplotlib", + "swanlab", + "trackio", +] +extras["dev"] = extras["quality"] + extras["testing"] + extras["rich"] + +extras["sagemaker"] = [ + "sagemaker", # boto3 is a required package in sagemaker +] + +setup( + name="accelerate", + version="1.10.0.dev0", + description="Accelerate", + long_description=open("README.md", encoding="utf-8").read(), + long_description_content_type="text/markdown", + keywords="deep learning", + license="Apache", + author="The HuggingFace team", + author_email="zach.mueller@huggingface.co", + url="https://github.com/huggingface/accelerate", + package_dir={"": "src"}, + packages=find_packages("src"), + entry_points={ + "console_scripts": [ + "accelerate=accelerate.commands.accelerate_cli:main", + "accelerate-config=accelerate.commands.config:main", + "accelerate-estimate-memory=accelerate.commands.estimate:main", + "accelerate-launch=accelerate.commands.launch:main", + "accelerate-merge-weights=accelerate.commands.merge:main", + ] + }, + python_requires=">=3.9.0", + install_requires=[ + "numpy>=1.17,<3.0.0", + "packaging>=20.0", + "psutil", + "pyyaml", + "torch>=2.0.0", + "huggingface_hub>=0.21.0", + "safetensors>=0.4.3", + ], + extras_require=extras, + classifiers=[ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Intended Audience :: Education", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: Apache Software License", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Topic :: Scientific/Engineering :: Artificial Intelligence", + ], +) + +# Release checklist +# 1. Checkout the release branch (for a patch the current release branch, for a new minor version, create one): +# git checkout -b vXX.xx-release +# The -b is only necessary for creation (so remove it when doing a patch) +# 2. Change the version in __init__.py and setup.py to the proper value. +# 3. Commit these changes with the message: "Release: v" +# 4. Add a tag in git to mark the release: +# git tag v -m 'Adds tag v for pypi' +# Push the tag and release commit to git: git push --tags origin vXX.xx-release +# 5. Run the following commands in the top-level directory: +# make prepare_release +# 6. Upload the package to the pypi test server first: +# make target=testpypi upload_release +# 7. Check that you can install it in a virtualenv by running: +# make install_test_release +# accelerate env +# accelerate test +# 8. Upload the final version to actual pypi: +# make target=pypi upload_release +# 9. Add release notes to the tag in github once everything is looking hunky-dory. +# 10. Go back to the main branch and update the version in __init__.py, setup.py to the new version ".dev" and push to +# main. diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/__init__.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..92d16deafe47901a080c69c6eb472a13a3a72daf --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/__init__.py @@ -0,0 +1,51 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +__version__ = "1.10.0.dev0" + +from .accelerator import Accelerator +from .big_modeling import ( + cpu_offload, + cpu_offload_with_hook, + disk_offload, + dispatch_model, + init_empty_weights, + init_on_device, + load_checkpoint_and_dispatch, +) +from .data_loader import skip_first_batches +from .inference import prepare_pippy +from .launchers import debug_launcher, notebook_launcher +from .parallelism_config import ParallelismConfig +from .state import PartialState +from .utils import ( + AutocastKwargs, + DataLoaderConfiguration, + DDPCommunicationHookType, + DeepSpeedPlugin, + DistributedDataParallelKwargs, + DistributedType, + FullyShardedDataParallelPlugin, + GradScalerKwargs, + InitProcessGroupKwargs, + ProfileKwargs, + find_executable_batch_size, + infer_auto_device_map, + is_rich_available, + load_checkpoint_in_model, + synchronize_rng_states, +) + + +if is_rich_available(): + from .utils import rich diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/accelerator.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/accelerator.py new file mode 100644 index 0000000000000000000000000000000000000000..382b01213327d1504941f1750993a0cbabc88d63 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/accelerator.py @@ -0,0 +1,4249 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import contextlib +import functools +import json +import math +import os +import re +import shutil +import sys +import warnings +from collections import OrderedDict +from contextlib import contextmanager +from functools import partial +from types import MethodType +from typing import Any, Callable, Union + +import torch +import torch.utils.hooks as hooks +from huggingface_hub import split_torch_state_dict_into_shards + +from accelerate.utils.dataclasses import FP8BackendType + +from .big_modeling import _attach_context_parallel_hooks +from .checkpointing import load_accelerator_state, load_custom_state, save_accelerator_state, save_custom_state +from .data_loader import DataLoaderDispatcher, prepare_data_loader, skip_first_batches +from .logging import get_logger +from .optimizer import AcceleratedOptimizer +from .parallelism_config import ParallelismConfig +from .scheduler import AcceleratedScheduler +from .state import AcceleratorState, GradientState, PartialState +from .tracking import LOGGER_TYPE_TO_CLASS, GeneralTracker, filter_trackers +from .utils import ( + MODEL_NAME, + SAFE_WEIGHTS_INDEX_NAME, + SAFE_WEIGHTS_NAME, + SAFE_WEIGHTS_PATTERN_NAME, + WEIGHTS_INDEX_NAME, + WEIGHTS_NAME, + WEIGHTS_PATTERN_NAME, + AORecipeKwargs, + AutocastKwargs, + DataLoaderConfiguration, + DeepSpeedPlugin, + DistributedDataParallelKwargs, + DistributedType, + DynamoBackend, + FP8RecipeKwargs, + FullyShardedDataParallelPlugin, + GradientAccumulationPlugin, + GradScalerKwargs, + InitProcessGroupKwargs, + KwargsHandler, + LoggerType, + MegatronLMPlugin, + MSAMPRecipeKwargs, + PrecisionType, + ProfileKwargs, + ProjectConfiguration, + RNGType, + TERecipeKwargs, + TorchDynamoPlugin, + TorchTensorParallelPlugin, + apply_fp8_autowrap, + check_os_kernel, + clean_state_dict_for_safetensors, + compare_versions, + convert_model, + convert_model_to_fp8_ao, + convert_outputs_to_fp32, + ensure_weights_retied, + extract_model_from_parallel, + fsdp2_apply_ac, + fsdp2_canonicalize_names, + fsdp2_prepare_model, + fsdp2_switch_optimizer_parameters, + gather, + gather_object, + get_fsdp2_grad_scaler, + get_grad_scaler, + get_mixed_precision_context_manager, + get_pretty_name, + has_offloaded_params, + is_bf16_available, + is_bitsandbytes_multi_backend_available, + is_deepspeed_available, + is_ipex_available, + is_lomo_available, + is_megatron_lm_available, + is_mlu_available, + is_msamp_available, + is_musa_available, + is_npu_available, + is_torch_version, + is_torch_xla_available, + is_torchao_available, + is_transformer_engine_available, + is_xpu_available, + load_fsdp_model, + load_fsdp_optimizer, + model_has_dtensor, + pad_across_processes, + parse_choice_from_env, + recursively_apply, + reduce, + release_memory, + save, + save_fsdp_model, + save_fsdp_optimizer, + wait_for_everyone, +) +from .utils.constants import ( + FSDP2_PYTORCH_VERSION, + FSDP_PYTORCH_VERSION, + PROFILE_PATTERN_NAME, + SCALER_NAME, +) +from .utils.modeling import get_state_dict_offloaded_model +from .utils.other import compile_regions, compile_regions_deepspeed, is_compiled_module + + +if is_deepspeed_available(): + from .utils import ( + DeepSpeedEngineWrapper, + DeepSpeedOptimizerWrapper, + DeepSpeedSchedulerWrapper, + DummyOptim, + DummyScheduler, + map_pytorch_optim_to_deepspeed, + ) + +if is_megatron_lm_available(): + from .utils import ( + MegatronEngine, + MegatronLMDummyDataLoader, + MegatronLMDummyScheduler, + MegatronLMOptimizerWrapper, + MegatronLMSchedulerWrapper, + megatron_lm_initialize, + megatron_lm_prepare_data_loader, + megatron_lm_prepare_model_optimizer_scheduler, + ) + +from torch.distributed.algorithms.join import Join + + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + import torch_xla.distributed.xla_multiprocessing as xmp + + +if is_npu_available(check_device=False): + import torch_npu # noqa: F401 + + +try: + from torch.optim.lr_scheduler import LRScheduler +except ImportError: + from torch.optim.lr_scheduler import _LRScheduler as LRScheduler + +logger = get_logger(__name__) + +# Sentinel values for defaults +_split_batches = object() +_dispatch_batches = object() +_even_batches = object() +_use_seedable_sampler = object() + + +class Accelerator: + """ + Creates an instance of an accelerator for distributed training or mixed precision training. + + Args: + device_placement (`bool`, *optional*, defaults to `True`): + Whether or not the accelerator should put objects on device (tensors yielded by the dataloader, model, + etc...). + mixed_precision (`str`, *optional*): + Whether or not to use mixed precision training. Choose from 'no','fp16','bf16' or 'fp8'. Will default to + the value in the environment variable `ACCELERATE_MIXED_PRECISION`, which will use the default value in the + accelerate config of the current system or the flag passed with the `accelerate.launch` command. 'fp8' + requires the installation of transformers-engine. + gradient_accumulation_steps (`int`, *optional*, default to 1): + The number of steps that should pass before gradients are accumulated. A number > 1 should be combined with + `Accelerator.accumulate`. If not passed, will default to the value in the environment variable + `ACCELERATE_GRADIENT_ACCUMULATION_STEPS`. Can also be configured through a `GradientAccumulationPlugin`. + cpu (`bool`, *optional*): + Whether or not to force the script to execute on CPU. Will ignore GPU available if set to `True` and force + the execution on one process only. + dataloader_config (`DataLoaderConfiguration`, *optional*): + A configuration for how the dataloaders should be handled in distributed scenarios. + deepspeed_plugin ([`~utils.DeepSpeedPlugin`] or dict of `str`: [`~utils.DeepSpeedPlugin`], *optional*): + Tweak your DeepSpeed related args using this argument. This argument is optional and can be configured + directly using *accelerate config*. If using multiple plugins, use the configured `key` property of each + plugin to access them from `accelerator.state.get_deepspeed_plugin(key)`. Alias for `deepspeed_plugins`. + fsdp_plugin ([`~utils.FullyShardedDataParallelPlugin`], *optional*): + Tweak your FSDP related args using this argument. This argument is optional and can be configured directly + using *accelerate config* + torch_tp_plugin ([`~utils.TorchTensorParallelPlugin`], *optional*): + Deprecated: use `parallelism_config` with `tp_size` instead. + megatron_lm_plugin ([`~utils.MegatronLMPlugin`], *optional*): + Tweak your MegatronLM related args using this argument. This argument is optional and can be configured + directly using *accelerate config* + rng_types (list of `str` or [`~utils.RNGType`]): + The list of random number generators to synchronize at the beginning of each iteration in your prepared + dataloaders. Should be one or several of: + + - `"torch"`: the base torch random number generator + - `"cuda"`: the CUDA random number generator (GPU only) + - `"xla"`: the XLA random number generator (TPU only) + - `"generator"`: the `torch.Generator` of the sampler (or batch sampler if there is no sampler in your + dataloader) or of the iterable dataset (if it exists) if the underlying dataset is of that type. + + Will default to `["torch"]` for PyTorch versions <=1.5.1 and `["generator"]` for PyTorch versions >= 1.6. + log_with (list of `str`, [`~utils.LoggerType`] or [`~tracking.GeneralTracker`], *optional*): + A list of loggers to be setup for experiment tracking. Should be one or several of: + + - `"all"` + - `"tensorboard"` + - `"wandb"` + - `"trackio"` + - `"aim"` + - `"comet_ml"` + - `"mlflow"` + - `"dvclive"` + - `"swanlab"` + If `"all"` is selected, will pick up all available trackers in the environment and initialize them. Can + also accept implementations of `GeneralTracker` for custom trackers, and can be combined with `"all"`. + project_config ([`~utils.ProjectConfiguration`], *optional*): + A configuration for how saving the state can be handled. + project_dir (`str`, `os.PathLike`, *optional*): + A path to a directory for storing data such as logs of locally-compatible loggers and potentially saved + checkpoints. + step_scheduler_with_optimizer (`bool`, *optional*, defaults to `True`): + Set `True` if the learning rate scheduler is stepped at the same time as the optimizer, `False` if only + done under certain circumstances (at the end of each epoch, for instance). + kwargs_handlers (list of [`~utils.KwargsHandler`], *optional*) + A list of [`~utils.KwargsHandler`] to customize how the objects related to distributed training, profiling + or mixed precision are created. See [kwargs](kwargs) for more information. + dynamo_backend (`str` or [`~utils.DynamoBackend`], *optional*, defaults to `"no"`): + Set to one of the possible dynamo backends to optimize your training with torch dynamo. + dynamo_plugin ([`~utils.TorchDynamoPlugin`], *optional*): + A configuration for how torch dynamo should be handled, if more tweaking than just the `backend` or `mode` + is needed. + gradient_accumulation_plugin ([`~utils.GradientAccumulationPlugin`], *optional*): + A configuration for how gradient accumulation should be handled, if more tweaking than just the + `gradient_accumulation_steps` is needed. + + **Available attributes:** + + - **device** (`torch.device`) -- The device to use. + - **distributed_type** ([`~utils.DistributedType`]) -- The distributed training configuration. + - **local_process_index** (`int`) -- The process index on the current machine. + - **mixed_precision** (`str`) -- The configured mixed precision mode. + - **num_processes** (`int`) -- The total number of processes used for training. + - **optimizer_step_was_skipped** (`bool`) -- Whether or not the optimizer update was skipped (because of + gradient overflow in mixed precision), in which + case the learning rate should not be changed. + - **process_index** (`int`) -- The overall index of the current process among all processes. + - **state** ([`~state.AcceleratorState`]) -- The distributed setup state. + - **sync_gradients** (`bool`) -- Whether the gradients are currently being synced across all processes. + - **use_distributed** (`bool`) -- Whether the current configuration is for distributed training. + """ + + def __init__( + self, + device_placement: bool = True, + split_batches: bool = _split_batches, + mixed_precision: PrecisionType | str | None = None, + gradient_accumulation_steps: int = 1, + cpu: bool = False, + dataloader_config: DataLoaderConfiguration | None = None, + deepspeed_plugin: DeepSpeedPlugin | dict[str, DeepSpeedPlugin] | None = None, + fsdp_plugin: FullyShardedDataParallelPlugin | None = None, + torch_tp_plugin: TorchTensorParallelPlugin | None = None, # Deprecate later, warning in `post_init` + megatron_lm_plugin: MegatronLMPlugin | None = None, + rng_types: list[str | RNGType] | None = None, + log_with: str | LoggerType | GeneralTracker | list[str | LoggerType | GeneralTracker] | None = None, + project_dir: str | os.PathLike | None = None, + project_config: ProjectConfiguration | None = None, + gradient_accumulation_plugin: GradientAccumulationPlugin | None = None, + step_scheduler_with_optimizer: bool = True, + kwargs_handlers: list[KwargsHandler] | None = None, + dynamo_backend: DynamoBackend | str | None = None, + dynamo_plugin: TorchDynamoPlugin | None = None, + deepspeed_plugins: DeepSpeedPlugin | dict[str, DeepSpeedPlugin] | None = None, + parallelism_config: ParallelismConfig | None = None, + ): + self.trackers = [] + if project_config is not None: + self.project_configuration = project_config + else: + self.project_configuration = ProjectConfiguration(project_dir=project_dir) + if project_dir is not None and self.project_dir is None: + self.project_configuration.set_directories(project_dir) + + if mixed_precision is not None: + mixed_precision = str(mixed_precision) + if mixed_precision not in PrecisionType: + raise ValueError( + f"Unknown mixed_precision mode: {mixed_precision}. Choose between {PrecisionType.list()}" + ) + if torch_tp_plugin is not None: + warnings.warn( + "`TorchTensorParallelPlugin` is deprecated and will be removed in a future version of Accelerate. " + "Please use the `ParallelismConfig` with `tp_size` instead.", + FutureWarning, + ) + + if dynamo_plugin is not None and dynamo_backend is not None: + raise ValueError("You cannot pass in both `dynamo_plugin` and `dynamo_backend`, please only pass in one.") + if dynamo_backend is not None: + dynamo_plugin = TorchDynamoPlugin(backend=dynamo_backend) + elif dynamo_plugin is None: + dynamo_plugin = TorchDynamoPlugin() + + if deepspeed_plugins is not None and deepspeed_plugin is not None: + raise ValueError("You cannot pass in both `deepspeed_plugins` and `deepspeed_plugin`.") + elif deepspeed_plugin is not None: + deepspeed_plugins = deepspeed_plugin + + if deepspeed_plugins is None: + # First check if we're creating another `Accelerator` w/o setting `deepspeed_plugin` + if ( + AcceleratorState._shared_state != {} + and AcceleratorState().distributed_type == DistributedType.DEEPSPEED + ): + deepspeed_plugins = AcceleratorState().deepspeed_plugins + else: + # init from env variables + deepspeed_plugins = ( + DeepSpeedPlugin() + if os.environ.get("ACCELERATE_USE_DEEPSPEED", "false").lower() == "true" + else None + ) + else: + # If we're creating a second `Accelerator`, users shouldn't be passing in a `deepspeed_plugin` + if ( + AcceleratorState._shared_state != {} + and AcceleratorState().distributed_type == DistributedType.DEEPSPEED + and AcceleratorState().deepspeed_plugins is not None + ): + raise NotImplementedError( + "You cannot pass in a `deepspeed_plugin` when creating a second `Accelerator`. " + "Please make sure the first `Accelerator` is initialized with all the plugins you want to use." + ) + if isinstance(deepspeed_plugins, dict): + for plugin in deepspeed_plugins.values(): + if not isinstance(plugin, DeepSpeedPlugin): + raise TypeError("`deepspeed_plugin` must be a DeepSpeedPlugin object.") + + if deepspeed_plugins is not None: + os.environ["ACCELERATE_USE_DEEPSPEED"] = "true" # use DeepSpeed if plugin is provided + if not is_deepspeed_available(): + raise ImportError("DeepSpeed is not installed => run `pip install deepspeed` or build it from source.") + if is_mlu_available(): + if compare_versions("deepspeed", "<", "0.15.2"): + raise ImportError("DeepSpeed MLU version must be >= 0.15.2. Please update DeepSpeed.") + elif is_musa_available(): + if compare_versions("deepspeed", "<", "0.14.3"): + raise ImportError("DeepSpeed MUSA version must be >= 0.14.3. Please update DeepSpeed.") + elif compare_versions("deepspeed", "<", "0.9.3"): + raise ImportError("DeepSpeed version must be >= 0.9.3. Please update DeepSpeed.") + + self.deepspeed_engine_wrapped = None + + if os.environ.get("ACCELERATE_USE_FSDP", "false").lower() == "true" or isinstance( + fsdp_plugin, FullyShardedDataParallelPlugin + ): + if not is_torch_version(">=", FSDP_PYTORCH_VERSION): + raise ValueError(f"FSDP requires PyTorch >= {FSDP_PYTORCH_VERSION}") + + if fsdp_plugin is None: # init from env variables + fsdp_plugin = ( + FullyShardedDataParallelPlugin() + if os.environ.get("ACCELERATE_USE_FSDP", "false").lower() == "true" + else None + ) + else: + if not isinstance(fsdp_plugin, FullyShardedDataParallelPlugin): + raise TypeError("`fsdp_plugin` must be a FullyShardedDataParallelPlugin object.") + os.environ["ACCELERATE_USE_FSDP"] = "true" # use FSDP if plugin is provided + + if fsdp_plugin is not None and fsdp_plugin.fsdp_version == 2: + if not is_torch_version(">=", FSDP2_PYTORCH_VERSION): + raise ImportError(f"FSDP2 requires PyTorch >= {FSDP2_PYTORCH_VERSION}") + + if megatron_lm_plugin is None: # init from env variables + megatron_lm_plugin = ( + MegatronLMPlugin() if os.environ.get("ACCELERATE_USE_MEGATRON_LM", "false").lower() == "true" else None + ) + else: + if not isinstance(megatron_lm_plugin, MegatronLMPlugin): + raise TypeError("`megatron_lm_plugin` must be a MegatronLMPlugin object.") + os.environ["ACCELERATE_USE_MEGATRON_LM"] = "true" # use MegatronLM if plugin is provided + + if megatron_lm_plugin: + if not is_megatron_lm_available(): + raise ImportError("Megatron is not installed. please build it from source.") + + # Kwargs handlers + self.ddp_handler = None + self.scaler_handler = None + self.init_handler = None + self.fp8_recipe_handler = None + self.ao_recipe_handler = None + self.te_recipe_handler = None + self.msamp_recipe_handler = None + self.autocast_handler = None + self.profile_handler = None + self.has_lomo_optimizer = False + + found_handlers = set() + handler_class_to_attr = { + DistributedDataParallelKwargs: "ddp_handler", + GradScalerKwargs: "scaler_handler", + InitProcessGroupKwargs: "init_handler", + FP8RecipeKwargs: "fp8_recipe_handler", + AutocastKwargs: "autocast_handler", + ProfileKwargs: "profile_handler", + AORecipeKwargs: "ao_recipe_handler", + TERecipeKwargs: "te_recipe_handler", + MSAMPRecipeKwargs: "msamp_recipe_handler", + } + self.has_fp8_handler = False + if kwargs_handlers is not None: + for handler in kwargs_handlers: + assert isinstance(handler, KwargsHandler), ( + f"Unsupported kwargs handler passed: {handler}, must be one that inherits `accelerate.utils.KwargsHandler`." + ) + # Add the handler class to the set of found handlers + if handler.__class__ in found_handlers: + raise ValueError(f"You can only pass one {handler.__class__} in `kwargs_handlers`.") + found_handlers.add(handler.__class__) + handler_attr = handler_class_to_attr[handler.__class__] + setattr(self, handler_attr, handler) + if "recipe_handler" in handler_attr and not self.has_fp8_handler: + self.has_fp8_handler = True + + parallelism_config = self._setup_parallelism_config(parallelism_config, torch_tp_plugin) + + kwargs = self.init_handler.to_kwargs() if self.init_handler is not None else {} + kwargs["parallelism_config"] = parallelism_config + self.state = AcceleratorState( + mixed_precision=mixed_precision, + cpu=cpu, + dynamo_plugin=dynamo_plugin, + deepspeed_plugin=deepspeed_plugins, + fsdp_plugin=fsdp_plugin, + megatron_lm_plugin=megatron_lm_plugin, + _from_accelerator=True, + **kwargs, + ) + + if self.parallelism_config: + self._build_torch_device_mesh(self.parallelism_config) + self.parallelism_config._validate_accelerator(self) + + self.fp8_enabled = self.state.mixed_precision == "fp8" or mixed_precision == "fp8" + + # Check for automatic FP8 recipe creation + if self.fp8_enabled and not self.has_fp8_handler: + if self.fp8_backend == FP8BackendType.AO: + self.ao_recipe_handler = AORecipeKwargs() + elif self.fp8_backend == FP8BackendType.TE: + self.te_recipe_handler = TERecipeKwargs() + elif self.fp8_backend == FP8BackendType.MSAMP: + self.msamp_recipe_handler = MSAMPRecipeKwargs() + elif self.fp8_backend == FP8BackendType.NO: + # Prioritize AO -> TE -> MSAMP + if is_torchao_available(): + logger.info("Found `torchao` installed, using it for FP8 training.") + self.ao_recipe_handler = AORecipeKwargs() + elif is_transformer_engine_available(): + logger.info("Found `transformer-engine` installed, using it for FP8 training.") + self.te_recipe_handler = TERecipeKwargs() + elif is_msamp_available(): + logger.info("Found `msamp` installed, using it for FP8 training.") + self.msamp_recipe_handler = MSAMPRecipeKwargs() + else: + raise ImportError( + "Tried to train with `fp8` and auto-detect backend, but no FP8-compatible backend was installed. " + "Valid backends are: `torchao`, `transformer-engine`, and `msamp`." + ) + self.has_fp8_handler = True + + self.delayed_fp8_autocast = False + if self.has_fp8_handler: + # We already check if FP8 is available during `self.state` + if not self.fp8_enabled and ( + self.distributed_type not in (DistributedType.FSDP, DistributedType.DEEPSPEED) + ): + raise ValueError("Passing in an FP8 configuration requires setting `mixed_precision='fp8'`.") + self.delayed_fp8_autocast = self.fp8_backend == "TE" and self.distributed_type in ( + DistributedType.MULTI_GPU, + DistributedType.FSDP, + ) + + # TODO: S1ro - this is probably gonna be a problem with other fp8 backends too + if ( + self.fp8_backend == FP8BackendType.AO + and self.state.distributed_type == DistributedType.FSDP + and self.state.fsdp_plugin.cpu_ram_efficient_loading + ): + raise ValueError( + "torchao with FSDP2 and cpu_ram_efficient_loading is not supported, setting `cpu_ram_efficient_loading` to False will fix the issue and work as intended." + ) + + trackers = filter_trackers(log_with, self.logging_dir) + if len(trackers) < 1 and log_with is not None: + warnings.warn(f"`log_with={log_with}` was passed but no supported trackers are currently installed.") + self.log_with = trackers + + if ( + (mixed_precision != "bf16") + and getattr(self.state, "downcast_bfloat", False) + and (self.state.distributedType != DistributedType.XLA) + ): + raise ValueError("Can only use `downcast_bf16` when using `mixed_precision='bf16'` and on a TPU") + + if gradient_accumulation_plugin is not None: + if gradient_accumulation_steps != 1: + raise ValueError( + "You can only pass one of `gradient_accumulation_steps` and `gradient_accumulation_plugin`. Please only pass in the created `GradientAccumulationPlugin` object." + ) + else: + gradient_accumulation_steps = int( + parse_choice_from_env("ACCELERATE_GRADIENT_ACCUMULATION_STEPS", gradient_accumulation_steps) + ) + gradient_accumulation_plugin = GradientAccumulationPlugin(num_steps=gradient_accumulation_steps) + + # If using DeepSpeed, update gradient accumulation steps from the DeepSpeed plugin + self.gradient_state = GradientState( + gradient_accumulation_plugin=gradient_accumulation_plugin, + ) + + self.device_placement = device_placement + if dataloader_config is None: + dataloader_config = DataLoaderConfiguration() + self.dataloader_config = dataloader_config + self.step_scheduler_with_optimizer = step_scheduler_with_optimizer + + # Mixed precision attributes + self.scaler = None + self.native_amp = False + if ( + self.state.mixed_precision == "fp16" + and self.device.type != "cpu" + and self.distributed_type not in (DistributedType.DEEPSPEED, DistributedType.MEGATRON_LM) + ): + self.native_amp = True + if self.device.type not in ( + "xpu", + "cuda", + "npu", + "xla", + "mlu", + "musa", + "hpu", + "sdaa", + ) or is_torch_xla_available(check_is_tpu=True): + raise ValueError(f"fp16 mixed precision requires a GPU (not {self.device.type!r}).") + kwargs = self.scaler_handler.to_kwargs() if self.scaler_handler is not None else {} + + # FSDP2 doesn't use ShardedGradScaler, don't want to modify `get_grad_scaler`, rather create a simple utility + if self.is_fsdp2: + self.scaler = get_fsdp2_grad_scaler(**kwargs) + else: + self.scaler = get_grad_scaler(self.distributed_type, **kwargs) + + elif self.state.mixed_precision == "bf16" and self.distributed_type not in ( + DistributedType.DEEPSPEED, + DistributedType.MEGATRON_LM, + ): + if self.device.type in ["cpu", "xpu", "hpu"]: + self.native_amp = True + else: + self.native_amp = is_bf16_available(True) + if mixed_precision == "bf16" and not self.native_amp and not is_torch_xla_available(): + raise ValueError("bf16 mixed precision requires PyTorch >= 1.10 and a supported device.") + + # for DeepSpeed, self.state.mixed_precision is always "bf16", + # see https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L968 and + # https://github.com/huggingface/accelerate/blob/main/src/accelerate/utils/dataclasses.py#L1263. + elif self.fp8_enabled: + # We always enable `native_amp` for FP8 + self.native_amp = True + if self.fp8_backend == FP8BackendType.MSAMP: + if self.distributed_type == DistributedType.FSDP: + raise NotImplementedError( + "`accelerate` + `MS-AMP` + `FSDP` is not supported at this time. " + "Please consider using deepspeed, which is supported." + ) + elif self.distributed_type != DistributedType.DEEPSPEED: + # MS-AMP requires `GradScaler` even with bf16 autocast w/ single GPU or DDP: + self.scaler = get_grad_scaler(**kwargs) + + # Start of internal step tracking + self.step = 0 + + # Internal references to the training objects + self._optimizers = [] + self._models = [] + self._schedulers = [] + self._dataloaders = [] + self._custom_objects = [] + + # Hooks + self._load_model_state_pre_hook = OrderedDict() + self._save_model_state_pre_hook = OrderedDict() + + # RNG Types + self.rng_types = rng_types + if self.rng_types is None: + self.rng_types = ["generator"] + + # Set a flag tensor for early stopping and other breakpoints + self.flag_tensor = None + + check_os_kernel() + + @property + def deepspeed_plugin(self): + """ + Returns the currently active DeepSpeedPlugin. + + If using multiple plugins, the first one will be the active one by default. Manually call + `accelerator.state.select_deepspeed_plugin(key)` to activate a different plugin. + + If deepspeed is not enabled, this will return `None`. + """ + return self.state.deepspeed_plugin + + @property + def use_distributed(self): + """ + Whether the Accelerator is configured for distributed training + """ + return self.state.use_distributed + + @property + def multi_device(self): + return self.use_distributed and self.distributed_type in ( + DistributedType.MULTI_GPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_SDAA, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_NPU, + DistributedType.MULTI_XPU, + DistributedType.MULTI_HPU, + ) + + @property + def distributed_type(self): + return self.state.distributed_type + + @property + def num_processes(self): + return self.state.num_processes + + @property + def process_index(self): + return self.state.process_index + + @property + def local_process_index(self): + return self.state.local_process_index + + @property + def device(self): + return self.state.device + + @property + def split_batches(self): + return self.dataloader_config.split_batches + + @property + def dispatch_batches(self): + return self.dataloader_config.dispatch_batches + + @property + def even_batches(self): + return self.dataloader_config.even_batches + + @even_batches.setter + def even_batches(self, value: bool): + self.dataloader_config.even_batches = value + + @property + def use_seedable_sampler(self): + return self.dataloader_config.use_seedable_sampler + + @property + def non_blocking(self): + return self.dataloader_config.non_blocking + + @property + def use_stateful_dataloader(self): + if hasattr(self.dataloader_config, "use_stateful_dataloader"): + return self.dataloader_config.use_stateful_dataloader + return False + + @property + def project_dir(self): + return self.project_configuration.project_dir + + @property + def logging_dir(self): + return self.project_configuration.logging_dir + + @property + def save_iteration(self): + return self.project_configuration.iteration + + @property + def is_main_process(self): + """True for one process only.""" + return self.state.is_main_process + + @property + def is_local_main_process(self): + """True for one process per server.""" + return self.state.is_local_main_process + + @property + def is_last_process(self): + return self.process_index == self.num_processes - 1 + + @property + def mixed_precision(self): + return self.state.mixed_precision + + @property + def is_fsdp2(self): + return self.state.is_fsdp2 + + @property + def is_composable_parallelism_enabled(self): + return self.is_fsdp2 + + @property + def parallelism_config(self) -> Union[ParallelismConfig, None]: + return self.state.parallelism_config + + @property + def torch_device_mesh(self): + return self.state.device_mesh + + @property + def should_save_model(self): + if (pc := self.parallelism_config) is None: + # shouldn't even happen + return self.state.is_local_main_process + _non_model_shard_dims = { + pc.dp_replicate_enabled: "dp_replicate", + pc.cp_enabled: "cp", + } + + # return all( + # self.torch_device_mesh[dim].get_local_rank() == 0 for key, dim in non_model_shard_dims.items() if key + # ) + # TODO: S1ro - this is a temporary solution until we figure out why `save_safe_file` is slow when not all processes + return True + + def _setup_parallelism_config( + self, parallelism_config: ParallelismConfig | None, torch_tp_plugin: TorchTensorParallelPlugin | None + ): + if parallelism_config is None: + if PartialState._shared_state != {} and PartialState().parallelism_config is not None: + if os.environ.get("ACCELERATE_USE_PARALLELISM_CONFIG", "false") == "true": + raise ValueError( + "Partial state contains a `parallelism_config` which is not None, but you configured `parallelism_config` from the `accelerate launch` CLI. We don't know which to use, please remove one of those configuration methods." + ) + parallelism_config = PartialState().parallelism_config + else: + # TODO: Remove after deprecating tp_plugin + tp_size = None if torch_tp_plugin is None else torch_tp_plugin.tp_size + parallelism_config = ParallelismConfig(tp_size=tp_size) + + return parallelism_config + + @property + def tensor_parallel_rank(self) -> int: + """ + Returns the local rank for tensor parallelism. If tensor parallelism is configured but not enabled, returns 0 + since all ranks are assumed to be the same. + """ + if self.parallelism_config: + if self.parallelism_config.tp_enabled: + return self.torch_device_mesh.get_local_rank("tp") + return 0 + raise RuntimeError("Tensor parallelism is not configured. Set `parallelism_config` first.") + + @property + def pipeline_parallel_rank(self) -> int: + """ + Pipeline parallelism is not supported yet. + """ + raise NotImplementedError("Pipeline parallelism is currently not supported in Accelerate.") + + @property + def context_parallel_rank(self) -> int: + """ + Context parallelism is not supported yet. + """ + raise NotImplementedError("Context parallelism is currently not supported in Accelerate.") + + @property + def data_parallel_rank(self) -> int: + """ + Returns the local rank for replicate-based data parallelism. If replicate-based data parallelism is configured + but not enabled, returns 0 since all ranks are assumed to be the same. + """ + if self.parallelism_config: + if self.parallelism_config.dp_replicate_enabled: + return self.torch_device_mesh.get_local_rank("dp_replicate") + return 0 + raise RuntimeError("Data parallelism is not configured. Set `parallelism_config` first.") + + @property + def data_parallel_shard_rank(self) -> int: + """ + Returns the local rank for shard-based data parallelism. If shard-based data parallelism is configured but not + enabled, returns 0 since all ranks are assumed to be the same. + """ + if self.parallelism_config: + if self.parallelism_config.dp_shard_enabled: + return self.torch_device_mesh.get_local_rank("dp_shard") + return 0 + raise RuntimeError("Shard-based data parallelism is not configured. Set `parallelism_config` first.") + + def _build_torch_device_mesh(self, parallelism_config): + if PartialState._shared_state != {} and getattr(PartialState(), "device_mesh", None) is not None: + device_mesh = PartialState().device_mesh + else: + device_mesh = parallelism_config.build_device_mesh(self.device.type) + self.state.device_mesh = device_mesh + PartialState().device_mesh = device_mesh + + @contextmanager + def split_between_processes(self, inputs: list | tuple | dict | torch.Tensor, apply_padding: bool = False): + """ + Splits `input` between `self.num_processes` quickly and can be then used on that process. Useful when doing + distributed inference, such as with different prompts. + + Note that when using a `dict`, all keys need to have the same number of elements. + + Args: + inputs (`list`, `tuple`, `torch.Tensor`, or `dict` of `list`/`tuple`/`torch.Tensor`): + The input to split between processes. + apply_padding (`bool`, `optional`, defaults to `False`): + Whether to apply padding by repeating the last element of the input so that all processes have the same + number of elements. Useful when trying to perform actions such as `Accelerator.gather()` on the outputs + or passing in less inputs than there are processes. If so, just remember to drop the padded elements + afterwards. + + Example: + + ```python + # Assume there are two processes + from accelerate import Accelerator + + accelerator = Accelerator() + with accelerator.split_between_processes(["A", "B", "C"]) as inputs: + print(inputs) + # Process 0 + ["A", "B"] + # Process 1 + ["C"] + + with accelerator.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs: + print(inputs) + # Process 0 + ["A", "B"] + # Process 1 + ["C", "C"] + ``` + """ + with PartialState().split_between_processes(inputs, apply_padding=apply_padding) as inputs: + yield inputs + + def on_main_process(self, function: Callable[..., Any] = None): + """ + A decorator that will run the decorated function on the main process only. Can also be called using the + `PartialState` class. + + Args: + function (`Callable`): The function to decorate. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + + + >>> @accelerator.on_main_process + ... def print_something(): + ... print("This will be printed by process 0 only.") + + + >>> print_something() + "This will be printed by process 0 only" + ``` + """ + # For times when the `Accelerator` object itself utilizes this decorator. + if function is None: + if "Accelerator." in self.__qualname__: + function = self + else: + raise ValueError( + "The `on_main_process` decorator must be called with a function on an instantiated `Accelerator` object." + ) + + def _inner(*args, **kwargs): + return PartialState().on_main_process(function)(*args, **kwargs) + + return _inner + + def on_local_main_process(self, function: Callable[..., Any] = None): + """ + A decorator that will run the decorated function on the local main process only. Can also be called using the + `PartialState` class. + + Args: + function (`Callable`): The function to decorate. + + Example: + ```python + # Assume we have 2 servers with 4 processes each. + from accelerate import Accelerator + + accelerator = Accelerator() + + + @accelerator.on_local_main_process + def print_something(): + print("This will be printed by process 0 only on each server.") + + + print_something() + # On server 1: + "This will be printed by process 0 only" + # On server 2: + "This will be printed by process 0 only" + ``` + """ + # For times when the `Accelerator` object itself utilizes this decorator. + if function is None: + if "Accelerator." in self.__qualname__: + function = self + else: + raise ValueError( + "The `on_local_main_process` decorator must be called with a function on an instantiated `Accelerator` object." + ) + + def _inner(*args, **kwargs): + return PartialState().on_local_main_process(function)(*args, **kwargs) + + return _inner + + def on_last_process(self, function: Callable[..., Any]): + """ + A decorator that will run the decorated function on the last process only. Can also be called using the + `PartialState` class. + + Args: + function (`Callable`): The function to decorate. + + Example: + ```python + # Assume we have 4 processes. + from accelerate import Accelerator + + accelerator = Accelerator() + + + @accelerator.on_last_process + def print_something(): + print(f"Printed on process {accelerator.process_index}") + + + print_something() + "Printed on process 3" + ``` + """ + # For times when the `Accelerator` object itself utilizes this decorator. + if function is None: + if "Accelerator." in self.__qualname__: + function = self + else: + raise ValueError( + "The `on_last_process` decorator must be called with a function on an instantiated `Accelerator` object." + ) + + def _inner(*args, **kwargs): + return PartialState().on_last_process(function)(*args, **kwargs) + + return _inner + + def on_process(self, function: Callable[..., Any] = None, process_index: int = None): + """ + A decorator that will run the decorated function on a given process index only. Can also be called using the + `PartialState` class. + + Args: + function (`Callable`, `optional`): + The function to decorate. + process_index (`int`, `optional`): + The index of the process on which to run the function. + + Example: + ```python + # Assume we have 4 processes. + from accelerate import Accelerator + + accelerator = Accelerator() + + + @accelerator.on_process(process_index=2) + def print_something(): + print(f"Printed on process {accelerator.process_index}") + + + print_something() + "Printed on process 2" + ``` + """ + # Initial construction of the decorator. + if (self is not None) and (process_index is not None) and (function is None): + return partial(self.on_process, process_index=process_index) + # For times when the `Accelerator` object itself utilizes this decorator. + if function is None: + if "Accelerator." in self.__qualname__: + function = self + else: + raise ValueError( + "The `on_main_process` decorator must be called with a function on an instantiated `Accelerator` object." + ) + + def _inner(*args, **kwargs): + return PartialState().on_process(function, process_index)(*args, **kwargs) + + return _inner + + def on_local_process(self, function: Callable[..., Any] = None, local_process_index: int = None): + """ + A decorator that will run the decorated function on a given local process index only. Can also be called using + the `PartialState` class. + + Args: + function (`Callable`, *optional*): + The function to decorate. + local_process_index (`int`, *optional*): + The index of the local process on which to run the function. + + Example: + ```python + # Assume we have 2 servers with 4 processes each. + from accelerate import Accelerator + + accelerator = Accelerator() + + + @accelerator.on_local_process(local_process_index=2) + def print_something(): + print(f"Printed on process {accelerator.local_process_index}") + + + print_something() + # On server 1: + "Printed on process 2" + # On server 2: + "Printed on process 2" + ``` + """ + # Initial construction of the decorator. + if (self is not None) and (local_process_index is not None) and (function is None): + return partial(self.on_local_process, local_process_index=local_process_index) + # For times when the `Accelerator` object itself utilizes this decorator. + if function is None: + if "Accelerator." in self.__qualname__: + function = self + else: + raise ValueError( + "The `on_main_process` decorator must be called with a function on an instantiated `Accelerator` object." + ) + + def _inner(*args, **kwargs): + return PartialState().on_local_process(function, local_process_index)(*args, **kwargs) + + return _inner + + @contextmanager + def main_process_first(self): + """ + Lets the main process go first inside a with block. + + The other processes will enter the with block after the main process exits. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> with accelerator.main_process_first(): + ... # This will be printed first by process 0 then in a seemingly + ... # random order by the other processes. + ... print(f"This will be printed by process {accelerator.process_index}") + ``` + """ + with self.state.main_process_first(): + yield + + @contextmanager + def local_main_process_first(self): + """ + Lets the local main process go inside a with block. + + The other processes will enter the with block after the main process exits. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> with accelerator.local_main_process_first(): + ... # This will be printed first by local process 0 then in a seemingly + ... # random order by the other processes. + ... print(f"This will be printed by process {accelerator.local_process_index}") + ``` + """ + with self.state.local_main_process_first(): + yield + + @contextmanager + def no_sync(self, model): + """ + A context manager to disable gradient synchronizations across DDP processes by calling + `torch.nn.parallel.DistributedDataParallel.no_sync`. + + If `model` is not in DDP, this context manager does nothing + + Args: + model (`torch.nn.Module`): + PyTorch Module that was prepared with `Accelerator.prepare` + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> dataloader, model, optimizer = accelerator.prepare(dataloader, model, optimizer) + >>> input_a = next(iter(dataloader)) + >>> input_b = next(iter(dataloader)) + + >>> with accelerator.no_sync(): + ... outputs = model(input_a) + ... loss = loss_func(outputs) + ... accelerator.backward(loss) + ... # No synchronization across processes, only accumulate gradients + >>> outputs = model(input_b) + >>> accelerator.backward(loss) + >>> # Synchronization across all processes + >>> optimizer.step() + >>> optimizer.zero_grad() + ``` + """ + context = contextlib.nullcontext + if self.use_distributed: + if self.distributed_type != DistributedType.DEEPSPEED or self.state.deepspeed_plugin.zero_stage < 2: + context = getattr(model, "no_sync", context) + + with context(): + yield + + @staticmethod + @contextmanager + def trigger_sync_in_backward(model): + """Trigger the sync of the gradients in the next backward pass of the model after multiple forward passes under + `Accelerator.no_sync` (only applicable in multi-GPU scenarios). + + If the script is not launched in distributed mode, this context manager does nothing. + + Args: + model (`torch.nn.Module`): + The model for which to trigger the gradient synchronization. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> dataloader, model, optimizer = accelerator.prepare(dataloader, model, optimizer) + + >>> with accelerator.no_sync(): + ... loss_a = loss_func(model(input_a)) # first forward pass + ... loss_b = loss_func(model(input_b)) # second forward pass + >>> accelerator.backward(loss_a) # No synchronization across processes, only accumulate gradients + >>> with accelerator.trigger_sync_in_backward(model): + ... accelerator.backward(loss_b) # Synchronization across all processes + >>> optimizer.step() + >>> optimizer.zero_grad() + ``` + """ + if not isinstance(model, torch.nn.parallel.DistributedDataParallel): + yield + return + + old_require_backward_grad_sync = model.require_backward_grad_sync + old_require_forward_param_sync = model.require_forward_param_sync + + # EXPERIMENTAL: This will force grad sync during `backward()`, but it is unknown if it breaks other DDP features. + # https://github.com/pytorch/pytorch/blob/e1502c0cdbfd17548c612f25d5a65b1e4b86224d/torch/nn/parallel/distributed.py#L1453-L1466 + model.require_backward_grad_sync = True + model.require_forward_param_sync = True + # https://github.com/pytorch/pytorch/blob/e1502c0cdbfd17548c612f25d5a65b1e4b86224d/torch/csrc/distributed/c10d/reducer.cpp#L1371-L1402 + model.reducer.prepare_for_backward([]) + try: + yield + finally: + model.require_backward_grad_sync = old_require_backward_grad_sync + model.require_forward_param_sync = old_require_forward_param_sync + + def _do_sync(self): + "Sets the right `sync_gradients` context and either resets or increases `self.step`" + if self.gradient_state.sync_with_dataloader and self.gradient_state.end_of_dataloader: + self.step = 0 + self.gradient_state._set_sync_gradients(True) + else: + self.step += 1 + self.gradient_state._set_sync_gradients((self.step % self.gradient_state.num_steps) == 0) + + @property + def sync_gradients(self): + return self.gradient_state.sync_gradients + + @sync_gradients.setter + def sync_gradients(self, sync_gradients): + self.gradient_state.sync_gradients = sync_gradients + + @property + def gradient_accumulation_steps(self): + return self.gradient_state.num_steps + + @gradient_accumulation_steps.setter + def gradient_accumulation_steps(self, gradient_accumulation_steps): + self.gradient_state.plugin_kwargs.update({"num_steps": gradient_accumulation_steps}) + + @contextmanager + def accumulate(self, *models): + """ + A context manager that will lightly wrap around and perform gradient accumulation automatically + + Args: + *models (list of `torch.nn.Module`): + PyTorch Modules that were prepared with `Accelerator.prepare`. Models passed to `accumulate()` will + skip gradient syncing during backward pass in distributed training + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator(gradient_accumulation_steps=1) + >>> dataloader, model, optimizer, scheduler = accelerator.prepare(dataloader, model, optimizer, scheduler) + + >>> for input, output in dataloader: + ... with accelerator.accumulate(model): + ... outputs = model(input) + ... loss = loss_func(outputs) + ... loss.backward() + ... optimizer.step() + ... scheduler.step() + ... optimizer.zero_grad() + ``` + """ + self._do_sync() + + allow_gradient_sync = ( + self.sync_gradients # must sync if sync gradients need to complete an optimizer step + or ( + # the no_sync context stops the gradients from reducing during distributed training + # bringing speedup (potentially at some costs). Here, no_sync can be prevented + # by setting sync_each_batch = True. + self.use_distributed # only relevant in distributed settings + and self.gradient_state.plugin_kwargs.get("sync_each_batch", False) + ) + ) + with contextlib.ExitStack() as cm_stack: + for m in models: + cm_stack.enter_context(contextlib.nullcontext() if allow_gradient_sync else self.no_sync(m)) + yield + + @contextmanager + def join_uneven_inputs(self, joinables, even_batches=None): + """ + A context manager that facilitates distributed training or evaluation on uneven inputs, which acts as a wrapper + around `torch.distributed.algorithms.join`. This is useful when the total batch size does not evenly divide the + length of the dataset. + + Args: + joinables (`list[torch.distributed.algorithms.Joinable]`): + A list of models or optimizers that subclass `torch.distributed.algorithms.Joinable`. Most commonly, a + PyTorch Module that was prepared with `Accelerator.prepare` for DistributedDataParallel training. + even_batches (`bool`, *optional*) + If set, this will override the value of `even_batches` set in the `Accelerator`. If it is not provided, + the default `Accelerator` value wil be used. + + + + `join_uneven_inputs` is only supported for Distributed Data Parallel training on multiple GPUs. For any other + configuration, this method will have no effect. + + + + + + Overidding `even_batches` will not affect iterable-style data loaders. + + + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator(even_batches=True) + >>> ddp_model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader) + + >>> with accelerator.join_uneven_inputs([ddp_model], even_batches=False): + ... for input, output in dataloader: + ... outputs = model(input) + ... loss = loss_func(outputs) + ... loss.backward() + ... optimizer.step() + ... optimizer.zero_grad() + ``` + """ + if self.multi_device: + dl_even_batches_values = [] + + if even_batches is not None: + iterable_dl_seen = False + # override value in batch sampler for map-style datasets + for dl_idx, dl in enumerate(self._dataloaders): + if isinstance(dl, DataLoaderDispatcher): + iterable_dl_seen = True + continue + dl_even_batches_values.append((dl_idx, dl.batch_sampler.even_batches)) + dl.batch_sampler.even_batches = even_batches + + if iterable_dl_seen: + warnings.warn( + "Overridding even_batches is only supported for map-style datasets, yet some dataloaders given were iterable" + ) + else: + even_batches = self.even_batches + + enable_join = False if even_batches else True + try: + with Join(joinables, enable=enable_join, throw_on_early_termination=False): + yield + finally: + # reset any batch samplers that have been modified + for dl_idx, even_batches_value in dl_even_batches_values: + self._dataloaders[dl_idx].batch_sampler.even_batches = even_batches_value + else: + # Even when disabled, Join expects models to subclass Joinable, so skip entirely for single process runs + if self.distributed_type != DistributedType.NO: + warnings.warn( + "Joining uneven inputs is only supported for multi-GPU training, as a result `join_uneven_inputs` will have no effect." + ) + + with contextlib.nullcontext(joinables): + yield + + def print(self, *args, **kwargs): + """ + Drop in replacement of `print()` to only print once per server. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> accelerator.print("Hello world!") + ``` + """ + self.state.print(*args, **kwargs) + + def _prepare_one(self, obj, first_pass=False, device_placement=None): + # First pass of preparation: DataLoader, model, optimizer + if first_pass: + if isinstance(obj, torch.utils.data.DataLoader): + return self.prepare_data_loader(obj, device_placement=device_placement) + elif isinstance(obj, torch.nn.Module): + return self.prepare_model(obj, device_placement=device_placement) + elif isinstance(obj, torch.optim.Optimizer): + optimizer = self.prepare_optimizer(obj, device_placement=device_placement) + return optimizer + # Second pass of preparation: LR scheduler (which need the full list of optimizers) + elif isinstance(obj, LRScheduler): + scheduler = self.prepare_scheduler(obj) + return scheduler + # Return the unprocessed object if previous criteria was not met + return obj + + def prepare(self, *args, device_placement=None): + """ + Prepare all objects passed in `args` for distributed training and mixed precision, then return them in the same + order. + + Args: + *args (list of objects): + Any of the following type of objects: + + - `torch.utils.data.DataLoader`: PyTorch Dataloader + - `torch.nn.Module`: PyTorch Module + - `torch.optim.Optimizer`: PyTorch Optimizer + - `torch.optim.lr_scheduler.LRScheduler`: PyTorch LR Scheduler + + device_placement (`list[bool]`, *optional*): + Used to customize whether automatic device placement should be performed for each object passed. Needs + to be a list of the same length as `args`. Not compatible with DeepSpeed or FSDP. + + + + You don't need to prepare a model if you only use it for inference without any kind of mixed precision + + + + Examples: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> # Assume a model, optimizer, data_loader and scheduler are defined + >>> model, optimizer, data_loader, scheduler = accelerator.prepare(model, optimizer, data_loader, scheduler) + ``` + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> # Assume a model, optimizer, data_loader and scheduler are defined + >>> device_placement = [True, True, False, False] + >>> # Will place the first two items passed in automatically to the right device but not the last two. + >>> model, optimizer, data_loader, scheduler = accelerator.prepare( + ... model, optimizer, data_loader, scheduler, device_placement=device_placement + ... ) + ``` + """ + if device_placement is None: + device_placement = [None for _ in args] + elif self.distributed_type in (DistributedType.DEEPSPEED, DistributedType.MEGATRON_LM): + raise ValueError("You can't customize device placements with DeepSpeed or Megatron-LM.") + elif len(device_placement) != len(args): + raise ValueError( + f"`device_placement` should be a list with {len(args)} elements (the number of objects passed)." + ) + + for obj in args: + # TODO: Look at enabling native TP training directly with a proper config + if ( + isinstance(obj, torch.nn.Module) + and self.verify_device_map(obj) + and self.distributed_type != DistributedType.NO + and os.environ.get("ACCELERATE_BYPASS_DEVICE_MAP", "false") != "true" + ): + raise ValueError( + "You can't train a model that has been loaded with `device_map='auto'` in any distributed mode." + " Please rerun your script specifying `--num_processes=1` or by launching with `python {{myscript.py}}`." + ) + + if self.distributed_type == DistributedType.DEEPSPEED: + model_count = 0 + for obj in args: + if isinstance(obj, torch.nn.Module): + model_count += 1 + if model_count > 1: + raise AssertionError( + "You can't use same `Accelerator()` instance with multiple models when using DeepSpeed" + ) + + # On TPUs, putting the model on the XLA device will create new parameters, so the corresponding optimizer will + # have parameters disconnected from the model (so no training :-( ). + # If the model and optimizer have parameters on different devices we raise an error. + if self.distributed_type == DistributedType.XLA: + model_device, optimizer_device = self._get_devices() + if model_device is not None and optimizer_device is not None and model_device != optimizer_device: + raise ValueError( + "The model and the optimizer parameters are not on the same device, which probably means you " + "created an optimizer around your model **before** putting on the device. Make sure the line " + "model.to(device) is before the optimizer creation in your script or remove it entirely and use " + "the flag default value for `device_placement` in your `Accelerator` to let it handle that " + "part for you." + ) + + if self.is_fsdp2: + model_count = 0 + optimizer_count = 0 + for i, obj in enumerate(args): + if isinstance(obj, torch.nn.Module): + model_count += 1 + elif isinstance(obj, torch.optim.Optimizer): + optimizer_count += 1 + + # This needs to be written as such, so that passing other objects other than models/optimizers doesn't raise an error + if (model_count < 1 and optimizer_count > 0) or (model_count > 0 and optimizer_count < 1): + raise ValueError( + "When using FSDP2, a model and optimizer must be passed together to `Accelerator.prepare()`" + " as the optimizer needs to have its parameters modified after the model is converted." + ) + if model_count > 1: + raise ValueError("Only one model is supported when using FSDP2") + + # If we're dealing with device placement, this deals with that by... + tpu_should_fix_optimizer = self.device_placement and self.distributed_type == DistributedType.XLA + + if tpu_should_fix_optimizer: + # 1. grabbing old model parameters + old_named_params = self._get_named_parameters(*args, drop_refs=False) + + if self.distributed_type in [DistributedType.MULTI_CPU, DistributedType.MULTI_XPU, DistributedType.NO]: + if ( + is_torch_version("<", "2.7.0") + and (self.device.type == "cpu" or self.device.type == "xpu") + and self.state.use_ipex + ): + logger.warning( + "You are using lower version of PyTorch(< 2.7.0) with ipex acceleration on Intel CPU or XPU, Intel has upstreamed most of the optimizations into stock PyTorch from 2.7.0, we enourage you to install the latest stock PyTorch and enjoy the out-of-experience on Intel CPU/XPU." + ) + args = self._prepare_ipex(*args) + if self.parallelism_config and self.parallelism_config.tp_enabled: + args = self._prepare_tp(*args) + + if self.parallelism_config and self.parallelism_config.cp_enabled: + args = self._prepare_cp(*args) + + if self.fp8_backend == FP8BackendType.TE: + args = self._prepare_te(*args) + elif self.fp8_backend == FP8BackendType.AO: + args = self._prepare_ao(*args) + if self.distributed_type == DistributedType.DEEPSPEED: + result = self._prepare_deepspeed(*args) + elif self.distributed_type == DistributedType.MEGATRON_LM: + result = self._prepare_megatron_lm(*args) + elif self.is_fsdp2: + result = self._prepare_fsdp2(*args) + else: + if self.fp8_backend == FP8BackendType.MSAMP: + args, device_placement = self._prepare_msamp(*args, device_placement=device_placement) + result = tuple( + self._prepare_one(obj, first_pass=True, device_placement=d) for obj, d in zip(args, device_placement) + ) + result = tuple(self._prepare_one(obj, device_placement=d) for obj, d in zip(result, device_placement)) + if tpu_should_fix_optimizer: + # 2. grabbing new model parameters + new_named_params = self._get_named_parameters(*result) + # 3. building a map from the first to the second + mapping = {p: new_named_params[n] for n, p in old_named_params.items()} + # 4. using that map to update the parameters of the optimizer + for obj in result: + if isinstance(obj, torch.optim.Optimizer): + obj._switch_parameters(mapping) + + for item in result: + if any( + item in container + for container in (self._dataloaders, self._models, self._optimizers, self._schedulers) + ): + item._is_accelerate_prepared = True + + return result if len(result) > 1 else result[0] + + def _prepare_tp(self, *args): + # First pass: prepare everything except schedulers (and model, which is prepared separately below) + result = [ + self._prepare_one(obj, first_pass=True) if not isinstance(obj, torch.nn.Module) else obj for obj in args + ] + + # Second pass: prepare schedulers + result = [self._prepare_one(obj) if not isinstance(obj, torch.nn.Module) else obj for obj in result] + + device_mesh = self.torch_device_mesh + + for arg in result: + if not isinstance(arg, torch.nn.Module): + continue + + from torch.distributed.tensor import DTensor, Replicate + from transformers.integrations.tensor_parallel import ReplicateParallel + + model: torch.nn.Module = arg + tp_plan = ReplicateParallel + + for name, param in model.named_parameters(): + if isinstance(param, DTensor): + continue + + dp = DTensor.from_local(param, device_mesh=device_mesh["tp"], placements=[Replicate()]) + param_name, param_type = name.rsplit(".", 1) + module_to_tp = model.get_submodule(param_name) + + tp_plan().prepare_module_tp(module_to_tp, device_mesh["tp"]) + if not isinstance(dp, torch.nn.Parameter): + dp = torch.nn.Parameter(dp, requires_grad=param.requires_grad) + setattr(module_to_tp, param_type, dp) + + return args + + def _prepare_cp(self, *args): + from torch.distributed.tensor.experimental import context_parallel + from torch.distributed.tensor.experimental._attention import set_rotate_method + + cp_comm_strategy = self.parallelism_config.cp_handler.cp_comm_strategy + set_rotate_method(cp_comm_strategy) + + self._cp_context = functools.partial(context_parallel, mesh=self.torch_device_mesh["cp"]) + + for arg in args: + if isinstance(arg, torch.nn.Module): + _attach_context_parallel_hooks(arg) + + return args + + def _prepare_fsdp2(self, *args): + # First pass: prepare everything except schedulers (and model, which is prepared separately below) + result = [ + self._prepare_one(obj, first_pass=True) if not isinstance(obj, torch.nn.Module) else obj for obj in args + ] + + # Second pass: prepare schedulers + result = [self._prepare_one(obj) if not isinstance(obj, torch.nn.Module) else obj for obj in result] + + # Prepare the model + model_index, model = None, None + for i, obj in enumerate(result): + if isinstance(obj, torch.nn.Module): + model_index, model = i, obj + + # Invariant: if we have a model, we also have an optimizer (checked in `prepare`) + if model_index is None: + return tuple(result) + + # Needs to be done first, to make sure AC + fully_shard will work as expected + self.state.fsdp_plugin.set_auto_wrap_policy(model) + + # Apply AC if needed + if self.state.fsdp_plugin.activation_checkpointing: + model = fsdp2_apply_ac(self, model) + + # Apply compile if needed, has to be *after* applying AC + # Copied from: `accelerator.prepare_model` ~ L1804 + if self.state.dynamo_plugin.backend != DynamoBackend.NO and not is_compiled_module(model): + if self.state.dynamo_plugin.use_regional_compilation: + model = compile_regions(model, **self.state.dynamo_plugin.to_kwargs()) + else: + model = torch.compile(model, **self.state.dynamo_plugin.to_kwargs()) + + # Get old params and canonicalize - we cannonicalize to have the mapping easy + old_named_params = fsdp2_canonicalize_names(self._get_named_parameters(*tuple(result), drop_refs=True)) + + # Swap the optimizer parameters with empty, so `fully_shard` after will not allocate too much memory + from torch.distributed.tensor import DTensor + + for obj in result: + if isinstance(obj, torch.optim.Optimizer): + for param_group in obj.param_groups: + for i, p in enumerate(param_group["params"]): + # We drop a reference to the original param here, so that _move_states_to_device triggers a reallocation + # We reassign the data_ptr to the original param, so that we preserve the mapping to the new ones + param_group["params"][i] = torch.empty(1, dtype=p.dtype, device=p.device) + param_group["params"][i].data_ptr = ( + p._local_tensor.data_ptr() if isinstance(p, DTensor) else p.data_ptr() + ) + + self._models.append(model) + + # Prepare everything FSDP2 related for the model (except AC) + model = fsdp2_prepare_model(self, model) + + # Remove the old model from the list + if len(self._models) > 1 and (self._models[-2] is self._models[-1]): + del self._models[-2] + + # Replace the old model with the new one (shouldn't be needed as everything should be in place) + result[model_index] = model + + # Get new params and canonicalize + new_named_params = fsdp2_canonicalize_names(self._get_named_parameters(*result)) + # Build a map from old to new params + mapping = {p: new_named_params[n] for n, p in old_named_params.items()} + # Update the optimizer parameters + for obj in result: + if isinstance(obj, torch.optim.Optimizer): + fsdp2_switch_optimizer_parameters(obj, mapping) + + return result + + def prepare_model(self, model: torch.nn.Module, device_placement: bool = None, evaluation_mode: bool = False): + """ + Prepares a PyTorch model for training in any distributed setup. It is recommended to use + [`Accelerator.prepare`] instead. + + Args: + model (`torch.nn.Module`): + A PyTorch model to prepare. You don't need to prepare a model if it is used only for inference without + any kind of mixed precision + device_placement (`bool`, *optional*): + Whether or not to place the model on the proper device. Will default to `self.device_placement`. + evaluation_mode (`bool`, *optional*, defaults to `False`): + Whether or not to set the model for evaluation only, by just applying mixed precision and + `torch.compile` (if configured in the `Accelerator` object). + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> # Assume a model is defined + >>> model = accelerator.prepare_model(model) + ``` + """ + if device_placement is None: + device_placement = self.device_placement and self.distributed_type != DistributedType.FSDP + + self._models.append(model) + + # TODO: Look at enabling native TP training directly with a proper config + if ( + self.verify_device_map(model) + and self.distributed_type != DistributedType.NO + and os.environ.get("ACCELERATE_BYPASS_DEVICE_MAP", "false") != "true" + ): + raise ValueError( + "You can't train a model that has been loaded with `device_map='auto'` in any distributed mode." + " Please rerun your script specifying `--num_processes=1` or by launching with `python {{myscript.py}}`." + ) + + if self.native_amp: + model._original_forward = model.forward + autocast_context = get_mixed_precision_context_manager(self.native_amp, self.autocast_handler) + # NOTE: MS-AMP adds `__func__` already to `model.forward`, so we should always use `model.forward` + if self.fp8_backend == FP8BackendType.MSAMP or not hasattr(model.forward, "__func__"): + model_forward_func = model.forward + model.forward = convert_outputs_to_fp32(autocast_context(model_forward_func)) + else: + model_forward_func = model.forward.__func__ + new_forward = autocast_context(model_forward_func) + model.forward = MethodType(new_forward, model) + model.forward = MethodType(convert_outputs_to_fp32(model.forward.__func__), model) + + # We prepare TE after, allowing for bf16 autocast to happen first + if self.fp8_backend == FP8BackendType.TE and not self.delayed_fp8_autocast: + model = apply_fp8_autowrap(model, self.te_recipe_handler or self.fp8_recipe_handler) + + if (getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False)) and getattr( + model, "hf_device_map", False + ): + model_devices = set(model.hf_device_map.values()) + if len(model_devices) > 1 and self.distributed_type != DistributedType.NO: + raise ValueError( + "You can't train a model that has been loaded in 8-bit or 4-bit precision on multiple devices in any distributed mode." + " In order to use 8-bit or 4-bit models that have been loaded across multiple GPUs the solution is to use Naive Pipeline Parallelism." + " Therefore you should not specify that you are under any distributed regime in your accelerate config." + ) + elif len(model_devices) == 1: + current_device = list(model_devices)[0] + if isinstance(current_device, torch.device): + current_device_index = current_device.index + elif isinstance(current_device, str): + current_device_index = torch.device(current_device).index + else: + current_device_index = current_device + + if self.device.type == "cpu" and is_bitsandbytes_multi_backend_available(): + # bnb with multi-backend supports CPU which don't need to check index. + pass + elif torch.device(current_device_index) != self.device: + # if on the first device (GPU 0) we don't care + if (self.device.index is not None) or (current_device_index != 0): + raise ValueError( + "You can't train a model that has been loaded in 8-bit or 4-bit precision on a different device than the one " + "you're training on. Make sure you loaded the model on the correct device using for example `device_map={'':torch.cuda.current_device()}` or `device_map={'':torch.xpu.current_device()}`" + ) + if ( + ("cpu" in model_devices and not is_bitsandbytes_multi_backend_available()) + or ("cpu" in model_devices and is_xpu_available()) + or "disk" in model_devices + ): + raise ValueError( + "You can't train a model that has been loaded in 8-bit or 4-bit precision with CPU or disk offload. " + "If you want train the 8-bit or 4-bit model in CPU, please install bitsandbytes with multi-backend, see https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backend" + ) + elif device_placement and not self.verify_device_map(model): + model = model.to(self.device) + if not evaluation_mode: + if self.multi_device and not (self.parallelism_config and self.parallelism_config.tp_enabled): + if model_has_dtensor(model): + raise ValueError( + "Your model contains `DTensor` parameters, which is incompatible with DDP. Maybe you loaded your model with `device_map='auto'`? Specify `device_map='cuda'` or 'cpu' instead." + ) + if any(p.requires_grad for p in model.parameters()): + kwargs = self.ddp_handler.to_kwargs() if self.ddp_handler is not None else {} + # TODO: Look at enabling native TP training directly with a proper config + if os.environ.get("ACCELERATE_BYPASS_DEVICE_MAP", "false") != "true": + if self.device.type == "hpu": + device_ids, output_device = [self.device.index], self.device.index + else: + device_ids, output_device = [self.local_process_index], self.local_process_index + else: + device_ids, output_device = None, None + model = torch.nn.parallel.DistributedDataParallel( + model, device_ids=device_ids, output_device=output_device, **kwargs + ) + if self.ddp_handler is not None: + self.ddp_handler.register_comm_hook(model) + elif self.parallelism_config and self.parallelism_config.tp_enabled: + if not hasattr(model, "tp_size"): + raise NotImplementedError( + "Model should undergo tensor parallel before passing it to accelerate." + "You can use .from_pretrained(..., tp_plan='auto') if the model supports" + ) + if model.tp_size != self.parallelism_config.tp_size: + raise ValueError( + f"tp_size in the plugin {self.parallelism_config.tp_size} should be same as model's tp size {model.tp_size}" + ) + elif self.is_fsdp2: + raise ValueError( + "FSDP2 preparation should be done via `accelerate.prepare()`, as it requires a model and an optimizer." + ) + + elif self.distributed_type == DistributedType.FSDP: + # We need to fix the optimizer *before* sharding the model + from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP + + # Check if the model is already a FSDP model due to `Manual Wrapping` and if so, + # don't wrap it again + # In case the model is already compiled using PyTorch 2.0 and the wrapped model in it + # is a FSDP model, don't wrap it again + is_type_fsdp = isinstance(model, FSDP) or ( + is_compiled_module(model) and isinstance(model._orig_mod, FSDP) + ) + + if not is_type_fsdp: + self.state.fsdp_plugin.set_auto_wrap_policy(model) + fsdp_plugin = self.state.fsdp_plugin + + # need to ensure that params are re-tied after running + # param_init_fn + fsdp_plugin.param_init_fn = ensure_weights_retied( + fsdp_plugin.param_init_fn, + model, + self.device, + ) + + kwargs = { + # We fallback to reshard_after_forward if sharding_strategy is not set. + # We prerfer sharding_strategy to not break the behavior of the existing code. + # Deprecation warning has already been issued in `utils.dataclasses.py` + "sharding_strategy": fsdp_plugin.sharding_strategy or fsdp_plugin.reshard_after_forward, + "cpu_offload": fsdp_plugin.cpu_offload, + "auto_wrap_policy": fsdp_plugin.auto_wrap_policy, + "mixed_precision": fsdp_plugin.mixed_precision_policy, + "sync_module_states": fsdp_plugin.sync_module_states, + "backward_prefetch": fsdp_plugin.backward_prefetch, + "forward_prefetch": fsdp_plugin.forward_prefetch, + "use_orig_params": fsdp_plugin.use_orig_params, + "param_init_fn": fsdp_plugin.param_init_fn, + "ignored_modules": fsdp_plugin.ignored_modules, + "limit_all_gathers": fsdp_plugin.limit_all_gathers, + "device_id": self.device, + } + + if isinstance(kwargs["ignored_modules"], str): + reg = re.compile(kwargs["ignored_modules"]) + ignored = [] + for name, module in model.named_modules(): + if reg.fullmatch(name): + # ensure that the device for these modules is still set correctly + module.to(self.device) + ignored.append(module) + kwargs["ignored_modules"] = ignored + + model = FSDP(model, **kwargs) + if fsdp_plugin.activation_checkpointing: + from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( + CheckpointImpl, + apply_activation_checkpointing, + checkpoint_wrapper, + ) + + apply_activation_checkpointing( + model, + checkpoint_wrapper_fn=functools.partial( + checkpoint_wrapper, + checkpoint_impl=CheckpointImpl.NO_REENTRANT, + ), + auto_wrap_policy=fsdp_plugin.auto_wrap_policy, + ) + + # In the event the model had been loaded in low precision, but + # mixed precision had also been activated, then we follow DeepSpeed's + # strategy to hold the parameters in full precision. + # - assume that trainer.args.bf16 and trainer.args.fp16 are already checked against + # fsdp_plugin.mixed_precision_policy. + # - NOTE: we do not check the mixed_precision attribute on the FSDP root wrapper. + # * this attribute will always set by init_utils.init_core_state so its always not None. + # * mixed_precision.param_dtype only regards _fwd_bwd_param_dtype + # * if model is loaded in 16bit, and even if mixed_precision.param_dtype is None, + # we still want to upcast the flat_param. + if self.mixed_precision != "no": # if mixed precision is set + upcasted_log = [] + for module in FSDP.fsdp_modules(model): + # Referencing DeepSpeed Zero3 + # - in Init, params are converted to 16bit while partitioning. + # - in accelerator.prepare, deepspeed.initialize is called to: + # * creates the DeepSpeedEngine. + # * since zero_optimization() is True , calls engine._configure_zero_optimizer. + # + # Inside the DeepSpeed Zero3 optimizer configuration, which initializes + # DeepSpeedZeroOptimizer_Stage3, during which: + # * trainable_param_groups are obtained from the attached optimizer + # (already partitioned in 16bit). + # * then _setup_for_real_optimizer -> _create_fp32_partitions + # which performs the fp32 upcasting. + + # To mimic DeepSeepds's casting in FSDP, we look at the (single) FlatParameter held + # within an FSDP wrapper. This FlatParameter will be seen by the optimizer. + # - even though there is a torch.device('meta') guard below, we + # expect _init_utils._init_param_handle_from_module to already + # sync the parameter. + + if not module._has_params: + continue # skip if FSDP module not managing parameters + param = module._flat_param + if ( + param.dtype != torch.float32 + and param.device != torch.device("meta") + and param.requires_grad + ): + # keep log of names_params that was upcasted + # NOTE: resorted to this because warnings.simplefilter("once") is somehow not working + name_param_log = (module.module.__class__.__name__, ", ".join(module._flat_param._fqns)) + if name_param_log not in upcasted_log: + upcasted_log.append(name_param_log) + + # this works because of FSDP's _runtime_utils.lazy_init. + # Have to be careful not to call anything before this that + # triggers lazy_init (e.g., _is_fsdp_root). + param.data = param.data.to(torch.float32) # upcasting + module._handle._orig_param_dtype = torch.float32 # update + + # report the warnings + # some messages can be quite repetitive, especially when reporting about layers that have identical architecture. + if self.is_main_process: + for name_log, param_log in upcasted_log: + warnings.warn( + f"Upcasted low precision parameters in {name_log} because mixed precision turned on in FSDP. " + f"Affects: {param_log}." + ) + + if len(upcasted_log) > 0: + warnings.warn( + "FSDP upcast of low precision parameters may affect the precision of model checkpoints." + ) + + # if the previous and current models are same, delete the previous one + if len(self._models) > 1 and (self._models[-2] is self._models[-1]): + del self._models[-2] + self._models[-1] = model + elif self.distributed_type == DistributedType.MULTI_CPU: + kwargs = self.ddp_handler.to_kwargs() if self.ddp_handler else {} + model = torch.nn.parallel.DistributedDataParallel(model, **kwargs) + if self.ddp_handler is not None: + self.ddp_handler.register_comm_hook(model) + elif self.distributed_type == DistributedType.XLA and self.state.fork_launched: + model = xmp.MpModelWrapper(model).to(self.device) + # Now we can apply the FP8 autocast + if self.fp8_backend == FP8BackendType.TE and self.delayed_fp8_autocast: + model = apply_fp8_autowrap(model, self.te_recipe_handler or self.fp8_recipe_handler) + # torch.compile should be called last and only if the model isn't already compiled + if self.state.dynamo_plugin.backend != DynamoBackend.NO and not is_compiled_module(model): + if self.state.dynamo_plugin.use_regional_compilation: + model = compile_regions(model, **self.state.dynamo_plugin.to_kwargs()) + else: + model = torch.compile(model, **self.state.dynamo_plugin.to_kwargs()) + return model + + def _prepare_ao(self, *args): + if not is_torchao_available(): + raise ImportError( + "`torchao` was not found on your system or is too old of a version. Please ensure that `torchao >= 0.6.1` is installed" + ) + + if self.is_fsdp2: + models = [x for x in args if isinstance(x, torch.nn.Module)] + optimizers = [x for x in args if isinstance(x, torch.optim.Optimizer)] + for arg in args: + if isinstance(arg, torch.nn.Module): + convert_model_to_fp8_ao( + arg, + config=self.ao_recipe_handler.config, + module_filter_func=self.ao_recipe_handler.module_filter_func, + ) + + # Invariant: with FSDP2, optimizer is always passed to `prepare()` together with model + # We only precompute scales if float8 all gather is enabled, possibly can add a flag for this later + if self.is_fsdp2 and len(optimizers) > 0 and self.ao_recipe_handler.config.enable_fsdp_float8_all_gather: + from torchao.float8 import precompute_float8_dynamic_scale_for_fsdp + + optimizers[0].register_step_post_hook( + lambda *args, **kwargs: precompute_float8_dynamic_scale_for_fsdp(models[0]) + ) + + return args + + def _prepare_te(self, *args): + if not is_transformer_engine_available(): + raise ImportError( + "`transformer_engine` was not found on your system. Please ensure that `transformer_engine` is installed" + ) + model, optimizer = None, None + num_models, num_optimizers = 0, 0 + result = [obj for obj in args] + for obj in result: + if isinstance(obj, torch.nn.Module): + model = obj + num_models += 1 + elif isinstance(obj, (torch.optim.Optimizer)): + optimizer = obj + num_optimizers += 1 + if optimizer is None and model is None: + return result + elif optimizer is None or model is None: + raise ValueError( + "You must pass a model and an optimizer together to `accelerate.prepare()` when using TransformerEngine." + ) + elif num_models > 1 or num_optimizers > 1: + raise ValueError( + f"You can't use multiple models ({num_models}) or optimizers {num_optimizers} with TransformerEngine." + ) + old_named_params = self._get_named_parameters(model) + with torch.no_grad(): + convert_model(model) + new_named_params = self._get_named_parameters(model) + mapping = {p: new_named_params[n] for n, p in old_named_params.items()} + # We need to switch the optimizer params to the new params *after* the model is wrapped in FSDP + for param_group in optimizer.param_groups: + param_group["params"] = [mapping[p] for p in param_group["params"]] + + return result + + def _prepare_deepspeed(self, *args): + import deepspeed + + ds_initialize = deepspeed.initialize + if self.fp8_backend == FP8BackendType.MSAMP: + # MS-AMP requires DeepSpeed patches + from msamp import deepspeed as msamp_deepspeed + + ds_initialize = msamp_deepspeed.initialize + + deepspeed_plugin = self.deepspeed_plugin + + is_dataloader_present = any(isinstance(obj, torch.utils.data.DataLoader) for obj in args) + tp_size = deepspeed_plugin.deepspeed_config.get("tensor_parallel", {}).get("autotp_size", 0) + if tp_size > 1: + if not compare_versions("deepspeed", ">=", "0.16.4"): + raise ImportError( + "Deepspeed TP requires deepspeed >= 0.16.4, Please update DeepSpeed via `pip install deepspeed -U`." + ) + if not is_torch_version(">=", "2.2.0"): + raise ImportError( + "Tried to use TP, but `torch.distributed.device_mesh` requires PyTorch >= 2.2.0. Please upgrade your PyTorch version" + ) + from torch.distributed.device_mesh import init_device_mesh + + mesh_dim_name = "tp" + self.state.ds_device_mesh = init_device_mesh(self.device.type, (tp_size,), mesh_dim_names=(mesh_dim_name,)) + + result = [ + self._prepare_one(obj, first_pass=True) if isinstance(obj, torch.utils.data.DataLoader) else obj + for obj in args + ] + + if deepspeed_plugin.is_auto("train_micro_batch_size_per_gpu"): + if is_dataloader_present: + batch_sizes = [obj.batch_size for obj in args if hasattr(obj, "batch_size")] + if any(bs is None for bs in batch_sizes): + raise ValueError( + "At least one of the dataloaders passed to `accelerate.prepare()` has `None` as batch size. " + "Please set an integer value in `train_micro_batch_size_per_gpu` in the deepspeed config file " + "or assign integer value to `AcceleratorState().deepspeed_plugin.deepspeed_config['train_micro_batch_size_per_gpu']`." + ) + if self.split_batches: + batch_sizes = [batch_size // self.num_processes for batch_size in batch_sizes] + + batch_size_per_device = min(batch_sizes) if deepspeed_plugin.is_train_batch_min else max(batch_sizes) + if len(batch_sizes) > 1: + logger.info( + "Since you passed both train and evaluation dataloader, `is_train_batch_min` (here " + f"{deepspeed_plugin.is_train_batch_min} will decide the `train_batch_size` ({batch_size_per_device})." + ) + else: + raise ValueError( + "When using DeepSpeed, `accelerate.prepare()` requires you to pass at least one of training or evaluation dataloaders " + "with `batch_size` attribute returning an integer value " + "or alternatively set an integer value in `train_micro_batch_size_per_gpu` in the deepspeed config file " + "or assign integer value to `AcceleratorState().deepspeed_plugin.deepspeed_config['train_micro_batch_size_per_gpu']`." + ) + else: + batch_size_per_device = deepspeed_plugin.get_value("train_micro_batch_size_per_gpu") + + # handle `gradient_accumulation_steps` when the value is `auto` + deepspeed_plugin.fill_match( + "gradient_accumulation_steps", + must_match=False, + gradient_accumulation_steps=self.gradient_accumulation_steps, + ) + + deepspeed_gradient_accumulation_steps = deepspeed_plugin.get_value("gradient_accumulation_steps") + # update gradient_accumulation_steps if there is a mismatch + if deepspeed_gradient_accumulation_steps != self.gradient_accumulation_steps: + logger.warning( + f"Gradient accumulation steps mismatch: GradientAccumulationPlugin has {self.gradient_accumulation_steps}, " + f"DeepSpeed config has {deepspeed_gradient_accumulation_steps}. Using DeepSpeed's value." + ) + self.gradient_accumulation_steps = deepspeed_gradient_accumulation_steps + + config_kwargs = { + "gradient_clipping": 1.0, + "zero_optimization.stage3_gather_16bit_weights_on_model_save": False, + } + # This is skipped when preparing just a model + if batch_size_per_device is not None: + config_kwargs["train_micro_batch_size_per_gpu"] = batch_size_per_device + config_kwargs["train_batch_size"] = ( + batch_size_per_device * deepspeed_plugin.get_value("gradient_accumulation_steps") * self.num_processes + ) + + model = None + optimizer = None + scheduler = None + for obj in result: + if isinstance(obj, torch.nn.Module): + model = obj + elif isinstance(obj, (torch.optim.Optimizer, DummyOptim)): + optimizer = obj + elif (isinstance(obj, (LRScheduler, DummyScheduler))) or ( + type(obj).__name__ in deepspeed.runtime.lr_schedules.VALID_LR_SCHEDULES + ): + scheduler = obj + + if optimizer is not None: + if "optimizer" in deepspeed_plugin.deepspeed_config and not isinstance(optimizer, (DummyOptim)): + raise ValueError( + "You cannot specify an optimizer in the config file and in the code at the same time. " + "Please remove the optimizer from the config file or " + "create `accelerate.utils.DummyOptim` in the code." + ) + elif "optimizer" not in deepspeed_plugin.deepspeed_config and isinstance(optimizer, (DummyOptim)): + raise ValueError( + "You cannot create a `DummyOptim` without specifying an optimizer in the config file." + ) + + if isinstance(optimizer, (torch.optim.Optimizer)): + deepspeed_plugin.deepspeed_config["zero_allow_untested_optimizer"] = True + + if scheduler is not None: + if "scheduler" in deepspeed_plugin.deepspeed_config and not isinstance(scheduler, (DummyScheduler)): + raise ValueError( + "You cannot specify a scheduler in the config file and in the code at the same time. " + "Please remove the scheduler from the config file or " + "create `accelerate.utils.DummyScheduler` in the code." + ) + elif ( + "scheduler" not in deepspeed_plugin.deepspeed_config + and isinstance(scheduler, (DummyScheduler)) + and scheduler.lr_scheduler_callable is None + ): + raise ValueError( + "Either specify a scheduler in the config file or " + "pass in the `lr_scheduler_callable` parameter when using `accelerate.utils.DummyScheduler`." + ) + + if optimizer is not None and scheduler is not None: + if isinstance(optimizer, (DummyOptim)) and not isinstance(scheduler, (DummyScheduler)): + raise ValueError( + "You can only specify `accelerate.utils.DummyScheduler` in the code when using " + "`accelerate.utils.DummyOptim`." + ) + + if model is not None: + # If we are using FP8, we need to apply the autowrap now + if self.fp8_backend == FP8BackendType.TE: + model = apply_fp8_autowrap(model, self.fp8_recipe_handler) + # if the model is an MOE, set the appropriate MOE layers as leaf Z3 modules + deepspeed_plugin.set_moe_leaf_modules(model) + # deal with config keys that use `auto` value and rely on model's hidden_size + hidden_size_based_keys = [ + "zero_optimization.reduce_bucket_size", + "zero_optimization.stage3_prefetch_bucket_size", + "zero_optimization.stage3_param_persistence_threshold", + ] + hidden_size_auto_keys = [x for x in hidden_size_based_keys if deepspeed_plugin.is_auto(x)] + if len(hidden_size_auto_keys) > 0: + reasoning = ( + "therefore it's not possible to automatically fill out the following `auto` entries " + + f"in the DeepSpeed config file: {hidden_size_auto_keys}. You can fix that by replacing " + + "`auto` values for these keys with an integer value of your choice." + ) + if not hasattr(model, "config"): + raise ValueError("Can't find `model.config` entry, " + reasoning) + + if hasattr(model.config, "hidden_size"): + hidden_size = model.config.hidden_size + elif hasattr(model.config, "hidden_sizes"): + # if there are many hidden sizes pick the largest one + hidden_size = max(model.config.hidden_sizes) + else: + raise ValueError( + "Can find neither `model.config.hidden_size` nor `model.config.hidden_sizes`, " + reasoning + ) + + config_kwargs.update( + { + "zero_optimization.reduce_bucket_size": hidden_size * hidden_size, + "zero_optimization.stage3_prefetch_bucket_size": int(0.9 * hidden_size * hidden_size), + "zero_optimization.stage3_param_persistence_threshold": 10 * hidden_size, + } + ) + + if isinstance(optimizer, (DummyOptim)): + config_kwargs.update( + {"optimizer.params.lr": optimizer.lr, "optimizer.params.weight_decay": optimizer.weight_decay} + ) + if isinstance(scheduler, (DummyScheduler)) and scheduler.lr_scheduler_callable is None: + max_lr = ( + getattr(scheduler.optimizer, "lr", None) + if getattr(scheduler.optimizer, "defaults", None) is None + else scheduler.optimizer.defaults["lr"] + ) + config_kwargs.update( + { + "scheduler.params.warmup_min_lr": 0, + "scheduler.params.warmup_max_lr": max_lr, + "scheduler.params.warmup_num_steps": scheduler.warmup_num_steps, + } + ) + if scheduler.total_num_steps is not None: + config_kwargs["scheduler.params.total_num_steps"] = ( + math.ceil(scheduler.total_num_steps / self.num_processes) + if not self.split_batches + else scheduler.total_num_steps + ) + deepspeed_plugin.deepspeed_config_process(must_match=False, **config_kwargs) + self.deepspeed_config = deepspeed_plugin.deepspeed_config + kwargs = dict(model=model, config_params=self.deepspeed_config) + if optimizer is not None: + if isinstance(optimizer, (DummyOptim)): + kwargs["model_parameters"] = optimizer.params + if isinstance(scheduler, (DummyScheduler)) and scheduler.lr_scheduler_callable is not None: + kwargs["lr_scheduler"] = scheduler.lr_scheduler_callable + else: + if self.deepspeed_config["zero_optimization"].get("offload_optimizer", {}).get( + "device", "none" + ) != "none" and self.deepspeed_config.get("zero_force_ds_cpu_optimizer", True): + if self.device.type == "hpu" and os.environ.get("PT_HPU_LAZY_MODE", "1") == "1": + raise ValueError( + "You can't use an Offload Optimizer with HPU in Lazy Mode. " + "Please set the environment variable `PT_HPU_LAZY_MODE` to `0`." + ) + + optimizer = map_pytorch_optim_to_deepspeed(optimizer) + kwargs["optimizer"] = optimizer + if scheduler is not None: + if type(scheduler).__name__ in deepspeed.runtime.lr_schedules.VALID_LR_SCHEDULES: + kwargs["lr_scheduler"] = scheduler + + if self.device.type == "hpu": + # This env variable is initialized here to make sure it is set to "true" + # It should be done by the launcher but it does not work for multi-node runs + os.environ["DEEPSPEED_USE_HPU"] = "true" + + engine, optimizer, _, lr_scheduler = ds_initialize(**kwargs) + + if compare_versions("deepspeed", ">=", "0.14.4") and self.state.dynamo_plugin.backend != DynamoBackend.NO: + compile_kwargs = self.state.dynamo_plugin.to_kwargs() + if self.state.dynamo_plugin.use_regional_compilation: + compile_regions_deepspeed(engine.module, **compile_kwargs) + else: + engine.compile(backend=compile_kwargs.pop("backend"), compile_kwargs=compile_kwargs) + if optimizer is not None: + optimizer = DeepSpeedOptimizerWrapper(optimizer) + if scheduler is not None: + if lr_scheduler is None: + scheduler = AcceleratedScheduler( + scheduler, + optimizer, + step_with_optimizer=self.step_scheduler_with_optimizer, + split_batches=self.split_batches, + ) + else: + scheduler = DeepSpeedSchedulerWrapper(lr_scheduler, optimizer) + + for i in range(len(result)): + if isinstance(result[i], torch.nn.Module): + result[i] = engine + elif isinstance(result[i], (torch.optim.Optimizer, DummyOptim)): + result[i] = optimizer + elif (isinstance(result[i], (LRScheduler, DummyScheduler))) or ( + type(result[i]).__name__ in deepspeed.runtime.lr_schedules.VALID_LR_SCHEDULES + ): + result[i] = scheduler + # pointing for deepspeed_engine_wrapped.backward() + if self.deepspeed_engine_wrapped is None: + self.deepspeed_engine_wrapped = DeepSpeedEngineWrapper(engine) + else: + logger.warning( + "A wrapped DeepSpeed engine reference is currently tied for this `Accelerator()` instance. " + "If you want to call `accelerator.backward()` referencing a new model/engine, " + "please create a separate `Accelerator()` instance and call `accelerator.prepare()` on it." + ) + self._models.append(engine) + if optimizer is not None: + self._optimizers.append(optimizer) + if scheduler is not None: + self._schedulers.append(scheduler) + return tuple(result) + + def _prepare_megatron_lm(self, *args): + megatron_lm_plugin = self.state.megatron_lm_plugin + micro_batch_size = None + if not megatron_lm_plugin.megatron_dataset_flag: + batch_sizes = [obj.batch_size for obj in args if hasattr(obj, "batch_size")] + if len(batch_sizes) == 0: + raise ValueError( + "You must specify a training or evaluation dataloader in `accelerate.prepare()` when using Megatron-LM." + ) + + micro_batch_size = min(batch_sizes) if megatron_lm_plugin.is_train_batch_min else max(batch_sizes) + if len(batch_sizes) > 1: + logger.info( + "Since you passed both train and evaluation dataloader, `is_train_batch_min` (here " + f"{megatron_lm_plugin.is_train_batch_min} will decide the `train_batch_size` ({micro_batch_size})." + ) + else: + for obj in args: + if isinstance(obj, MegatronLMDummyDataLoader): + micro_batch_size = obj.dataset_args["micro_batch_size"] + break + if micro_batch_size is not None: + dp_degree = self.num_processes // (megatron_lm_plugin.tp_degree * megatron_lm_plugin.pp_degree) + megatron_lm_plugin.set_training_args(micro_batch_size, dp_degree) + else: + raise ValueError( + "When you do not pass the dataloader parameter, the `data_parallel_size`, " + "`micro_batch_size`, and `global_batch_size` megatron parameters will not be updated." + ) + model = None + optimizer = None + scheduler = None + batch_data = None + for obj in args: + if isinstance(obj, torch.utils.data.DataLoader) and batch_data is None: + batch_data = next(iter(obj)) + elif isinstance(obj, torch.nn.Module): + model = obj + elif isinstance(obj, (torch.optim.Optimizer)): + optimizer = obj + elif isinstance(obj, (LRScheduler, MegatronLMDummyScheduler)): + scheduler = obj + + if model is not None: + megatron_lm_plugin.set_network_size_args(model, batch_data) + if optimizer is not None: + megatron_lm_plugin.set_optimizer_type(optimizer) + if scheduler is not None: + if not isinstance(scheduler, MegatronLMDummyScheduler): + raise ValueError( + "You can't use a custom scheduler with Megatron-LM. Please use the `accelerate.utils.MegatronLMDummyScheduler` instead." + ) + megatron_lm_plugin.set_scheduler_args(scheduler) + + # initialize megatron-lm + megatron_lm_initialize(self, args_defaults=megatron_lm_plugin.megatron_lm_default_args) + + (model, optimizer, scheduler) = megatron_lm_prepare_model_optimizer_scheduler(self) + self.wait_for_everyone() + + counter = 0 + result = [] + for obj in args: + if isinstance(obj, torch.utils.data.DataLoader): + result.append(megatron_lm_prepare_data_loader(self, obj)) + counter += 1 + elif isinstance(obj, MegatronLMDummyDataLoader): + if counter == 0: + obj.set_megatron_data_args() + dataloaders = megatron_lm_prepare_data_loader(self, obj) + result.append(dataloaders[counter]) + counter += 1 + else: + result.append(obj) + + if model is not None: + model = MegatronEngine(self, model, optimizer, scheduler) + if optimizer is not None: + optimizer = MegatronLMOptimizerWrapper(optimizer) + if scheduler is not None: + scheduler = MegatronLMSchedulerWrapper(scheduler, optimizer) + + for i in range(len(result)): + if isinstance(result[i], torch.nn.Module): + result[i] = model + elif isinstance(result[i], torch.optim.Optimizer): + result[i] = optimizer + elif isinstance(result[i], MegatronLMDummyScheduler): + result[i] = scheduler + + if model is not None: + self._models.append(model) + if len(self._models) > 1: + raise AssertionError( + "You can't use same `Accelerator()` instance with multiple models when using Megatron-LM" + ) + if optimizer is not None: + self._optimizers.append(optimizer) + if scheduler is not None: + self._schedulers.append(scheduler) + + return tuple(result) + + def _prepare_ipex(self, *args): + """ + Prepares model and optimizer for training with IPEX on CPU/XPU. This covers 3 cases, IPEX compiled with CPU + only support, IPEX compiled with XPU support and training with XPU pytorch backend available in stock pytorch + starting from version 2.4. + """ + + # ipex.optimize() is available only for IPEX, both IPEX-CPU and IPEX-XPU + if is_ipex_available(): + import intel_extension_for_pytorch as ipex + else: + raise ImportError( + "IPEX is not installed or IPEX's version does not match current PyTorch version. Please refer" + " to https://github.com/intel/intel-extension-for-pytorch." + ) + + models = [] + optimizers = [] + result = [obj for obj in args] + for i, obj in enumerate(result): + if isinstance(obj, torch.nn.Module): + model = obj + model.train() + models.append((i, model)) + elif isinstance(obj, (torch.optim.Optimizer)): + optimizers.append((i, obj)) + + # Impossible to determine what to do if multiple models and/or optimizers are provided + if len(optimizers) > 1 or (len(models) > 1 and len(optimizers) == 1): + raise ValueError( + "Prepare with IPEX expects either 1+ models and no optimizer OR a single model-optimizer pair." + ) + + # Nothing to do + if len(models) == 0 and len(optimizers) == 0: + return result + + dtype = torch.bfloat16 if self.state.mixed_precision == "bf16" else None + # Multiple models and no optimizer (inference) are provided + if len(models) > 0 and len(optimizers) == 0: + for i, model in models: + if self.device.type == "xpu" and next(model.parameters()).device.type == "cpu": + model = model.to(self.device) + model, _ = ipex.optimize(model, optimizer=None, dtype=dtype, inplace=True, level="O1") + # Replace in result + result[i] = model + + # A single model-optimizer pair (training) is provided + if len(models) == 1 and len(optimizers) == 1: + i_model, model = models[0] + i_optimizer, optimizer = optimizers[0] + if self.device.type == "xpu" and next(model.parameters()).device.type == "cpu": + model = model.to(self.device) + model, optimizer = ipex.optimize(model, optimizer=optimizer, dtype=dtype, inplace=True, level="O1") + # Replace in result + result[i_model] = model + result[i_optimizer] = optimizer + + return tuple(result) + + def _prepare_device_mesh(self): + """ + Prepare the device mesh for distributed training. The dataloader will determine how to load data based on the + device mesh. + """ + if self.distributed_type == DistributedType.DEEPSPEED and hasattr(self.state, "ds_device_mesh"): + return self.state.ds_device_mesh + else: + return self.torch_device_mesh + + def _prepare_msamp(self, *args, device_placement): + if not is_msamp_available(): + raise ImportError( + "MS-AMP was not found on your system. Please ensure that MS-AMP is available " + " or choose `'te'` as the backend for FP8 mixed precision training." + ) + # We've already checked for FSDP + MS-AMP during `__init__` + import msamp + + model, optimizer = None, None + optimizer_index = None + num_models, num_optimizers = 0, 0 + result = [obj for obj in args] + for i, obj in enumerate(result): + if isinstance(obj, torch.nn.Module): + model = obj + num_models += 1 + elif isinstance(obj, (torch.optim.Optimizer)): + optimizer = obj + optimizer_index = i + num_optimizers += 1 + # DataLoader/Scheduler case + if optimizer is None and model is None: + return result, device_placement + elif optimizer is None or model is None: + raise ValueError( + "You must pass a model and an optimizer together to `accelerate.prepare()` when using MS-AMP." + ) + elif num_models > 1 or num_optimizers > 1: + raise ValueError( + f"You can't use multiple models ({num_models}) or optimizers {num_optimizers} with MS-AMP." + ) + else: + # DEPRECATE @ 2.0 + if self.fp8_recipe_handler is not None: + opt_level = self.fp8_recipe_handler.opt_level + else: + opt_level = self.msamp_recipe_handler.opt_level + model, optimizer = msamp.initialize(model, optimizer, opt_level=opt_level) + for i in range(len(result)): + if isinstance(result[i], torch.nn.Module): + result[i] = model + elif isinstance(result[i], (torch.optim.Optimizer)): + result[i] = optimizer + if optimizer_index is not None: + # NOTE: MS-AMP moves the optimizer, but *not* the model to the right device + device_placement[optimizer_index] = False + return tuple(result), device_placement + + def prepare_data_loader( + self, data_loader: torch.utils.data.DataLoader, device_placement=None, slice_fn_for_dispatch=None + ): + """ + Prepares a PyTorch DataLoader for training in any distributed setup. It is recommended to use + [`Accelerator.prepare`] instead. + + Args: + data_loader (`torch.utils.data.DataLoader`): + A vanilla PyTorch DataLoader to prepare + device_placement (`bool`, *optional*): + Whether or not to place the batches on the proper device in the prepared dataloader. Will default to + `self.device_placement`. + slice_fn_for_dispatch (`Callable`, *optional*`): + If passed, this function will be used to slice tensors across `num_processes`. Will default to + [`~utils.slice_tensors`]. This argument is used only when `dispatch_batches` is set to `True` and will + be ignored otherwise. + + Example: + + ```python + >>> import torch + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> data_loader = torch.utils.data.DataLoader(...) + >>> data_loader = accelerator.prepare_data_loader(data_loader, device_placement=True) + ``` + """ + # Ensure we can't double wrap a DataLoader due to `find_batch_size` + if getattr(data_loader, "_is_accelerate_prepared", False): + if data_loader not in self._dataloaders: + self._dataloaders.append(data_loader) + return data_loader + if device_placement is None: + device_placement = self.device_placement if self.distributed_type != DistributedType.XLA else False + + device_mesh = self._prepare_device_mesh() + + prepared_data_loader = prepare_data_loader( + data_loader, + self.device, + num_processes=self.num_processes, + process_index=self.process_index, + split_batches=self.split_batches, + put_on_device=device_placement, + rng_types=self.rng_types.copy(), + dispatch_batches=self.dispatch_batches, + even_batches=self.even_batches, + slice_fn_for_dispatch=slice_fn_for_dispatch, + use_seedable_sampler=self.use_seedable_sampler, + data_seed=self.dataloader_config.data_seed, + non_blocking=self.non_blocking, + use_stateful_dataloader=self.use_stateful_dataloader, + torch_device_mesh=device_mesh, + ) + self._dataloaders.append(prepared_data_loader) + return prepared_data_loader + + def prepare_optimizer(self, optimizer: torch.optim.Optimizer, device_placement=None): + """ + Prepares a PyTorch Optimizer for training in any distributed setup. It is recommended to use + [`Accelerator.prepare`] instead. + + Args: + optimizer (`torch.optim.Optimizer`): + A vanilla PyTorch optimizer to prepare + device_placement (`bool`, *optional*): + Whether or not to place the optimizer on the proper device. Will default to `self.device_placement`. + + Example: + + ```python + >>> import torch + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> optimizer = torch.optim.Adam(...) + >>> optimizer = accelerator.prepare_optimizer(optimizer, device_placement=True) + ``` + """ + if is_lomo_available(): + # We need to import locally to avoid circular imports since lomo imports stuff from + # transformers & accelerate + from lomo_optim import AdaLomo, Lomo + + # Support multiple optimizers: https://github.com/huggingface/accelerate/pull/2695#discussion_r1589164607 + self.has_lomo_optimizer |= isinstance(optimizer, (Lomo, AdaLomo)) + + # Ensure we can't double wrap an optimizer due to `find_batch_size` + if getattr(optimizer, "_is_accelerate_prepared", False): + if optimizer not in self._optimizers: + self._optimizers.append(optimizer) + return optimizer + if device_placement is None: + device_placement = self.device_placement + # NOTE: Special case with MS-AMP we do *not* pass in the scaler explicitly to the `AcceleratedOptimizer`, + # Their optimizer handles it for us. + scaler = None if self.fp8_backend == FP8BackendType.MSAMP else self.scaler + optimizer = AcceleratedOptimizer(optimizer, device_placement=device_placement, scaler=scaler) + self._optimizers.append(optimizer) + return optimizer + + def prepare_scheduler(self, scheduler: LRScheduler): + """ + Prepares a PyTorch Scheduler for training in any distributed setup. It is recommended to use + [`Accelerator.prepare`] instead. + + Args: + scheduler (`torch.optim.lr_scheduler.LRScheduler`): + A vanilla PyTorch scheduler to prepare + + Example: + + ```python + >>> import torch + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> optimizer = torch.optim.Adam(...) + >>> scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, ...) + >>> scheduler = accelerator.prepare_scheduler(scheduler) + ``` + """ + # Ensure we can't double wrap a scheduler due to `find_batch_size` + if getattr(scheduler, "_is_accelerate_prepared", False): + if scheduler not in self._schedulers: + self._schedulers.append(scheduler) + return scheduler + # We try to find the optimizer associated with `scheduler`, the default is the full list. + optimizer = self._optimizers + for opt in self._optimizers: + if getattr(scheduler, "optimizer", None) == opt.optimizer: + optimizer = opt + break + scheduler = AcceleratedScheduler( + scheduler, + optimizer, + step_with_optimizer=self.step_scheduler_with_optimizer, + split_batches=self.split_batches, + ) + self._schedulers.append(scheduler) + return scheduler + + def backward(self, loss, **kwargs): + """ + Scales the gradients in accordance to the `GradientAccumulationPlugin` and calls the correct `backward()` based + on the configuration. + + Should be used in lieu of `loss.backward()`. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator(gradient_accumulation_steps=2) + >>> outputs = model(inputs) + >>> loss = loss_fn(outputs, labels) + >>> accelerator.backward(loss) + ``` + """ + learning_rate = kwargs.get("learning_rate") + + if self.distributed_type != DistributedType.DEEPSPEED: + # deepspeed handles loss scaling by gradient_accumulation_steps in its `backward` + loss = loss / self.gradient_accumulation_steps + if self.distributed_type == DistributedType.DEEPSPEED: + self.deepspeed_engine_wrapped.backward(loss, sync_gradients=self.sync_gradients, **kwargs) + elif self.distributed_type == DistributedType.MEGATRON_LM: + return + elif self.scaler is not None: + self.scaler.scale(loss).backward(**kwargs) + elif learning_rate is not None and self.has_lomo_optimizer: + self.lomo_backward(loss, learning_rate) + else: + loss.backward(**kwargs) + + def set_trigger(self): + """ + Sets the internal trigger tensor to 1 on the current process. A latter check should follow using this which + will check across all processes. + + Note: + Does not require `wait_for_everyone()` + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> # Assume later in the training script + >>> # `should_do_breakpoint` is a custom function to monitor when to break, + >>> # e.g. when the loss is NaN + >>> if should_do_breakpoint(loss): + ... accelerator.set_trigger() + >>> # Assume later in the training script + >>> if accelerator.check_breakpoint(): + ... break + ``` + """ + self.flag_tensor = torch.tensor(1, device=self.device) + + def check_trigger(self): + """ + Checks if the internal trigger tensor has been set to 1 in any of the processes. If so, will return `True` and + reset the trigger tensor to 0. + + Note: + Does not require `wait_for_everyone()` + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> # Assume later in the training script + >>> # `should_do_breakpoint` is a custom function to monitor when to break, + >>> # e.g. when the loss is NaN + >>> if should_do_breakpoint(loss): + ... accelerator.set_trigger() + >>> # Assume later in the training script + >>> if accelerator.check_trigger(): + ... break + ``` + """ + # Now that we are outside `__init__`, we can initialize it if it is `None` on device + if self.flag_tensor is None: + self.flag_tensor = torch.tensor(0, device=self.device) + flag_tensor = self.reduce(self.flag_tensor) + if flag_tensor.item() >= 1: + self.flag_tensor = torch.tensor(0, device=self.device) + return True + return False + + def unscale_gradients(self, optimizer=None): + """ + Unscale the gradients in mixed precision training with AMP. This is a noop in all other settings. + + Likely should be called through [`Accelerator.clip_grad_norm_`] or [`Accelerator.clip_grad_value_`] + + Args: + optimizer (`torch.optim.Optimizer` or `list[torch.optim.Optimizer]`, *optional*): + The optimizer(s) for which to unscale gradients. If not set, will unscale gradients on all optimizers + that were passed to [`~Accelerator.prepare`]. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> model, optimizer = accelerator.prepare(model, optimizer) + >>> outputs = model(inputs) + >>> loss = loss_fn(outputs, labels) + >>> accelerator.backward(loss) + >>> accelerator.unscale_gradients(optimizer=optimizer) + ``` + """ + if self.native_amp and self.mixed_precision == "fp16": + if optimizer is None: + # TODO: this unscales all optimizers where we should only unscale the one where parameters are. + optimizer = self._optimizers + elif not isinstance(optimizer, (tuple, list)): + optimizer = [optimizer] + for opt in optimizer: + while isinstance(opt, AcceleratedOptimizer): + opt = opt.optimizer + self.scaler.unscale_(opt) + + def clip_grad_norm_(self, parameters, max_norm, norm_type=2): + """ + Should be used in place of `torch.nn.utils.clip_grad_norm_`. + + Returns: + `torch.Tensor`: Total norm of the parameter gradients (viewed as a single vector). + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator(gradient_accumulation_steps=2) + >>> dataloader, model, optimizer, scheduler = accelerator.prepare(dataloader, model, optimizer, scheduler) + + >>> for input, target in dataloader: + ... optimizer.zero_grad() + ... output = model(input) + ... loss = loss_func(output, target) + ... accelerator.backward(loss) + ... if accelerator.sync_gradients: + ... accelerator.clip_grad_norm_(model.parameters(), max_grad_norm) + ... optimizer.step() + ``` + """ + if self.distributed_type == DistributedType.FSDP: + self.unscale_gradients() + parameters = [p for p in parameters] + for model in self._models: + if parameters == [p for p in model.parameters()]: + if not self.is_fsdp2: + return model.clip_grad_norm_(max_norm, norm_type) + else: + return torch.nn.utils.clip_grad_norm_( + parameters, max_norm, norm_type=norm_type + ) # viz: https://github.com/pytorch/torchtitan/blob/main/docs/fsdp.md + elif self.distributed_type == DistributedType.DEEPSPEED: + # DeepSpeed handles gradient clipping internally, but we can retrieve the gradient norm + if self.deepspeed_engine_wrapped is not None: + return self.deepspeed_engine_wrapped.get_global_grad_norm() + return None + elif self.distributed_type == DistributedType.XLA: + # Reduce gradients first for XLA + for acc_opt in self._optimizers: + if not acc_opt.gradient_state.is_xla_gradients_synced: + opt = acc_opt + while isinstance(opt, AcceleratedOptimizer): + opt = opt.optimizer + gradients = xm._fetch_gradients(opt) + # Use xm.all_reduce to perform an in-place all-reduce. Recusrsive all-reduce each tensor + # one by one in self.reduce is non-inplace. + xm.all_reduce("sum", gradients, scale=1.0 / self.num_processes) + # Set is_xla_gradients_synced to True to avoid all-reduce twice in the AcceleratedOptimizer step. + acc_opt.gradient_state.is_xla_gradients_synced = True + if os.environ.get("ACCELERATE_USE_FSDP", "false").lower() == "true": + self.unscale_gradients() + parameters = [p for p in parameters] + for model in self._models: + if parameters == [p for p in model.parameters()]: + return model.clip_grad_norm_(max_norm, norm_type) + self.unscale_gradients() + return torch.nn.utils.clip_grad_norm_(parameters, max_norm, norm_type=norm_type) + + def clip_grad_value_(self, parameters, clip_value): + """ + Should be used in place of `torch.nn.utils.clip_grad_value_`. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator(gradient_accumulation_steps=2) + >>> dataloader, model, optimizer, scheduler = accelerator.prepare(dataloader, model, optimizer, scheduler) + + >>> for input, target in dataloader: + ... optimizer.zero_grad() + ... output = model(input) + ... loss = loss_func(output, target) + ... accelerator.backward(loss) + ... if accelerator.sync_gradients: + ... accelerator.clip_grad_value_(model.parameters(), clip_value) + ... optimizer.step() + ``` + """ + if self.distributed_type in [DistributedType.DEEPSPEED, DistributedType.FSDP]: + raise Exception("DeepSpeed and FSDP do not support `clip_grad_value_`. Use `clip_grad_norm_` instead.") + self.unscale_gradients() + torch.nn.utils.clip_grad_value_(parameters, clip_value) + + def gather(self, tensor): + """ + Gather the values in *tensor* across all processes and concatenate them on the first dimension. Useful to + regroup the predictions from all processes when doing evaluation. + + Note: + This gather happens in all processes. + + Args: + tensor (`torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`): + The tensors to gather across all processes. + + Returns: + `torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`: The gathered tensor(s). Note that the + first dimension of the result is *num_processes* multiplied by the first dimension of the input tensors. + + Example: + + ```python + >>> # Assuming four processes + >>> import torch + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> process_tensor = torch.tensor([accelerator.process_index]) + >>> gathered_tensor = accelerator.gather(process_tensor) + >>> gathered_tensor + tensor([0, 1, 2, 3]) + ``` + """ + return gather(tensor) + + def gather_for_metrics(self, input_data, use_gather_object=False): + """ + Gathers `input_data` and potentially drops duplicates in the last batch if on a distributed system. Should be + used for gathering the inputs and targets for metric calculation. + + Args: + input (`torch.Tensor`, `object`, a nested tuple/list/dictionary of `torch.Tensor`, or a nested tuple/list/dictionary of `object`): + The tensors or objects for calculating metrics across all processes + use_gather_object(`bool`): + Whether to forcibly use gather_object instead of gather (which is already done if all objects passed do + not contain tensors). This flag can be useful for gathering tensors with different sizes that we don't + want to pad and concatenate along the first dimension. Using it with GPU tensors is not well supported + and inefficient as it incurs GPU -> CPU transfer since tensors would be pickled. + + Example: + + ```python + >>> # Assuming two processes, with a batch size of 5 on a dataset with 9 samples + >>> import torch + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> dataloader = torch.utils.data.DataLoader(range(9), batch_size=5) + >>> dataloader = accelerator.prepare(dataloader) + >>> batch = next(iter(dataloader)) + >>> gathered_items = accelerator.gather_for_metrics(batch) + >>> len(gathered_items) + 9 + ``` + """ + + try: + recursively_apply(lambda x: x, input_data, error_on_other_type=True) + all_tensors = True + except TypeError: + all_tensors = False + + use_gather_object = use_gather_object or not all_tensors + + if use_gather_object: + data = gather_object(input_data) + else: + data = self.gather(input_data) + + try: + if self.gradient_state.end_of_dataloader: + # at the end of a dataloader, `gather_for_metrics` regresses to + # `gather` unless the dataset has a remainder so log. + if self.gradient_state.remainder == -1: + logger.info( + "The used dataset had no length, returning gathered tensors. You should drop the remainder yourself." + ) + return data + elif self.gradient_state.remainder > 0: + # Last batch needs to be truncated on distributed systems as it contains additional samples + def _adjust_samples(tensor): + return tensor[: self.gradient_state.remainder] + + if use_gather_object: + # gather_object put the objects in a list + return _adjust_samples(data) + else: + return recursively_apply(_adjust_samples, data) + else: # remainder is 0 + # no remainder even though at end of dataloader, so nothing to do. + return data + else: + # Not at the end of the dataloader, no need to adjust the tensors + return data + except Exception: + # Dataset had no length or raised an error + return data + + def reduce(self, tensor, reduction="sum", scale=1.0): + """ + Reduce the values in *tensor* across all processes based on *reduction*. + + Note: + All processes get the reduced value. + + Args: + tensor (`torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`): + The tensors to reduce across all processes. + reduction (`str`, *optional*, defaults to "sum"): + A reduction type, can be one of 'sum', 'mean', or 'none'. If 'none', will not perform any operation. + scale (`float`, *optional*, defaults to 1.0): + A default scaling value to be applied after the reduce, only valied on XLA. + + Returns: + `torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`: + The reduced tensor(s). + + Example: + + ```python + >>> # Assuming two processes + >>> import torch + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> process_tensor = torch.arange(accelerator.num_processes) + 1 + (2 * accelerator.process_index) + >>> process_tensor = process_tensor.to(accelerator.device) + >>> reduced_tensor = accelerator.reduce(process_tensor, reduction="sum") + >>> reduced_tensor + tensor([4, 6]) + ``` + """ + return reduce(tensor, reduction, scale) + + def pad_across_processes(self, tensor, dim=0, pad_index=0, pad_first=False): + """ + Recursively pad the tensors in a nested list/tuple/dictionary of tensors from all devices to the same size so + they can safely be gathered. + + Args: + tensor (nested list/tuple/dictionary of `torch.Tensor`): + The data to gather. + dim (`int`, *optional*, defaults to 0): + The dimension on which to pad. + pad_index (`int`, *optional*, defaults to 0): + The value with which to pad. + pad_first (`bool`, *optional*, defaults to `False`): + Whether to pad at the beginning or the end. + + Returns: + `torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`: + The padded tensor(s). + + Example: + + ```python + >>> # Assuming two processes, with the first processes having a tensor of size 1 and the second of size 2 + >>> import torch + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> process_tensor = torch.arange(accelerator.process_index + 1).to(accelerator.device) + >>> padded_tensor = accelerator.pad_across_processes(process_tensor) + >>> padded_tensor.shape + torch.Size([2]) + ``` + """ + return pad_across_processes(tensor, dim=dim, pad_index=pad_index, pad_first=pad_first) + + def unwrap_model(self, model, keep_fp32_wrapper: bool = True, keep_torch_compile: bool = True): + """ + Unwraps the `model` from the additional layer possible added by [`~Accelerator.prepare`]. Useful before saving + the model. + + Args: + model (`torch.nn.Module`): + The model to unwrap. + keep_fp32_wrapper (`bool`, *optional*, defaults to `True`): + Whether to not remove the mixed precision hook if it was added. + keep_torch_compile (`bool`, *optional*, defaults to `True`): + Whether to not unwrap compiled model if compiled. + Returns: + `torch.nn.Module`: The unwrapped model. + + Example: + + ```python + >>> # Assuming two GPU processes + >>> from torch.nn.parallel import DistributedDataParallel + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> model = accelerator.prepare(MyModel()) + >>> print(model.__class__.__name__) + DistributedDataParallel + + >>> model = accelerator.unwrap_model(model) + >>> print(model.__class__.__name__) + MyModel + ``` + """ + return extract_model_from_parallel(model, keep_fp32_wrapper, keep_torch_compile) + + def wait_for_everyone(self): + """ + Will stop the execution of the current process until every other process has reached that point (so this does + nothing when the script is only run in one process). Useful to do before saving a model. + + Example: + + ```python + >>> # Assuming two GPU processes + >>> import time + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> if accelerator.is_main_process: + ... time.sleep(2) + >>> else: + ... print("I'm waiting for the main process to finish its sleep...") + >>> accelerator.wait_for_everyone() + >>> # Should print on every process at the same time + >>> print("Everyone is here") + ``` + """ + wait_for_everyone() + + @on_main_process + def init_trackers(self, project_name: str, config: dict | None = None, init_kwargs: dict | None = {}): + """ + Initializes a run for all trackers stored in `self.log_with`, potentially with starting configurations + + Args: + project_name (`str`): + The name of the project. All trackers will save their data based on this + config (`dict`, *optional*): + Optional starting configuration to be logged. + init_kwargs (`dict`, *optional*): + A nested dictionary of kwargs to be passed to a specific tracker's `__init__` function. Should be + formatted like so: + ```python + {"wandb": {"tags": ["tag_a", "tag_b"]}} + ``` + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator(log_with="tensorboard") + >>> accelerator.init_trackers( + ... project_name="my_project", + ... config={"learning_rate": 0.001, "batch_size": 32}, + ... init_kwargs={"tensorboard": {"flush_secs": 60}}, + ... ) + ``` + """ + for tracker in self.log_with: + if issubclass(type(tracker), GeneralTracker): + # Custom trackers are already initialized + self.trackers.append(tracker) + else: + tracker_init = LOGGER_TYPE_TO_CLASS[str(tracker)] + if tracker_init.requires_logging_directory: + # We can skip this check since it was done in `__init__` + self.trackers.append( + tracker_init(project_name, self.logging_dir, **init_kwargs.get(str(tracker), {})) + ) + else: + self.trackers.append(tracker_init(project_name, **init_kwargs.get(str(tracker), {}))) + + for tracker in self.trackers: + tracker.start() + + if config is not None: + for tracker in self.trackers: + tracker.store_init_configuration(config) + + def get_tracker(self, name: str, unwrap: bool = False): + """ + Returns a `tracker` from `self.trackers` based on `name` on the main process only. + + Args: + name (`str`): + The name of a tracker, corresponding to the `.name` property. + unwrap (`bool`): + Whether to return the internal tracking mechanism or to return the wrapped tracker instead + (recommended). + + Returns: + `GeneralTracker`: The tracker corresponding to `name` if it exists. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator(log_with="tensorboard") + >>> accelerator.init_trackers("my_project") + >>> tensorboard_tracker = accelerator.get_tracker("tensorboard") + ``` + """ + if len(self.trackers) > 0: + for tracker in self.trackers: + if tracker.name == name: + return tracker.tracker if unwrap else tracker + raise ValueError(f"{name} is not an available tracker stored inside the `Accelerator`.") + # Handle tracker only made on main process + return GeneralTracker(_blank=True) + + @on_main_process + def log(self, values: dict, step: int | None = None, log_kwargs: dict | None = {}): + """ + Logs `values` to all stored trackers in `self.trackers` on the main process only. + + Args: + values (`dict`): + Values should be a dictionary-like object containing only types `int`, `float`, or `str`. + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + log_kwargs (`dict`, *optional*): + A nested dictionary of kwargs to be passed to a specific tracker's `log` function. Should be formatted + like so: + ```python + {"wandb": {"tags": ["tag_a", "tag_b"]}} + ``` + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator(log_with="tensorboard") + >>> accelerator.init_trackers("my_project") + >>> accelerator.log({"loss": 0.5, "accuracy": 0.9}) + ``` + """ + for tracker in self.trackers: + tracker.log(values, step=step, **log_kwargs.get(tracker.name, {})) + + def end_training(self): + """ + Runs any special end training behaviors, such as stopping trackers on the main process only or destoying + process group. Should always be called at the end of your script if using experiment tracking. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator(log_with="tensorboard") + >>> accelerator.init_trackers("my_project") + >>> # Do training + >>> accelerator.end_training() + ``` + """ + for tracker in self.trackers: + tracker.finish() + + self.state.destroy_process_group() + + def save(self, obj, f, safe_serialization=False): + """ + Save the object passed to disk once per machine. Use in place of `torch.save`. + + Args: + obj (`object`): The object to save. + f (`str` or `os.PathLike`): Where to save the content of `obj`. + safe_serialization (`bool`, *optional*, defaults to `False`): Whether to save `obj` using `safetensors` + + Note: + If `save_on_each_node` was passed in as a `ProjectConfiguration`, will save the object once per node, + rather than only once on the main node. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> arr = [0, 1, 2, 3] + >>> accelerator.save(arr, "array.pkl") + ``` + """ + save( + obj, + f, + save_on_each_node=self.project_configuration.save_on_each_node, + safe_serialization=safe_serialization, + ) + + def save_model( + self, + model: torch.nn.Module, + save_directory: Union[str, os.PathLike], + max_shard_size: Union[int, str] = "10GB", + safe_serialization: bool = True, + ): + """ + Save a model so that it can be re-loaded using load_checkpoint_in_model + + Arguments: + model: (`torch.nn.Module`): + Model to be saved. The model can be wrapped or unwraped. + save_directory (`str` or `os.PathLike`): + Directory to which to save. Will be created if it doesn't exist. + max_shard_size (`int` or `str`, *optional*, defaults to `"10GB"`): + The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size + lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`). + + + + If a single weight of the model is bigger than `max_shard_size`, it will be in its own checkpoint shard + which will be bigger than `max_shard_size`. + + + + safe_serialization (`bool`, *optional*, defaults to `True`): + Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`). + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> model = ... + >>> accelerator.save_model(model, save_directory) + ``` + """ + + if os.path.isfile(save_directory): + logger.error(f"Provided path ({save_directory}) should be a directory, not a file") + return + + # get the state_dict of the model + if any(has_offloaded_params(module) for module in model.modules()): + state_dict = get_state_dict_offloaded_model(model) + else: + if any(param.device == torch.device("meta") for param in model.parameters()): + raise RuntimeError("You can't save the model since some parameters are on the meta device.") + state_dict = self.get_state_dict(model) + + # Case: DeepSpeed zero3 gets gathered and `state_dict` is empty + if state_dict is None: + return + os.makedirs(save_directory, exist_ok=True) + + if safe_serialization: + state_dict = clean_state_dict_for_safetensors(state_dict) + weights_name = SAFE_WEIGHTS_NAME if safe_serialization else WEIGHTS_NAME + filename_pattern = SAFE_WEIGHTS_PATTERN_NAME if safe_serialization else WEIGHTS_PATTERN_NAME + + state_dict_split = split_torch_state_dict_into_shards( + state_dict, filename_pattern=filename_pattern, max_shard_size=max_shard_size + ) + + # Clean the folder from a previous save + for filename in os.listdir(save_directory): + full_filename = os.path.join(save_directory, filename) + # If we have a shard file that is not going to be replaced, we delete it, but only from the main process + # in distributed settings to avoid race conditions. + weights_no_suffix = weights_name.replace(".bin", "") + + # make sure that file to be deleted matches format of sharded file, e.g. pytorch_model-00001-of-00005 + filename_no_suffix = filename.replace(".bin", "") + reg = re.compile(r"(.*?)-\d{5}-of-\d{5}") + + if ( + filename.startswith(weights_no_suffix) + and os.path.isfile(full_filename) + and filename not in state_dict_split.filename_to_tensors.keys() + and reg.fullmatch(filename_no_suffix) is not None + and PartialState().is_main_process + ): + os.remove(full_filename) + + # Save the model + for filename, tensors in state_dict_split.filename_to_tensors.items(): + shard = {tensor: state_dict[tensor] for tensor in tensors} + self.save(shard, os.path.join(save_directory, filename), safe_serialization=safe_serialization) + + # Save index if sharded + if state_dict_split.is_sharded: + index = { + "metadata": state_dict_split.metadata, + "weight_map": state_dict_split.tensor_to_filename, + } + save_index_file = SAFE_WEIGHTS_INDEX_NAME if safe_serialization else WEIGHTS_INDEX_NAME + save_index_file = os.path.join(save_directory, save_index_file) + with open(save_index_file, "w", encoding="utf-8") as f: + content = json.dumps(index, indent=2, sort_keys=True) + "\n" + f.write(content) + logger.info( + f"The model is bigger than the maximum size per checkpoint ({max_shard_size}) and is going to be " + f"split in {len(state_dict_split.filename_to_tensors)} checkpoint shards. You can find where each parameters has been saved in the " + f"index located at {save_index_file}." + ) + else: + path_to_weights = os.path.join(save_directory, WEIGHTS_NAME) + logger.info(f"Model weights saved in {path_to_weights}") + + def register_save_state_pre_hook(self, hook: Callable[..., None]) -> hooks.RemovableHandle: + """ + Registers a pre hook to be run before `save_checkpoint` is called in [`Accelerator.save_state`]. + + Args: + hook (`Callable`): + A function to be called in [`Accelerator.save_state`] before `save_checkpoint`. + + The hook should have the following signature: + + `hook(models: list[torch.nn.Module], weights: list[dict[str, torch.Tensor]], input_dir: str) -> None` + + The `models` argument are the models as saved in the accelerator state under `accelerator._models`, `weigths` + argument are the state dicts of the `models`, and the `input_dir` argument is the `input_dir` argument passed + to [`Accelerator.load_state`]. + + + + Should only be used in conjunction with [`Accelerator.register_load_state_pre_hook`]. Can be useful to save + configurations in addition to model weights. Can also be used to overwrite model saving with a customized + method. In this case, make sure to remove already loaded weights from the weights list. + + + + Returns: + `torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling + `handle.remove()` + """ + handle = hooks.RemovableHandle(self._save_model_state_pre_hook) + self._save_model_state_pre_hook[handle.id] = hook + return handle + + def save_state(self, output_dir: str = None, safe_serialization: bool = True, **save_model_func_kwargs): + """ + Saves the current states of the model, optimizer, scaler, RNG generators, and registered objects to a folder. + + If a `ProjectConfiguration` was passed to the `Accelerator` object with `automatic_checkpoint_naming` enabled + then checkpoints will be saved to `self.project_dir/checkpoints`. If the number of current saves is greater + than `total_limit` then the oldest save is deleted. Each checkpoint is saved in separate folders named + `checkpoint_`. + + Otherwise they are just saved to `output_dir`. + + + + Should only be used when wanting to save a checkpoint during training and restoring the state in the same + environment. + + + + Args: + output_dir (`str` or `os.PathLike`): + The name of the folder to save all relevant weights and states. + safe_serialization (`bool`, *optional*, defaults to `True`): + Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`). + save_model_func_kwargs (`dict`, *optional*): + Additional keyword arguments for saving model which can be passed to the underlying save function, such + as optional arguments for DeepSpeed's `save_checkpoint` function. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> model, optimizer, lr_scheduler = ... + >>> model, optimizer, lr_scheduler = accelerator.prepare(model, optimizer, lr_scheduler) + >>> accelerator.save_state(output_dir="my_checkpoint") + ``` + """ + if self.project_configuration.automatic_checkpoint_naming: + output_dir = os.path.join(self.project_dir, "checkpoints") + os.makedirs(output_dir, exist_ok=True) + if self.project_configuration.automatic_checkpoint_naming: + folders = [os.path.join(output_dir, folder) for folder in os.listdir(output_dir)] + if ( + self.project_configuration.total_limit is not None + and (len(folders) + 1 > self.project_configuration.total_limit) + and self.is_main_process + ): + + def _inner(folder): + return list(map(int, re.findall(r"[\/]?([0-9]+)(?=[^\/]*$)", folder)))[0] + + folders.sort(key=_inner) + logger.warning( + f"Deleting {len(folders) + 1 - self.project_configuration.total_limit} checkpoints to make room for new checkpoint." + ) + for folder in folders[: len(folders) + 1 - self.project_configuration.total_limit]: + shutil.rmtree(folder) + output_dir = os.path.join(output_dir, f"checkpoint_{self.save_iteration}") + if os.path.exists(output_dir): + raise ValueError( + f"Checkpoint directory {output_dir} ({self.save_iteration}) already exists. Please manually override `self.save_iteration` with what iteration to start with." + ) + self.wait_for_everyone() + os.makedirs(output_dir, exist_ok=True) + logger.info(f"Saving current state to {output_dir}") + + if self.distributed_type == DistributedType.XLA: + # Finish running the previous step before checkpointing + xm.mark_step() + + # Save the models taking care of FSDP and DeepSpeed nuances + weights = [] + for i, model in enumerate(self._models): + if self.distributed_type == DistributedType.FSDP: + logger.info("Saving FSDP model") + save_fsdp_model(self.state.fsdp_plugin, self, model, output_dir, i) + logger.info(f"FSDP Model saved to output dir {output_dir}") + elif self.distributed_type == DistributedType.DEEPSPEED: + logger.info("Saving DeepSpeed Model and Optimizer") + ckpt_id = f"{MODEL_NAME}" if i == 0 else f"{MODEL_NAME}_{i}" + model.save_checkpoint(output_dir, ckpt_id, **save_model_func_kwargs) + logger.info(f"DeepSpeed Model and Optimizer saved to output dir {os.path.join(output_dir, ckpt_id)}") + elif self.distributed_type == DistributedType.MEGATRON_LM: + logger.info("Saving Megatron-LM Model, Optimizer and Scheduler") + model.save_checkpoint(output_dir) + logger.info(f"Megatron-LM Model , Optimizer and Scheduler saved to output dir {output_dir}") + else: + weights.append(self.get_state_dict(model, unwrap=False)) + + # Save the optimizers taking care of FSDP and DeepSpeed nuances + optimizers = [] + if self.distributed_type == DistributedType.FSDP: + for i, opt in enumerate(self._optimizers): + logger.info("Saving FSDP Optimizer") + save_fsdp_optimizer(self.state.fsdp_plugin, self, opt, self._models[i], output_dir, i) + logger.info(f"FSDP Optimizer saved to output dir {output_dir}") + elif self.distributed_type not in [DistributedType.DEEPSPEED, DistributedType.MEGATRON_LM]: + optimizers = self._optimizers + + # Save the lr schedulers taking care of DeepSpeed nuances + schedulers = [] + if self.distributed_type == DistributedType.DEEPSPEED: + for i, scheduler in enumerate(self._schedulers): + if isinstance(scheduler, DeepSpeedSchedulerWrapper): + continue + schedulers.append(scheduler) + elif self.distributed_type not in [DistributedType.MEGATRON_LM]: + schedulers = self._schedulers + + # Save the samplers of the dataloaders + dataloaders = self._dataloaders + + # Call model loading hooks that might have been registered with + # accelerator.register_model_state_hook + for hook in self._save_model_state_pre_hook.values(): + hook(self._models, weights, output_dir) + + save_location = save_accelerator_state( + output_dir, + weights, + optimizers, + schedulers, + dataloaders, + self.state.process_index, + self.step, + self.scaler, + save_on_each_node=self.project_configuration.save_on_each_node, + safe_serialization=safe_serialization, + ) + for i, obj in enumerate(self._custom_objects): + save_custom_state(obj, output_dir, i, save_on_each_node=self.project_configuration.save_on_each_node) + self.project_configuration.iteration += 1 + return save_location + + def register_load_state_pre_hook(self, hook: Callable[..., None]) -> hooks.RemovableHandle: + """ + Registers a pre hook to be run before [`load_checkpoint`] is called in [`Accelerator.load_state`]. + + Args: + hook (`Callable`): + A function to be called in [`Accelerator.load_state`] before `load_checkpoint`. + + The hook should have the following signature: + + `hook(models: list[torch.nn.Module], input_dir: str) -> None` + + The `models` argument are the models as saved in the accelerator state under `accelerator._models`, and the + `input_dir` argument is the `input_dir` argument passed to [`Accelerator.load_state`]. + + + + Should only be used in conjunction with [`Accelerator.register_save_state_pre_hook`]. Can be useful to load + configurations in addition to model weights. Can also be used to overwrite model loading with a customized + method. In this case, make sure to remove already loaded models from the models list. + + + + Returns: + `torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling + `handle.remove()` + """ + handle = hooks.RemovableHandle(self._load_model_state_pre_hook) + self._load_model_state_pre_hook[handle.id] = hook + return handle + + def load_state(self, input_dir: str = None, load_kwargs: dict | None = None, **load_model_func_kwargs): + """ + Loads the current states of the model, optimizer, scaler, RNG generators, and registered objects. + + + + Should only be used in conjunction with [`Accelerator.save_state`]. If a file is not registered for + checkpointing, it will not be loaded if stored in the directory. + + + + Args: + input_dir (`str` or `os.PathLike`): + The name of the folder all relevant weights and states were saved in. Can be `None` if + `automatic_checkpoint_naming` is used, and will pick up from the latest checkpoint. + load_kwargs (`dict`, *optional*): + Additional keyword arguments for the underlying `load` function, such as optional arguments for + state_dict and optimizer on. + load_model_func_kwargs (`dict`, *optional*): + Additional keyword arguments for loading model which can be passed to the underlying load function, + such as optional arguments for DeepSpeed's `load_checkpoint` function or a `map_location` to load the + model and optimizer on. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> model, optimizer, lr_scheduler = ... + >>> model, optimizer, lr_scheduler = accelerator.prepare(model, optimizer, lr_scheduler) + >>> accelerator.load_state("my_checkpoint") + ``` + """ + if input_dir is not None: + # Check if folder exists + input_dir = os.path.expanduser(input_dir) + if not os.path.isdir(input_dir): + raise ValueError(f"Tried to find {input_dir} but folder does not exist") + elif self.project_configuration.automatic_checkpoint_naming: + # Pick up from automatic checkpoint naming + input_dir = os.path.join(self.project_dir, "checkpoints") + folders = [os.path.join(input_dir, folder) for folder in os.listdir(input_dir)] + + def _inner(folder): + return list(map(int, re.findall(r"[\/]?([0-9]+)(?=[^\/]*$)", folder)))[0] + + folders.sort(key=_inner) + input_dir = folders[-1] + else: + raise ValueError("No input_dir provided and automatic checkpoint naming is disabled.") + logger.info(f"Loading states from {input_dir}") + + # Load the models taking care of FSDP and DeepSpeed nuances + models = [] + for i, model in enumerate(self._models): + if self.distributed_type == DistributedType.FSDP: + logger.info("Loading FSDP model") + load_fsdp_model(self.state.fsdp_plugin, self, model, input_dir, i) + logger.info(f"FSDP Model loaded from input dir {input_dir}") + elif self.distributed_type == DistributedType.DEEPSPEED: + logger.info("Loading DeepSpeed Model and Optimizer") + ckpt_id = f"{MODEL_NAME}" if i == 0 else f"{MODEL_NAME}_{i}" + model.load_checkpoint(input_dir, ckpt_id, **load_model_func_kwargs) + logger.info(f"DeepSpeed Model and Optimizer loaded from input dir {os.path.join(input_dir, ckpt_id)}") + elif self.distributed_type == DistributedType.MEGATRON_LM: + logger.info("Loading Megatron-LM Model, Optimizer and Scheduler") + model.load_checkpoint(input_dir) + logger.info(f"Megatron-LM Model , Optimizer and Scheduler loaded from input dir {input_dir}") + else: + models.append(model) + + # We need to load the scaler state before the optimizer for FSDP2 + # (`torch.distributed.checkpoint.set_optimizer_state_dict`) which we use to set the state of the optimizer calls `optimizer.step` on + # a dummy tensor, but since the scaler is not initialized, it will raise an error (the scaler exists but its `_scale` is None) + scaler = None + if self.scaler is not None and self.is_fsdp2: + input_scaler_file = os.path.join(input_dir, SCALER_NAME) + scaler_state = torch.load(input_scaler_file) + self.scaler.load_state_dict(scaler_state) + # We also need to call the `_lazy_init_scale_growth_tracker` to initialize the scaler, as it would else be called + # on the first call to scale + self.scaler._lazy_init_scale_growth_tracker(self.scaler._device) + logger.info("GradScaler state loaded successfully") + else: + scaler = self.scaler + + # Load the optimizers taking care of FSDP and DeepSpeed nuances + optimizers = [] + if self.distributed_type == DistributedType.FSDP: + for i, opt in enumerate(self._optimizers): + logger.info("Loading FSDP Optimizer") + load_fsdp_optimizer(self.state.fsdp_plugin, self, opt, self._models[i], input_dir, i) + logger.info(f"FSDP Optimizer loaded from input dir {input_dir}") + elif self.distributed_type not in [DistributedType.DEEPSPEED, DistributedType.MEGATRON_LM]: + optimizers = self._optimizers + + # Load the lr schedulers taking care of DeepSpeed nuances + schedulers = [] + if self.distributed_type == DistributedType.DEEPSPEED: + for i, scheduler in enumerate(self._schedulers): + if isinstance(scheduler, DeepSpeedSchedulerWrapper): + continue + schedulers.append(scheduler) + elif self.distributed_type not in [DistributedType.MEGATRON_LM]: + schedulers = self._schedulers + + dataloaders = self._dataloaders + + # Call model loading hooks that might have been registered with + # accelerator.register_model_state_hook + for hook in self._load_model_state_pre_hook.values(): + hook(models, input_dir) + + map_location = load_model_func_kwargs.pop("map_location", None) + if map_location is None: + if self.num_processes > 1 and self.multi_device and self.distributed_type != DistributedType.MULTI_XPU: + map_location = "on_device" + else: + map_location = "cpu" + + override_attributes = load_accelerator_state( + input_dir, + models, + optimizers, + schedulers, + dataloaders, + self.state.process_index, + scaler, + map_location, + load_kwargs, + **load_model_func_kwargs, + ) + if "step" in override_attributes: + self.step = override_attributes["step"] + custom_checkpoints = [ + f for f in os.listdir(input_dir) if re.search(r"^custom_checkpoint_\d+\.pkl$", f) is not None + ] + if len(custom_checkpoints) != len(self._custom_objects): + err = ( + f"Number of custom checkpoints in folder {input_dir} does not match the number of registered objects:" + ) + err += f"\n\tFound checkpoints: {len(custom_checkpoints)}" + err += f"\n\tRegistered objects: {len(self._custom_objects)}\n" + err += "Please make sure to only load checkpoints from folders that were created with the same set of registered objects," + err += "or avoid using `custom_checkpoint` in the filename for files in that same directory and load them in manually." + raise RuntimeError(err) + else: + logger.info(f"Loading in {len(custom_checkpoints)} custom states") + for index, obj in enumerate(self._custom_objects): + load_custom_state(obj, input_dir, index) + + def free_memory(self, *objects): + """ + Will release all references to the internal objects stored and call the garbage collector. You should call this + method between two trainings with different models/optimizers. Also will reset `Accelerator.step` to 0. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> model, optimizer, scheduler = ... + >>> model, optimizer, scheduler = accelerator.prepare(model, optimizer, scheduler) + >>> model, optimizer, scheduler = accelerator.free_memory(model, optimizer, scheduler) + ``` + """ + # Deepspeed needs a bit more prep that should be done first + if hasattr(self, "deepspeed_engine_wrapped"): + if self.deepspeed_engine_wrapped is not None: + self.deepspeed_engine_wrapped.engine.destroy() + self.deepspeed_engine_wrapped = None + objects = release_memory(*objects) + self._schedulers = [] + self._optimizers = [] + self._models = [] + self._dataloaders = [] + self.step = 0 + return objects + + def clear(self, *objects): + """ + Alias for [`Accelerate.free_memory`], releases all references to the internal objects stored and call the + garbage collector. You should call this method between two trainings with different models/optimizers. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> model, optimizer, scheduler = ... + >>> model, optimizer, scheduler = accelerator.prepare(model, optimizer, scheduler) + >>> model, optimizer, scheduler = accelerator.clear(model, optimizer, scheduler) + ``` + """ + return self.free_memory(*objects) + + def _get_named_parameters(self, *args, drop_refs=False): + named_parameters = {} + accessor_mapping = {} + for obj in args: + if isinstance(obj, torch.nn.Module): + obj = extract_model_from_parallel(obj) + if not drop_refs: + named_parameters.update({n: p for n, p in obj.named_parameters()}) + continue + + # we need this bit as `WeightWithDynamic...` returns 0 when `data_ptr()` is called, + # the underlying pointer is actually hidden in `_tensor` attribute + if self.fp8_backend == FP8BackendType.AO: + from torchao.float8.fsdp_utils import WeightWithDynamicFloat8CastTensor + + accessor_mapping[WeightWithDynamicFloat8CastTensor] = "_tensor" + # we know we're in FSDP2 so DTensor is available + if self.is_fsdp2: + from torch.distributed.tensor import DTensor + + accessor_mapping[DTensor] = "_local_tensor" + + named_parameters.update( + { + n: getattr(p, accessor_mapping[type(p)]).data_ptr() + if type(p) in accessor_mapping + else p.data_ptr() + for n, p in obj.named_parameters() + } + ) + return named_parameters + + def _get_devices(self, *args): + model_device = None + optimizer_device = None + for obj in args: + # Loop through model parameters and stop at the first once we have its device. + if isinstance(obj, torch.nn.Module): + for param in obj.parameters(): + model_device = param.device + break + # Loop through optimizer parameters groups and stop at the first once we have its device. + if isinstance(obj, torch.optim.Optimizer): + for param_group in obj.param_groups: + if len(param_group["params"]) > 0: + optimizer_device = param_group["params"][0].device + break + return (model_device, optimizer_device) + + def get_state_dict(self, model, unwrap=True): + """ + Returns the state dictionary of a model sent through [`Accelerator.prepare`] potentially without full + precision. + + Args: + model (`torch.nn.Module`): + A PyTorch model sent through [`Accelerator.prepare`] + unwrap (`bool`, *optional*, defaults to `True`): + Whether to return the original underlying state_dict of `model` or to return the wrapped state_dict + + Returns: + `dict`: The state dictionary of the model potentially without full precision. + + Example: + + ```python + >>> import torch + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> net = torch.nn.Linear(2, 2) + >>> net = accelerator.prepare(net) + >>> state_dict = accelerator.get_state_dict(net) + ``` + """ + + if self.distributed_type == DistributedType.DEEPSPEED: + zero3_sharding = self.deepspeed_config["zero_optimization"]["stage"] == 3 + tp_sharding = self.deepspeed_config.get("tensor_parallel", {}).get("autotp_size", 0) > 1 + if zero3_sharding or tp_sharding: + if model.zero_gather_16bit_weights_on_model_save(): + if tp_sharding and not compare_versions("deepspeed", ">=", "0.16.4"): + raise ImportError( + "Deepspeed TP requires deepspeed >= 0.16.4, Please update DeepSpeed via `pip install deepspeed -U`." + ) + state_dict = ( + model._consolidated_16bit_state_dict() + if tp_sharding + else model._zero3_consolidated_16bit_state_dict() + ) + else: + raise ValueError( + "Cannot get 16bit model weights because `stage3_gather_16bit_weights_on_model_save` in DeepSpeed config is False. " + "To save the model weights in 16bit, set `stage3_gather_16bit_weights_on_model_save` to True in DeepSpeed config file or " + "set `zero3_save_16bit_model` to True when using `accelerate config`. " + "To save the full checkpoint, run `model.save_checkpoint(save_dir)` and use `zero_to_fp32.py` to recover weights." + ) + else: + from deepspeed.checkpoint.utils import clone_tensors_for_torch_save + + state_dict = clone_tensors_for_torch_save(self.unwrap_model(model).state_dict()) + elif self.is_fsdp2: + from torch.distributed.checkpoint.state_dict import StateDictOptions, get_model_state_dict + + options = StateDictOptions(full_state_dict=True, broadcast_from_rank0=True, cpu_offload=True) + state_dict = get_model_state_dict(model, options=options) + elif self.distributed_type == DistributedType.FSDP: + from torch.distributed.fsdp import FullStateDictConfig, StateDictType + from torch.distributed.fsdp import FullyShardedDataParallel as FSDP + + full_state_dict_config = FullStateDictConfig(offload_to_cpu=True, rank0_only=True) + with FSDP.state_dict_type(model, StateDictType.FULL_STATE_DICT, full_state_dict_config): + state_dict = model.state_dict() + else: + if unwrap: + model = self.unwrap_model(model) + state_dict = model.state_dict() + + return state_dict + + def register_for_checkpointing(self, *objects): + """ + Makes note of `objects` and will save or load them in during `save_state` or `load_state`. + + These should be utilized when the state is being loaded or saved in the same script. It is not designed to be + used in different scripts. + + + + Every `object` must have a `load_state_dict` and `state_dict` function to be stored. + + + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> # Assume `CustomObject` has a `state_dict` and `load_state_dict` function. + >>> obj = CustomObject() + >>> accelerator.register_for_checkpointing(obj) + >>> accelerator.save_state("checkpoint.pt") + ``` + """ + invalid_objects = [] + for obj in objects: + if not hasattr(obj, "state_dict") or not hasattr(obj, "load_state_dict"): + invalid_objects.append(obj) + if len(invalid_objects) > 0: + err = "All `objects` must include a `state_dict` and `load_state_dict` function to be stored. The following inputs are invalid:" + for index, obj in enumerate(invalid_objects): + err += f"\n\t- Item at index {index}, `{get_pretty_name(obj)}`" + raise ValueError(err) + self._custom_objects.extend(objects) + + @contextmanager + def maybe_context_parallel( + self, + buffers: list[torch.Tensor] | None = None, + buffer_seq_dims: list[int] | None = None, + no_restore_buffers: set[torch.Tensor] | None = None, + ): + """ + A context manager that enables context parallel training. + + Args: + buffers (`list[torch.Tensor]`, `optional`): + Buffers, which are going to be sharded along the sequence dimension. Common examples are inputs, labels + or positional embedding buffers. This context manager will modify these buffers in-place, and after + exiting the context, the buffers will be restored to their original state. To avoid unnecessary + restores, you can use `no_restore_buffers` to specify which buffers don't need to be restored. + buffer_seq_dims (`list[int]`, `optional`): + Sequence dimensions of `buffers`. + no_restore_buffers (`set[torch.Tensor]`, `optional`): + This set must be a subset of `buffers`. Specifies which buffers from `buffers` argument won't be + restored after the context exits. These buffers will be then kept in sharded state. + + + + `context_parallel` is currently only supported together with FSDP2, and requires `parallelism_config.cp_size` > + 1. If either of these conditions are not met, this context manager will have no effect, though to enable fewer + code changes it will not raise an Exception. + + + + + + This context manager has to be recreated with each training step, as shown in the example below. + + + + Example: + + ```python + >>> for batch in dataloader: + ... with accelerator.maybe_context_parallel( + ... buffers=[batch["input_ids"], batch["attention_mask"]], + ... buffer_seq_dims=[1, 1], + ... no_restore_buffers={batch["input_ids"]}, + ... ): + ... outputs = model(batch) + ... ... + ``` + """ + # We don't need to check FSDP2 as parallelism_config does that for us + # Invariant: in this branch self._cp_context is set, as it was set by `self._prepare_cp` + if self.parallelism_config and self.parallelism_config.cp_enabled: + with self._cp_context( + buffers=buffers, buffer_seq_dims=buffer_seq_dims, no_restore_buffers=no_restore_buffers + ): + yield + else: + logger.warning_once( + "Context parallel training is not enabled. This context manager will have no effect. " + "To enable it, set `parallelism_config.cp_size` > 1 in the `Accelerator` constructor." + ) + yield + + @contextmanager + def autocast(self, autocast_handler: AutocastKwargs = None): + """ + Will apply automatic mixed-precision inside the block inside this context manager, if it is enabled. Nothing + different will happen otherwise. + + A different `autocast_handler` can be passed in to override the one set in the `Accelerator` object. This is + useful in blocks under `autocast` where you want to revert to fp32. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator(mixed_precision="fp16") + >>> with accelerator.autocast(): + ... train() + ``` + """ + if autocast_handler is None: + autocast_handler = self.autocast_handler + autocast_context = get_mixed_precision_context_manager(self.native_amp, autocast_handler) + autocast_context.__enter__() + # TODO: should the `yield` be in a try/finally block? + yield + autocast_context.__exit__(*sys.exc_info()) + + @contextmanager + def profile(self, profile_handler: ProfileKwargs | None = None): + """ + Will profile the code inside the context manager. The profile will be saved to a Chrome Trace file if + `profile_handler.output_trace_dir` is set. + + A different `profile_handler` can be passed in to override the one set in the `Accelerator` object. + + Args: + profile_handler (`ProfileKwargs`, *optional*): + The profile handler to use for this context manager. If not passed, will use the one set in the + `Accelerator` object. + + Example: + + ```python + # Profile with default settings + from accelerate import Accelerator + from accelerate.utils import ProfileKwargs + + accelerator = Accelerator() + with accelerator.profile() as prof: + train() + accelerator.print(prof.key_averages().table()) + + + # Profile with the custom handler + def custom_handler(prof): + print(prof.key_averages().table(sort_by="self_cpu_time_total", row_limit=10)) + + + kwargs = ProfileKwargs(schedule_option=dict(wait=1, warmup=1, active=1), on_trace_ready=custom_handler) + accelerator = Accelerator(kwarg_handler=[kwargs]) + with accelerator.profile() as prof: + for _ in range(10): + train_iteration() + prof.step() + + + # Profile and export to Chrome Trace + kwargs = ProfileKwargs(output_trace_dir="output_trace") + accelerator = Accelerator(kwarg_handler=[kwargs]) + with accelerator.profile(): + train() + ``` + """ + profile_handler = profile_handler or self.profile_handler or ProfileKwargs() + + with profile_handler.build() as profiler: + yield profiler + + if profile_handler.output_trace_dir is None: + return + + os.makedirs(profile_handler.output_trace_dir, exist_ok=True) + profiler.export_chrome_trace( + os.path.join(profile_handler.output_trace_dir, PROFILE_PATTERN_NAME.format(suffix=self.process_index)) + ) + self.wait_for_everyone() + + @property + def optimizer_step_was_skipped(self): + """ + Whether or not the optimizer update was skipped (because of gradient overflow in mixed precision), in which + case the learning rate should not be changed. + """ + for optimizer in self._optimizers: + if optimizer.step_was_skipped: + return True + return False + + def skip_first_batches(self, dataloader, num_batches: int = 0): + """ + Creates a new `torch.utils.data.DataLoader` that will efficiently skip the first `num_batches`. + + Args: + dataloader (`torch.utils.data.DataLoader`): The data loader in which to skip batches. + num_batches (`int`, *optional*, defaults to 0): The number of batches to skip + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> dataloader, model, optimizer, scheduler = accelerator.prepare(dataloader, model, optimizer, scheduler) + >>> skipped_dataloader = accelerator.skip_first_batches(dataloader, num_batches=2) + >>> # for the first epoch only + >>> for input, target in skipped_dataloader: + ... optimizer.zero_grad() + ... output = model(input) + ... loss = loss_func(output, target) + ... accelerator.backward(loss) + ... optimizer.step() + + >>> # subsequent epochs + >>> for input, target in dataloader: + ... optimizer.zero_grad() + ... ... + ``` + """ + return skip_first_batches(dataloader, num_batches=num_batches) + + def __deepcopy__(self, memo): + logger.info("Deep copying the `Accelerator` object, note that this will point to the same original object.") + return self + + def verify_device_map(self, model: torch.nn.Module) -> bool: + """ + Verifies that `model` has not been prepared with big model inference with a device-map resembling `auto`. + """ + # Checks if any of the child modules has the attribute `hf_device_map` and this map has more than one entry. + for m in model.modules(): + if hasattr(m, "hf_device_map") and len(m.hf_device_map) > 1: + return True + + return False + + def lomo_backward(self, loss: torch.Tensor, learning_rate: float) -> None: + """ + Runs backward pass on LOMO optimizers. + """ + if is_lomo_available(): + # We need to import locally to avoid circular imports since lomo imports stuff from + # transformers & accelerate + from lomo_optim import AdaLomo, Lomo + + if learning_rate is None: + raise ValueError("A learning rate must be passed in order to call backward pass with LOMO optimizers.") + + _backward_called = False + + for optimizer in self._optimizers: + if isinstance(optimizer.optimizer, (Lomo, AdaLomo)): + optimizer.optimizer.fused_backward(loss, learning_rate) + _backward_called = True + + if not _backward_called: + raise ValueError( + "Backward pass not properly called on LOMO optimizers. Are you sure you passed a LOMO optimizer in accelerator.prepare()?" + ) + + @property + def fp8_backend(self) -> FP8BackendType: + "Returns the configured backend for training in FP8" + if self.has_fp8_handler: + if self.fp8_recipe_handler is not None: + return FP8BackendType(self.fp8_recipe_handler.backend) + elif self.ao_recipe_handler is not None: + return FP8BackendType.AO + elif self.te_recipe_handler is not None: + return FP8BackendType.TE + elif self.msamp_recipe_handler is not None: + return FP8BackendType.MSAMP + elif self.state.deepspeed_plugin is not None and self.state.deepspeed_plugin.enable_msamp: + return FP8BackendType.MSAMP + + return FP8BackendType(parse_choice_from_env("ACCELERATE_FP8_BACKEND", "NO")) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/big_modeling.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/big_modeling.py new file mode 100644 index 0000000000000000000000000000000000000000..2bace0f5615f37c84c1c3e77fe116081ed691bac --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/big_modeling.py @@ -0,0 +1,789 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import os +import re +from contextlib import contextmanager +from functools import wraps +from typing import Optional, Union + +import torch +import torch.nn as nn + +from .hooks import ( + AlignDevicesHook, + CpuOffload, + LayerwiseCastingHook, + UserCpuOffloadHook, + add_hook_to_module, + attach_align_device_hook, + attach_align_device_hook_on_blocks, +) +from .utils import ( + OffloadedWeightsLoader, + check_cuda_p2p_ib_support, + check_device_map, + extract_submodules_state_dict, + find_tied_parameters, + get_balanced_memory, + infer_auto_device_map, + is_bnb_available, + is_mlu_available, + is_musa_available, + is_npu_available, + is_sdaa_available, + is_xpu_available, + load_checkpoint_in_model, + offload_state_dict, + parse_flag_from_env, + retie_parameters, +) +from .utils.constants import SUPPORTED_PYTORCH_LAYERS_FOR_UPCASTING +from .utils.other import recursive_getattr + + +logger = logging.getLogger(__name__) + + +@contextmanager +def init_empty_weights(include_buffers: bool = None): + """ + A context manager under which models are initialized with all parameters on the meta device, therefore creating an + empty model. Useful when just initializing the model would blow the available RAM. + + Args: + include_buffers (`bool`, *optional*): + Whether or not to also put all buffers on the meta device while initializing. + + Example: + + ```python + import torch.nn as nn + from accelerate import init_empty_weights + + # Initialize a model with 100 billions parameters in no time and without using any RAM. + with init_empty_weights(): + tst = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)]) + ``` + + + + Any model created under this context manager has no weights. As such you can't do something like + `model.to(some_device)` with it. To load weights inside your empty model, see [`load_checkpoint_and_dispatch`]. + Make sure to overwrite the default device_map param for [`load_checkpoint_and_dispatch`], otherwise dispatch is not + called. + + + """ + if include_buffers is None: + include_buffers = parse_flag_from_env("ACCELERATE_INIT_INCLUDE_BUFFERS", False) + with init_on_device(torch.device("meta"), include_buffers=include_buffers) as f: + yield f + + +@contextmanager +def init_on_device(device: torch.device, include_buffers: bool = None): + """ + A context manager under which models are initialized with all parameters on the specified device. + + Args: + device (`torch.device`): + Device to initialize all parameters on. + include_buffers (`bool`, *optional*): + Whether or not to also put all buffers on the meta device while initializing. + + Example: + + ```python + import torch.nn as nn + from accelerate import init_on_device + + with init_on_device(device=torch.device("cuda")): + tst = nn.Linear(100, 100) # on `cuda` device + ``` + """ + if include_buffers is None: + include_buffers = parse_flag_from_env("ACCELERATE_INIT_INCLUDE_BUFFERS", False) + + if include_buffers: + with device: + yield + return + + old_register_parameter = nn.Module.register_parameter + if include_buffers: + old_register_buffer = nn.Module.register_buffer + + def register_empty_parameter(module, name, param): + old_register_parameter(module, name, param) + if param is not None: + param_cls = type(module._parameters[name]) + kwargs = module._parameters[name].__dict__ + kwargs["requires_grad"] = param.requires_grad + module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs) + + def register_empty_buffer(module, name, buffer, persistent=True): + old_register_buffer(module, name, buffer, persistent=persistent) + if buffer is not None: + module._buffers[name] = module._buffers[name].to(device) + + # Patch tensor creation + if include_buffers: + tensor_constructors_to_patch = { + torch_function_name: getattr(torch, torch_function_name) + for torch_function_name in ["empty", "zeros", "ones", "full"] + } + else: + tensor_constructors_to_patch = {} + + def patch_tensor_constructor(fn): + def wrapper(*args, **kwargs): + kwargs["device"] = device + return fn(*args, **kwargs) + + return wrapper + + try: + nn.Module.register_parameter = register_empty_parameter + if include_buffers: + nn.Module.register_buffer = register_empty_buffer + for torch_function_name in tensor_constructors_to_patch.keys(): + setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name))) + yield + finally: + nn.Module.register_parameter = old_register_parameter + if include_buffers: + nn.Module.register_buffer = old_register_buffer + for torch_function_name, old_torch_function in tensor_constructors_to_patch.items(): + setattr(torch, torch_function_name, old_torch_function) + + +def cpu_offload( + model: nn.Module, + execution_device: Optional[torch.device] = None, + offload_buffers: bool = False, + state_dict: Optional[dict[str, torch.Tensor]] = None, + preload_module_classes: Optional[list[str]] = None, +): + """ + Activates full CPU offload for a model. As a result, all parameters of the model will be offloaded and only one + copy of the state dict of the model will be kept. During the forward pass, parameters will be extracted from that + state dict and put on the execution device passed as they are needed, then offloaded again. + + Args: + model (`torch.nn.Module`): + The model to offload. + execution_device (`torch.device`, *optional*): + The device on which the forward pass of the model will be executed (should be a GPU). Will default to the + model first parameter device. + offload_buffers (`bool`, *optional*, defaults to `False`): + Whether or not to offload the buffers with the model parameters. + state_dict (`Dict[str, torch.Tensor]`, *optional*): + The state dict of the model that will be kept on CPU. + preload_module_classes (`List[str]`, *optional*): + A list of classes whose instances should load all their weights (even in the submodules) at the beginning + of the forward. This should only be used for classes that have submodules which are registered but not + called directly during the forward, for instance if a `dense` linear layer is registered, but at forward, + `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly. + """ + if execution_device is None: + execution_device = next(iter(model.parameters())).device + if state_dict is None: + state_dict = {n: p.to("cpu") for n, p in model.state_dict().items()} + + add_hook_to_module(model, AlignDevicesHook(io_same_device=True), append=True) + attach_align_device_hook( + model, + execution_device=execution_device, + offload=True, + offload_buffers=offload_buffers, + weights_map=state_dict, + preload_module_classes=preload_module_classes, + ) + + return model + + +def cpu_offload_with_hook( + model: torch.nn.Module, + execution_device: Optional[Union[int, str, torch.device]] = None, + prev_module_hook: Optional[UserCpuOffloadHook] = None, +): + """ + Offloads a model on the CPU and puts it back to an execution device when executed. The difference with + [`cpu_offload`] is that the model stays on the execution device after the forward and is only offloaded again when + the `offload` method of the returned `hook` is called. Useful for pipelines running a model in a loop. + + Args: + model (`torch.nn.Module`): + The model to offload. + execution_device(`str`, `int` or `torch.device`, *optional*): + The device on which the model should be executed. Will default to the MPS device if it's available, then + GPU 0 if there is a GPU, and finally to the CPU. + prev_module_hook (`UserCpuOffloadHook`, *optional*): + The hook sent back by this function for a previous model in the pipeline you are running. If passed, its + offload method will be called just before the forward of the model to which this hook is attached. + + Example: + + ```py + model_1, hook_1 = cpu_offload_with_hook(model_1, cuda_device) + model_2, hook_2 = cpu_offload_with_hook(model_2, cuda_device, prev_module_hook=hook_1) + model_3, hook_3 = cpu_offload_with_hook(model_3, cuda_device, prev_module_hook=hook_2) + + hid_1 = model_1(input) + for i in range(50): + # model1 is offloaded on the CPU at the first iteration, model 2 stays on the GPU for this whole loop. + hid_2 = model_2(hid_1) + # model2 is offloaded to the CPU just before this forward. + hid_3 = model_3(hid_3) + + # For model3, you need to manually call the hook offload method. + hook_3.offload() + ``` + """ + hook = CpuOffload(execution_device=execution_device, prev_module_hook=prev_module_hook) + add_hook_to_module(model, hook, append=True) + user_hook = UserCpuOffloadHook(model, hook) + return model, user_hook + + +def disk_offload( + model: nn.Module, + offload_dir: Union[str, os.PathLike], + execution_device: Optional[torch.device] = None, + offload_buffers: bool = False, + preload_module_classes: Optional[list[str]] = None, +): + """ + Activates full disk offload for a model. As a result, all parameters of the model will be offloaded as + memory-mapped array in a given folder. During the forward pass, parameters will be accessed from that folder and + put on the execution device passed as they are needed, then offloaded again. + + Args: + model (`torch.nn.Module`): The model to offload. + offload_dir (`str` or `os.PathLike`): + The folder in which to offload the model weights (or where the model weights are already offloaded). + execution_device (`torch.device`, *optional*): + The device on which the forward pass of the model will be executed (should be a GPU). Will default to the + model's first parameter device. + offload_buffers (`bool`, *optional*, defaults to `False`): + Whether or not to offload the buffers with the model parameters. + preload_module_classes (`List[str]`, *optional*): + A list of classes whose instances should load all their weights (even in the submodules) at the beginning + of the forward. This should only be used for classes that have submodules which are registered but not + called directly during the forward, for instance if a `dense` linear layer is registered, but at forward, + `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly. + """ + if not os.path.isdir(offload_dir) or not os.path.isfile(os.path.join(offload_dir, "index.json")): + offload_state_dict(offload_dir, model.state_dict()) + if execution_device is None: + execution_device = next(iter(model.parameters())).device + weights_map = OffloadedWeightsLoader(save_folder=offload_dir) + + add_hook_to_module(model, AlignDevicesHook(io_same_device=True), append=True) + attach_align_device_hook( + model, + execution_device=execution_device, + offload=True, + offload_buffers=offload_buffers, + weights_map=weights_map, + preload_module_classes=preload_module_classes, + ) + + return model + + +def dispatch_model( + model: nn.Module, + device_map: dict[str, Union[str, int, torch.device]], + main_device: Optional[torch.device] = None, + state_dict: Optional[dict[str, torch.Tensor]] = None, + offload_dir: Optional[Union[str, os.PathLike]] = None, + offload_index: Optional[dict[str, str]] = None, + offload_buffers: bool = False, + skip_keys: Optional[Union[str, list[str]]] = None, + preload_module_classes: Optional[list[str]] = None, + force_hooks: bool = False, +): + """ + Dispatches a model according to a given device map. Layers of the model might be spread across GPUs, offloaded on + the CPU or even the disk. + + Args: + model (`torch.nn.Module`): + The model to dispatch. + device_map (`Dict[str, Union[str, int, torch.device]]`): + A dictionary mapping module names in the models `state_dict` to the device they should go to. Note that + `"disk"` is accepted even if it's not a proper value for `torch.device`. + main_device (`str`, `int` or `torch.device`, *optional*): + The main execution device. Will default to the first device in the `device_map` different from `"cpu"` or + `"disk"`. + state_dict (`Dict[str, torch.Tensor]`, *optional*): + The state dict of the part of the model that will be kept on CPU. + offload_dir (`str` or `os.PathLike`): + The folder in which to offload the model weights (or where the model weights are already offloaded). + offload_index (`Dict`, *optional*): + A dictionary from weight name to their information (`dtype`/ `shape` or safetensors filename). Will default + to the index saved in `save_folder`. + offload_buffers (`bool`, *optional*, defaults to `False`): + Whether or not to offload the buffers with the model parameters. + skip_keys (`str` or `List[str]`, *optional*): + A list of keys to ignore when moving inputs or outputs between devices. + preload_module_classes (`List[str]`, *optional*): + A list of classes whose instances should load all their weights (even in the submodules) at the beginning + of the forward. This should only be used for classes that have submodules which are registered but not + called directly during the forward, for instance if a `dense` linear layer is registered, but at forward, + `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly. + force_hooks (`bool`, *optional*, defaults to `False`): + Whether or not to force device hooks to be attached to the model even if all layers are dispatched to a + single device. + """ + # Error early if the device map is incomplete. + check_device_map(model, device_map) + + # We need to force hook for quantized model that can't be moved with to() + if getattr(model, "quantization_method", "bitsandbytes") == "bitsandbytes": + # since bnb 0.43.2, we can move 4-bit model + if getattr(model, "is_loaded_in_8bit", False) or ( + getattr(model, "is_loaded_in_4bit", False) and not is_bnb_available(min_version="0.43.2") + ): + force_hooks = True + + # We attach hooks if the device_map has at least 2 different devices or if + # force_hooks is set to `True`. Otherwise, the model in already loaded + # in the unique device and the user can decide where to dispatch the model. + # If the model is quantized, we always force-dispatch the model + if (len(set(device_map.values())) > 1) or force_hooks: + if main_device is None: + if set(device_map.values()) == {"cpu"} or set(device_map.values()) == {"cpu", "disk"}: + main_device = "cpu" + else: + main_device = [d for d in device_map.values() if d not in ["cpu", "disk"]][0] + + if main_device != "cpu": + cpu_modules = [name for name, device in device_map.items() if device == "cpu"] + if state_dict is None and len(cpu_modules) > 0: + state_dict = extract_submodules_state_dict(model.state_dict(), cpu_modules) + + disk_modules = [name for name, device in device_map.items() if device == "disk"] + if offload_dir is None and offload_index is None and len(disk_modules) > 0: + raise ValueError( + "We need an `offload_dir` to dispatch this model according to this `device_map`, the following submodules " + f"need to be offloaded: {', '.join(disk_modules)}." + ) + if ( + len(disk_modules) > 0 + and offload_index is None + and (not os.path.isdir(offload_dir) or not os.path.isfile(os.path.join(offload_dir, "index.json"))) + ): + disk_state_dict = extract_submodules_state_dict(model.state_dict(), disk_modules) + offload_state_dict(offload_dir, disk_state_dict) + + execution_device = { + name: main_device if device in ["cpu", "disk"] else device for name, device in device_map.items() + } + execution_device[""] = main_device + offloaded_devices = ["disk"] if main_device == "cpu" or main_device == "mps" else ["cpu", "disk"] + offload = {name: device in offloaded_devices for name, device in device_map.items()} + save_folder = offload_dir if len(disk_modules) > 0 else None + if state_dict is not None or save_folder is not None or offload_index is not None: + device = main_device if offload_index is not None else None + weights_map = OffloadedWeightsLoader( + state_dict=state_dict, save_folder=save_folder, index=offload_index, device=device + ) + else: + weights_map = None + + # When dispatching the model's parameters to the devices specified in device_map, we want to avoid allocating memory several times for the + # tied parameters. The dictionary tied_params_map keeps track of the already allocated data for a given tied parameter (represented by its + # original pointer) on each devices. + tied_params = find_tied_parameters(model) + + tied_params_map = {} + for group in tied_params: + for param_name in group: + # data_ptr() is enough here, as `find_tied_parameters` finds tied params simply by comparing `param1 is param2`, so we don't need + # to care about views of tensors through storage_offset. + data_ptr = recursive_getattr(model, param_name).data_ptr() + tied_params_map[data_ptr] = {} + + # Note: To handle the disk offloading case, we can not simply use weights_map[param_name].data_ptr() as the reference pointer, + # as we have no guarantee that safetensors' `file.get_tensor()` will always give the same pointer. + + attach_align_device_hook_on_blocks( + model, + execution_device=execution_device, + offload=offload, + offload_buffers=offload_buffers, + weights_map=weights_map, + skip_keys=skip_keys, + preload_module_classes=preload_module_classes, + tied_params_map=tied_params_map, + ) + + # warn if there is any params on the meta device + offloaded_devices_str = " and ".join( + [device for device in set(device_map.values()) if device in ("cpu", "disk")] + ) + if len(offloaded_devices_str) > 0: + logger.warning( + f"Some parameters are on the meta device because they were offloaded to the {offloaded_devices_str}." + ) + + # Attaching the hook may break tied weights, so we retie them + retie_parameters(model, tied_params) + + # add warning to cuda and to method + def add_warning(fn, model): + @wraps(fn) + def wrapper(*args, **kwargs): + warning_msg = "You shouldn't move a model that is dispatched using accelerate hooks." + if str(fn.__name__) == "to": + to_device = torch._C._nn._parse_to(*args, **kwargs)[0] + if to_device is not None: + logger.warning(warning_msg) + else: + logger.warning(warning_msg) + for param in model.parameters(): + if param.device == torch.device("meta"): + raise RuntimeError("You can't move a model that has some modules offloaded to cpu or disk.") + return fn(*args, **kwargs) + + return wrapper + + # Make sure to update _accelerate_added_attributes in hooks.py if you add any hook + model.to = add_warning(model.to, model) + if is_npu_available(): + model.npu = add_warning(model.npu, model) + elif is_mlu_available(): + model.mlu = add_warning(model.mlu, model) + elif is_sdaa_available(): + model.sdaa = add_warning(model.sdaa, model) + elif is_musa_available(): + model.musa = add_warning(model.musa, model) + elif is_xpu_available(): + model.xpu = add_warning(model.xpu, model) + else: + model.cuda = add_warning(model.cuda, model) + + # Check if we are using multi-gpus with RTX 4000 series + use_multi_gpu = len([device for device in set(device_map.values()) if device not in ("cpu", "disk")]) > 1 + if use_multi_gpu and not check_cuda_p2p_ib_support(): + logger.warning( + "We've detected an older driver with an RTX 4000 series GPU. These drivers have issues with P2P. " + "This can affect the multi-gpu inference when using accelerate device_map." + "Please make sure to update your driver to the latest version which resolves this." + ) + else: + device = list(device_map.values())[0] + # `torch.Tensor.to()` is not supported by `torch_npu` (see this [issue](https://github.com/Ascend/pytorch/issues/16)). + if is_npu_available() and isinstance(device, int): + device = f"npu:{device}" + elif is_mlu_available() and isinstance(device, int): + device = f"mlu:{device}" + elif is_sdaa_available() and isinstance(device, int): + device = f"sdaa:{device}" + elif is_musa_available() and isinstance(device, int): + device = f"musa:{device}" + if device != "disk": + model.to(device) + else: + raise ValueError( + "You are trying to offload the whole model to the disk. Please use the `disk_offload` function instead." + ) + # Convert OrderedDict back to dict for easier usage + model.hf_device_map = dict(device_map) + return model + + +def load_checkpoint_and_dispatch( + model: nn.Module, + checkpoint: Union[str, os.PathLike], + device_map: Optional[Union[str, dict[str, Union[int, str, torch.device]]]] = None, + max_memory: Optional[dict[Union[int, str], Union[int, str]]] = None, + no_split_module_classes: Optional[list[str]] = None, + offload_folder: Optional[Union[str, os.PathLike]] = None, + offload_buffers: bool = False, + dtype: Optional[Union[str, torch.dtype]] = None, + offload_state_dict: Optional[bool] = None, + skip_keys: Optional[Union[str, list[str]]] = None, + preload_module_classes: Optional[list[str]] = None, + force_hooks: bool = False, + strict: bool = False, + full_state_dict: bool = True, + broadcast_from_rank0: bool = False, +): + """ + Loads a (potentially sharded) checkpoint inside a model, potentially sending weights to a given device as they are + loaded and adds the various hooks that will make this model run properly (even if split across devices). + + Args: + model (`torch.nn.Module`): The model in which we want to load a checkpoint. + checkpoint (`str` or `os.PathLike`): + The folder checkpoint to load. It can be: + - a path to a file containing a whole model state dict + - a path to a `.json` file containing the index to a sharded checkpoint + - a path to a folder containing a unique `.index.json` file and the shards of a checkpoint. + device_map (`Dict[str, Union[int, str, torch.device]]`, *optional*): + A map that specifies where each submodule should go. It doesn't need to be refined to each parameter/buffer + name, once a given module name is inside, every submodule of it will be sent to the same device. + + To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For more + information about each option see [here](../concept_guides/big_model_inference#designing-a-device-map). + Defaults to None, which means [`dispatch_model`] will not be called. + max_memory (`Dict`, *optional*): + A dictionary device identifier to maximum memory. Will default to the maximum memory available for each GPU + and the available CPU RAM if unset. + no_split_module_classes (`List[str]`, *optional*): + A list of layer class names that should never be split across device (for instance any layer that has a + residual connection). + offload_folder (`str` or `os.PathLike`, *optional*): + If the `device_map` contains any value `"disk"`, the folder where we will offload weights. + offload_buffers (`bool`, *optional*, defaults to `False`): + In the layers that are offloaded on the CPU or the hard drive, whether or not to offload the buffers as + well as the parameters. + dtype (`str` or `torch.dtype`, *optional*): + If provided, the weights will be converted to that type when loaded. + offload_state_dict (`bool`, *optional*): + If `True`, will temporarily offload the CPU state dict on the hard drive to avoid getting out of CPU RAM if + the weight of the CPU state dict + the biggest shard does not fit. Will default to `True` if the device map + picked contains `"disk"` values. + skip_keys (`str` or `List[str]`, *optional*): + A list of keys to ignore when moving inputs or outputs between devices. + preload_module_classes (`List[str]`, *optional*): + A list of classes whose instances should load all their weights (even in the submodules) at the beginning + of the forward. This should only be used for classes that have submodules which are registered but not + called directly during the forward, for instance if a `dense` linear layer is registered, but at forward, + `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly. + force_hooks (`bool`, *optional*, defaults to `False`): + Whether or not to force device hooks to be attached to the model even if all layers are dispatched to a + single device. + strict (`bool`, *optional*, defaults to `False`): + Whether to strictly enforce that the keys in the checkpoint state_dict match the keys of the model's + state_dict. + full_state_dict (`bool`, *optional*, defaults to `True`): if this is set to `True`, all the tensors in the + loaded state_dict will be gathered. No ShardedTensor and DTensor will be in the loaded state_dict. + broadcast_from_rank0 (`False`, *optional*, defaults to `False`): when the option is `True`, a distributed + `ProcessGroup` must be initialized. rank0 should receive a full state_dict and will broadcast the tensors + in the state_dict one by one to other ranks. Other ranks will receive the tensors and shard (if applicable) + according to the local shards in the model. + + Example: + + ```python + >>> from accelerate import init_empty_weights, load_checkpoint_and_dispatch + >>> from huggingface_hub import hf_hub_download + >>> from transformers import AutoConfig, AutoModelForCausalLM + + >>> # Download the Weights + >>> checkpoint = "EleutherAI/gpt-j-6B" + >>> weights_location = hf_hub_download(checkpoint, "pytorch_model.bin") + + >>> # Create a model and initialize it with empty weights + >>> config = AutoConfig.from_pretrained(checkpoint) + >>> with init_empty_weights(): + ... model = AutoModelForCausalLM.from_config(config) + + >>> # Load the checkpoint and dispatch it to the right devices + >>> model = load_checkpoint_and_dispatch( + ... model, weights_location, device_map="auto", no_split_module_classes=["GPTJBlock"] + ... ) + ``` + """ + if isinstance(device_map, str) and device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: + raise ValueError( + "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or 'sequential'." + ) + if isinstance(device_map, str): + if device_map != "sequential": + max_memory = get_balanced_memory( + model, + max_memory=max_memory, + no_split_module_classes=no_split_module_classes, + dtype=dtype, + low_zero=(device_map == "balanced_low_0"), + ) + device_map = infer_auto_device_map( + model, + max_memory=max_memory, + no_split_module_classes=no_split_module_classes, + dtype=dtype, + offload_buffers=offload_buffers, + ) + if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): + offload_state_dict = True + load_checkpoint_in_model( + model, + checkpoint, + device_map=device_map, + offload_folder=offload_folder, + dtype=dtype, + offload_state_dict=offload_state_dict, + offload_buffers=offload_buffers, + strict=strict, + full_state_dict=full_state_dict, + broadcast_from_rank0=broadcast_from_rank0, + ) + if device_map is None: + return model + return dispatch_model( + model, + device_map=device_map, + offload_dir=offload_folder, + offload_buffers=offload_buffers, + skip_keys=skip_keys, + preload_module_classes=preload_module_classes, + force_hooks=force_hooks, + ) + + +def attach_layerwise_casting_hooks( + module: torch.nn.Module, + storage_dtype: torch.dtype, + compute_dtype: torch.dtype, + skip_modules_pattern: Union[str, tuple[str, ...]] = None, + skip_modules_classes: Optional[tuple[type[torch.nn.Module], ...]] = None, + non_blocking: bool = False, +) -> None: + r""" + Applies layerwise casting to a given module. The module expected here is a PyTorch `nn.Module`. This is helpful for + reducing memory requirements when one doesn't want to fully quantize a model. Model params can be kept in say, + `torch.float8_e4m3fn` and upcasted to a higher precision like `torch.bfloat16` during forward pass and downcasted + back to `torch.float8_e4m3fn` to realize memory savings. + + Args: + module (`torch.nn.Module`): + The module whose leaf modules will be cast to a high precision dtype for computation, and to a low + precision dtype for storage. + storage_dtype (`torch.dtype`): + The dtype to cast the module to before/after the forward pass for storage. + compute_dtype (`torch.dtype`): + The dtype to cast the module to during the forward pass for computation. + skip_modules_pattern (`tuple[str, ...]`, defaults to `None`): + A list of patterns to match the names of the modules to skip during the layerwise casting process. If set + to `None` alongside `skip_modules_classes` being `None`, the layerwise casting is applied directly to the + module instead of its internal submodules. + skip_modules_classes (`tuple[type[torch.nn.Module], ...]`, defaults to `None`): + A list of module classes to skip during the layerwise casting process. + non_blocking (`bool`, defaults to `False`): + If `True`, the weight casting operations are non-blocking. + + Example: + + ```python + >>> from accelerate.hooks import attach_layerwise_casting_hooks + >>> from transformers import AutoModelForCausalLM + >>> import torch + + >>> # Model + >>> checkpoint = "EleutherAI/gpt-j-6B" + >>> model = AutoModelForCausalLM.from_pretrained(checkpoint) + + >>> # Attach hooks and perform inference + >>> attach_layerwise_casting_hooks(model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16) + >>> with torch.no_grad(): + ... model(...) + ``` + + Users can also pass modules they want to avoid from getting downcasted. + + ```py + >>> attach_layerwise_casting_hooks( + ... model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16, skip_modules_pattern=["norm"] + ... ) + ``` + """ + _attach_layerwise_casting_hooks( + module, storage_dtype, compute_dtype, skip_modules_pattern, skip_modules_classes, non_blocking + ) + + +def _attach_layerwise_casting_hooks( + module: torch.nn.Module, + storage_dtype: torch.dtype, + compute_dtype: torch.dtype, + skip_modules_pattern: Union[str, tuple[str, ...]] = None, + skip_modules_classes: Optional[tuple[type[torch.nn.Module], ...]] = None, + non_blocking: bool = False, + _prefix: str = "", +): + should_skip = (skip_modules_classes is not None and isinstance(module, skip_modules_classes)) or ( + skip_modules_pattern is not None and any(re.search(pattern, _prefix) for pattern in skip_modules_pattern) + ) + if should_skip: + logger.debug(f'Skipping layerwise casting for layer "{_prefix}"') + return + + if isinstance(module, SUPPORTED_PYTORCH_LAYERS_FOR_UPCASTING): + logger.debug(f'Applying layerwise casting to layer "{_prefix}"') + add_hook_to_module( + module, + LayerwiseCastingHook(storage_dtype=storage_dtype, compute_dtype=compute_dtype, non_blocking=non_blocking), + append=True, + ) + return + + for name, submodule in module.named_children(): + layer_name = f"{_prefix}.{name}" if _prefix else name + _attach_layerwise_casting_hooks( + submodule, + storage_dtype, + compute_dtype, + skip_modules_pattern, + skip_modules_classes, + non_blocking, + _prefix=layer_name, + ) + + +def _attach_context_parallel_hooks( + model: nn.Module, +): + """ + Monkeypatch huggingface's `transformers` model to fix attention mask issues when using context parallelism. + + This function attaches forward_pre_hooks to each self_attn module of the model, where each hook checks the + args/kwargs, if they contain an attention mask, if it does, it will remove this mask, check if it is a causal mask, + if yes, will add a kwarg `is_causal=True`, otherwise will raise an error. This is because context parallelism does + not support attention masks. This function modifies the model in place. + + Args: + model (`nn.Module`): + The model to attach the hooks to. + + """ + + def _self_attn_pre_forward_hook(_module, module_args, module_kwargs): + if "attention_mask" in module_kwargs: + module_kwargs["attention_mask"] = None + module_kwargs["is_causal"] = True + + return module_args, module_kwargs + + for name, module in model.named_modules(): + # We hope (assume) that if user uses their own model (without this structure which transformers uses), they read the docs saying they can't pass in attention masks + # Then these cases can happen: + # 1) some modules end with a `self-attn` module, in which case we attach the hook, but the + # there's no attention mask kwarg -> hook is a no-op + # 2) some modules end with a `self-attn` module, in which case we attach the hook, and the + # attention mask kwarg is passed -> hook will remove the attention mask and add + # `is_causal=True` kwarg, which either crashes the training or fixes it + # (training would crash anyway as attention mask isn't supported) + # 3) no modules end with a `self-attn` module, in which case we don't attach the hook, this is + # a no-op as well + if name.endswith("self_attn"): + # we want the hook to be executed first, to avoid any other hooks doing work on the attention mask + module.register_forward_pre_hook(_self_attn_pre_forward_hook, with_kwargs=True, prepend=True) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/checkpointing.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/checkpointing.py new file mode 100644 index 0000000000000000000000000000000000000000..425dd3fecd323dc2cf161ff5b427662b82ee823b --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/checkpointing.py @@ -0,0 +1,330 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import random +from pathlib import Path + +import numpy as np +import torch +from safetensors.torch import load_model + +from .utils import ( + MODEL_NAME, + OPTIMIZER_NAME, + RNG_STATE_NAME, + SAFE_MODEL_NAME, + SAFE_WEIGHTS_NAME, + SAMPLER_NAME, + SCALER_NAME, + SCHEDULER_NAME, + WEIGHTS_NAME, + get_pretty_name, + is_cuda_available, + is_hpu_available, + is_mlu_available, + is_musa_available, + is_sdaa_available, + is_torch_version, + is_torch_xla_available, + is_xpu_available, + load, + save, +) + + +if is_torch_version(">=", "2.4.0"): + from torch.amp import GradScaler +else: + from torch.cuda.amp import GradScaler + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + +from .logging import get_logger +from .state import PartialState + + +logger = get_logger(__name__) + + +def save_accelerator_state( + output_dir: str, + model_states: list[dict], + optimizers: list, + schedulers: list, + dataloaders: list, + process_index: int, + step: int, + scaler: GradScaler = None, + save_on_each_node: bool = False, + safe_serialization: bool = True, +): + """ + Saves the current states of the models, optimizers, scaler, and RNG generators to a given directory. + + + + If `safe_serialization` is `True`, models will be saved with `safetensors` while the rest are saved using native + `pickle`. + + + + Args: + output_dir (`str` or `os.PathLike`): + The name of the folder to save all relevant weights and states. + model_states (`List[torch.nn.Module]`): + A list of model states + optimizers (`List[torch.optim.Optimizer]`): + A list of optimizer instances + schedulers (`List[torch.optim.lr_scheduler._LRScheduler]`): + A list of learning rate schedulers + dataloaders (`List[torch.utils.data.DataLoader]`): + A list of dataloader instances to save their sampler states + process_index (`int`): + The current process index in the Accelerator state + step (`int`): + The current step in the internal step tracker + scaler (`torch.amp.GradScaler`, *optional*): + An optional gradient scaler instance to save; + save_on_each_node (`bool`, *optional*): + Whether to save on every node, or only the main node. + safe_serialization (`bool`, *optional*, defaults to `True`): + Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`). + """ + output_dir = Path(output_dir) + # Model states + for i, state in enumerate(model_states): + weights_name = WEIGHTS_NAME if not safe_serialization else SAFE_WEIGHTS_NAME + if i > 0: + weights_name = weights_name.replace(".", f"_{i}.") + output_model_file = output_dir.joinpath(weights_name) + save(state, output_model_file, save_on_each_node=save_on_each_node, safe_serialization=safe_serialization) + logger.info(f"Model weights saved in {output_model_file}") + # Optimizer states + for i, opt in enumerate(optimizers): + state = opt.state_dict() + optimizer_name = f"{OPTIMIZER_NAME}.bin" if i == 0 else f"{OPTIMIZER_NAME}_{i}.bin" + output_optimizer_file = output_dir.joinpath(optimizer_name) + save(state, output_optimizer_file, save_on_each_node=save_on_each_node, safe_serialization=False) + logger.info(f"Optimizer state saved in {output_optimizer_file}") + # Scheduler states + for i, scheduler in enumerate(schedulers): + state = scheduler.state_dict() + scheduler_name = f"{SCHEDULER_NAME}.bin" if i == 0 else f"{SCHEDULER_NAME}_{i}.bin" + output_scheduler_file = output_dir.joinpath(scheduler_name) + save(state, output_scheduler_file, save_on_each_node=save_on_each_node, safe_serialization=False) + logger.info(f"Scheduler state saved in {output_scheduler_file}") + # DataLoader states + for i, dataloader in enumerate(dataloaders): + sampler_name = f"{SAMPLER_NAME}.bin" if i == 0 else f"{SAMPLER_NAME}_{i}.bin" + output_sampler_file = output_dir.joinpath(sampler_name) + # Only save if we have our custom sampler + from .data_loader import IterableDatasetShard, SeedableRandomSampler + + if isinstance(dataloader.dataset, IterableDatasetShard): + sampler = dataloader.get_sampler() + if isinstance(sampler, SeedableRandomSampler): + save(sampler, output_sampler_file, save_on_each_node=save_on_each_node, safe_serialization=False) + if getattr(dataloader, "use_stateful_dataloader", False): + dataloader_state_dict_name = "dl_state_dict.bin" if i == 0 else f"dl_state_dict_{i}.bin" + output_dataloader_state_dict_file = output_dir.joinpath(dataloader_state_dict_name) + state_dict = dataloader.state_dict() + torch.save(state_dict, output_dataloader_state_dict_file) + logger.info(f"Sampler state for dataloader {i} saved in {output_sampler_file}") + + # GradScaler state + if scaler is not None: + state = scaler.state_dict() + output_scaler_file = output_dir.joinpath(SCALER_NAME) + torch.save(state, output_scaler_file) + logger.info(f"Gradient scaler state saved in {output_scaler_file}") + # Random number generator states + states = {} + states_name = f"{RNG_STATE_NAME}_{process_index}.pkl" + states["step"] = step + states["random_state"] = random.getstate() + states["numpy_random_seed"] = np.random.get_state() + states["torch_manual_seed"] = torch.get_rng_state() + if is_xpu_available(): + states["torch_xpu_manual_seed"] = torch.xpu.get_rng_state_all() + if is_mlu_available(): + states["torch_mlu_manual_seed"] = torch.mlu.get_rng_state_all() + elif is_sdaa_available(): + states["torch_sdaa_manual_seed"] = torch.sdaa.get_rng_state_all() + elif is_musa_available(): + states["torch_musa_manual_seed"] = torch.musa.get_rng_state_all() + if is_hpu_available(): + states["torch_hpu_manual_seed"] = torch.hpu.get_rng_state_all() + if is_cuda_available(): + states["torch_cuda_manual_seed"] = torch.cuda.get_rng_state_all() + if is_torch_xla_available(): + states["xm_seed"] = xm.get_rng_state() + output_states_file = output_dir.joinpath(states_name) + torch.save(states, output_states_file) + logger.info(f"Random states saved in {output_states_file}") + return output_dir + + +def load_accelerator_state( + input_dir, + models, + optimizers, + schedulers, + dataloaders, + process_index, + scaler=None, + map_location=None, + load_kwargs=None, + **load_model_func_kwargs, +): + """ + Loads states of the models, optimizers, scaler, and RNG generators from a given directory. + + Args: + input_dir (`str` or `os.PathLike`): + The name of the folder to load all relevant weights and states. + models (`List[torch.nn.Module]`): + A list of model instances + optimizers (`List[torch.optim.Optimizer]`): + A list of optimizer instances + schedulers (`List[torch.optim.lr_scheduler._LRScheduler]`): + A list of learning rate schedulers + process_index (`int`): + The current process index in the Accelerator state + scaler (`torch.amp.GradScaler`, *optional*): + An optional *GradScaler* instance to load + map_location (`str`, *optional*): + What device to load the optimizer state onto. Should be one of either "cpu" or "on_device". + load_kwargs (`dict`, *optional*): + Additional arguments that can be passed to the `load` function. + load_model_func_kwargs (`dict`, *optional*): + Additional arguments that can be passed to the model's `load_state_dict` method. + + Returns: + `dict`: Contains the `Accelerator` attributes to override while loading the state. + """ + # stores the `Accelerator` attributes to override + override_attributes = dict() + if map_location not in [None, "cpu", "on_device"]: + raise TypeError( + "Unsupported optimizer map location passed, please choose one of `None`, `'cpu'`, or `'on_device'`" + ) + if map_location is None: + map_location = "cpu" + elif map_location == "on_device": + map_location = PartialState().device + + if load_kwargs is None: + load_kwargs = {} + + input_dir = Path(input_dir) + # Model states + for i, model in enumerate(models): + ending = f"_{i}" if i > 0 else "" + input_model_file = input_dir.joinpath(f"{SAFE_MODEL_NAME}{ending}.safetensors") + if input_model_file.exists(): + load_model(model, input_model_file, device=str(map_location), **load_model_func_kwargs) + else: + # Load with torch + input_model_file = input_dir.joinpath(f"{MODEL_NAME}{ending}.bin") + state_dict = load(input_model_file, map_location=map_location) + model.load_state_dict(state_dict, **load_model_func_kwargs) + logger.info("All model weights loaded successfully") + + # Optimizer states + for i, opt in enumerate(optimizers): + optimizer_name = f"{OPTIMIZER_NAME}.bin" if i == 0 else f"{OPTIMIZER_NAME}_{i}.bin" + input_optimizer_file = input_dir.joinpath(optimizer_name) + optimizer_state = load(input_optimizer_file, map_location=map_location, **load_kwargs) + optimizers[i].load_state_dict(optimizer_state) + logger.info("All optimizer states loaded successfully") + + # Scheduler states + for i, scheduler in enumerate(schedulers): + scheduler_name = f"{SCHEDULER_NAME}.bin" if i == 0 else f"{SCHEDULER_NAME}_{i}.bin" + input_scheduler_file = input_dir.joinpath(scheduler_name) + scheduler_state = load(input_scheduler_file, **load_kwargs) + scheduler.load_state_dict(scheduler_state) + logger.info("All scheduler states loaded successfully") + + for i, dataloader in enumerate(dataloaders): + sampler_name = f"{SAMPLER_NAME}.bin" if i == 0 else f"{SAMPLER_NAME}_{i}.bin" + input_sampler_file = input_dir.joinpath(sampler_name) + # Only load if we have our custom sampler + from .data_loader import IterableDatasetShard, SeedableRandomSampler + + if isinstance(dataloader.dataset, IterableDatasetShard): + sampler = dataloader.get_sampler() + if isinstance(sampler, SeedableRandomSampler): + sampler = dataloader.set_sampler(load(input_sampler_file)) + if getattr(dataloader, "use_stateful_dataloader", False): + dataloader_state_dict_name = "dl_state_dict.bin" if i == 0 else f"dl_state_dict_{i}.bin" + input_dataloader_state_dict_file = input_dir.joinpath(dataloader_state_dict_name) + if input_dataloader_state_dict_file.exists(): + state_dict = load(input_dataloader_state_dict_file, **load_kwargs) + dataloader.load_state_dict(state_dict) + logger.info("All dataloader sampler states loaded successfully") + + # GradScaler state + if scaler is not None: + input_scaler_file = input_dir.joinpath(SCALER_NAME) + scaler_state = load(input_scaler_file) + scaler.load_state_dict(scaler_state) + logger.info("GradScaler state loaded successfully") + + # Random states + try: + states = load(input_dir.joinpath(f"{RNG_STATE_NAME}_{process_index}.pkl")) + if "step" in states: + override_attributes["step"] = states["step"] + random.setstate(states["random_state"]) + np.random.set_state(states["numpy_random_seed"]) + torch.set_rng_state(states["torch_manual_seed"]) + if is_xpu_available(): + torch.xpu.set_rng_state_all(states["torch_xpu_manual_seed"]) + if is_mlu_available(): + torch.mlu.set_rng_state_all(states["torch_mlu_manual_seed"]) + elif is_sdaa_available(): + torch.sdaa.set_rng_state_all(states["torch_sdaa_manual_seed"]) + elif is_musa_available(): + torch.musa.set_rng_state_all(states["torch_musa_manual_seed"]) + else: + torch.cuda.set_rng_state_all(states["torch_cuda_manual_seed"]) + if is_torch_xla_available(): + xm.set_rng_state(states["xm_seed"]) + logger.info("All random states loaded successfully") + except Exception: + logger.info("Could not load random states") + + return override_attributes + + +def save_custom_state(obj, path, index: int = 0, save_on_each_node: bool = False): + """ + Saves the state of `obj` to `{path}/custom_checkpoint_{index}.pkl` + """ + # Should this be the right way to get a qual_name type value from `obj`? + save_location = Path(path) / f"custom_checkpoint_{index}.pkl" + logger.info(f"Saving the state of {get_pretty_name(obj)} to {save_location}") + save(obj.state_dict(), save_location, save_on_each_node=save_on_each_node) + + +def load_custom_state(obj, path, index: int = 0): + """ + Loads the state of `obj` at `{path}/custom_checkpoint_{index}.pkl`. Will always set `weights_only=False` when + loading the state. + """ + load_location = f"{path}/custom_checkpoint_{index}.pkl" + logger.info(f"Loading the state of {get_pretty_name(obj)} from {load_location}") + obj.load_state_dict(load(load_location, map_location="cpu", weights_only=False)) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/__init__.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c9cbe26c257b515f657c05e1996d517e69613972 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/accelerate_cli.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/accelerate_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..b878c8debd874e1418b946775b11568c7487ad72 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/accelerate_cli.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python + +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from accelerate.commands.config import get_config_parser +from accelerate.commands.env import env_command_parser +from accelerate.commands.estimate import estimate_command_parser +from accelerate.commands.launch import launch_command_parser +from accelerate.commands.merge import merge_command_parser +from accelerate.commands.test import test_command_parser +from accelerate.commands.to_fsdp2 import to_fsdp2_command_parser +from accelerate.commands.tpu import tpu_command_parser +from accelerate.commands.utils import CustomArgumentParser + + +def main(): + parser = CustomArgumentParser("Accelerate CLI tool", usage="accelerate []", allow_abbrev=False) + subparsers = parser.add_subparsers(help="accelerate command helpers") + + # Register commands + get_config_parser(subparsers=subparsers) + estimate_command_parser(subparsers=subparsers) + env_command_parser(subparsers=subparsers) + launch_command_parser(subparsers=subparsers) + merge_command_parser(subparsers=subparsers) + tpu_command_parser(subparsers=subparsers) + test_command_parser(subparsers=subparsers) + to_fsdp2_command_parser(subparsers=subparsers) + + # Let's go + args = parser.parse_args() + + if not hasattr(args, "func"): + parser.print_help() + exit(1) + + # Run + args.func(args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/__init__.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..649a15888cccd070b3d4ca9a600457c6ad59d4d3 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/__init__.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python + +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse + +from .config import config_command_parser +from .config_args import default_config_file, load_config_from_file # noqa: F401 +from .default import default_command_parser +from .update import update_command_parser + + +def get_config_parser(subparsers=None): + parent_parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False) + # The main config parser + config_parser = config_command_parser(subparsers) + # The subparser to add commands to + subcommands = config_parser.add_subparsers(title="subcommands", dest="subcommand") + + # Then add other parsers with the parent parser + default_command_parser(subcommands, parents=[parent_parser]) + update_command_parser(subcommands, parents=[parent_parser]) + + return config_parser + + +def main(): + config_parser = get_config_parser() + args = config_parser.parse_args() + + if not hasattr(args, "func"): + config_parser.print_help() + exit(1) + + # Run + args.func(args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/cluster.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/cluster.py new file mode 100644 index 0000000000000000000000000000000000000000..e466ba8048beb2b024e5903552a4f2de2416f86c --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/cluster.py @@ -0,0 +1,917 @@ +#!/usr/bin/env python + +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os + +from ...utils import ( + ComputeEnvironment, + DistributedType, + is_deepspeed_available, + is_fp8_available, + is_hpu_available, + is_mlu_available, + is_mps_available, + is_msamp_available, + is_musa_available, + is_npu_available, + is_sdaa_available, + is_transformer_engine_available, + is_transformers_available, + is_xpu_available, +) +from ...utils.constants import ( + DEEPSPEED_MULTINODE_LAUNCHERS, + FSDP2_STATE_DICT_TYPE, + FSDP_AUTO_WRAP_POLICY, + FSDP_BACKWARD_PREFETCH, + FSDP_SHARDING_STRATEGY, + FSDP_STATE_DICT_TYPE, + TORCH_DYNAMO_MODES, +) +from .config_args import ClusterConfig +from .config_utils import ( + DYNAMO_BACKENDS, + _ask_field, + _ask_options, + _convert_distributed_mode, + _convert_dynamo_backend, + _convert_fp8_backend, + _convert_mixed_precision, + _convert_yes_no_to_bool, +) + + +def get_cluster_input(): + distributed_type = _ask_options( + "Which type of machine are you using?", + [ + "No distributed training", + "multi-CPU", + "multi-XPU", + "multi-HPU", + "multi-GPU", + "multi-NPU", + "multi-MLU", + "multi-SDAA", + "multi-MUSA", + "TPU", + ], + _convert_distributed_mode, + ) + + machine_rank = 0 + num_machines = 1 + num_processes = 1 + gpu_ids = None + main_process_ip = None + main_process_port = None + rdzv_backend = "static" + same_network = True + debug = False + + if distributed_type in [ + DistributedType.MULTI_GPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_SDAA, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_NPU, + DistributedType.MULTI_XPU, + DistributedType.MULTI_CPU, + DistributedType.MULTI_HPU, + ]: + num_machines = _ask_field( + "How many different machines will you use (use more than 1 for multi-node training)? [1]: ", + int, + default=1, + ) + if num_machines > 1: + machine_rank = _ask_options( + "What is the rank of this machine?", + list(range(num_machines)), + int, + ) + main_process_ip = _ask_field( + "What is the IP address of the machine that will host the main process? ", + ) + main_process_port = _ask_field( + "What is the port you will use to communicate with the main process? ", + int, + ) + same_network = _ask_field( + "Are all the machines on the same local network? Answer `no` if nodes are on the cloud and/or on different network hosts [YES/no]: ", + _convert_yes_no_to_bool, + default=True, + error_message="Please enter yes or no.", + ) + if not same_network: + rdzv_backend = _ask_field( + "What rendezvous backend will you use? ('static', 'c10d', ...): ", default="static" + ) + debug = _ask_field( + "Should distributed operations be checked while running for errors? This can avoid timeout issues but will be slower. [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + + if distributed_type == DistributedType.NO: + use_cpu = _ask_field( + "Do you want to run your training on CPU only (even if a GPU / Apple Silicon / Ascend NPU device is available)? [yes/NO]:", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + elif distributed_type == DistributedType.MULTI_CPU: + use_cpu = True + else: + use_cpu = False + + ipex_config = {} + mpirun_config = {} + if use_cpu or is_xpu_available(): + ipex_config["ipex"] = _ask_field( + "Do you want to use Intel PyTorch Extension (IPEX) to speed up training on CPU/XPU? [yes/NO]:", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + + if use_cpu: + if distributed_type == DistributedType.MULTI_CPU: + use_mpirun = _ask_field( + "Do you want accelerate to launch mpirun? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if use_mpirun: + mpirun_hostfile = _ask_field( + "Please enter the path to the hostfile to use with mpirun [~/hostfile]: ", + str, + default="~/hostfile", + ) + mpirun_config["mpirun_hostfile"] = os.path.expanduser(mpirun_hostfile.strip()) + mpirun_config["mpirun_ccl"] = _ask_field("Enter the number of oneCCL worker threads [1]: ", default=1) + + dynamo_config = {} + use_dynamo = _ask_field( + "Do you wish to optimize your script with torch dynamo?[yes/NO]:", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if use_dynamo: + prefix = "dynamo_" + dynamo_config[prefix + "backend"] = _ask_options( + "Which dynamo backend would you like to use?", + [x.lower() for x in DYNAMO_BACKENDS], + _convert_dynamo_backend, + default=2, + ) + use_custom_options = _ask_field( + "Do you want to customize the defaults sent to torch.compile? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + + if use_custom_options: + dynamo_config[prefix + "mode"] = _ask_options( + "Which mode do you want to use?", + TORCH_DYNAMO_MODES, + lambda x: TORCH_DYNAMO_MODES[int(x)], + default=0, + ) + dynamo_config[prefix + "use_fullgraph"] = _ask_field( + "Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + dynamo_config[prefix + "use_dynamic"] = _ask_field( + "Do you want to enable dynamic shape tracing? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + dynamo_config[prefix + "use_regional_compilation"] = _ask_field( + "Do you want to enable regional compilation? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + + use_mps = not use_cpu and is_mps_available() + deepspeed_config = {} + if ( + distributed_type + in [ + DistributedType.MULTI_GPU, + DistributedType.MULTI_XPU, + DistributedType.MULTI_HPU, + DistributedType.MULTI_NPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_SDAA, + DistributedType.MULTI_MUSA, + DistributedType.NO, + ] + and not use_mps + ): + use_deepspeed = _ask_field( + "Do you want to use DeepSpeed? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if use_deepspeed: + distributed_type = DistributedType.DEEPSPEED + assert is_deepspeed_available(), ( + "DeepSpeed is not installed => run `pip3 install deepspeed` or build it from source" + ) + + if distributed_type == DistributedType.DEEPSPEED: + use_deepspeed_config = _ask_field( + "Do you want to specify a json file to a DeepSpeed config? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if use_deepspeed_config: + deepspeed_config["deepspeed_config_file"] = _ask_field( + "Please enter the path to the json DeepSpeed config file: ", + str, + default="none", + ) + else: + deepspeed_config["zero_stage"] = _ask_options( + "What should be your DeepSpeed's ZeRO optimization stage?", + [0, 1, 2, 3], + int, + default=2, + ) + + deepspeed_devices = ["none", "cpu", "nvme"] + if deepspeed_config["zero_stage"] >= 2: + deepspeed_config["offload_optimizer_device"] = _ask_options( + "Where to offload optimizer states?", deepspeed_devices, lambda x: deepspeed_devices[int(x)] + ) + deepspeed_config["offload_param_device"] = _ask_options( + "Where to offload parameters?", deepspeed_devices, lambda x: deepspeed_devices[int(x)] + ) + if deepspeed_config["offload_param_device"] == "nvme": + deepspeed_config["offload_param_nvme_path"] = _ask_field( + "Nvme Path to offload parameters?", + str, + default="/nvme", + ) + if deepspeed_config["offload_optimizer_device"] == "nvme": + deepspeed_config["offload_optimizer_nvme_path"] = _ask_field( + "Nvme Path to offload optimizer states?", + str, + default="/nvme", + ) + deepspeed_config["gradient_accumulation_steps"] = _ask_field( + "How many gradient accumulation steps you're passing in your script? [1]: ", + int, + default=1, + ) + use_gradient_clipping = _ask_field( + "Do you want to use gradient clipping? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if use_gradient_clipping: + deepspeed_config["gradient_clipping"] = _ask_field( + "What is the gradient clipping value? [1.0]: ", + float, + default=1.0, + ) + if deepspeed_config["zero_stage"] == 3: + deepspeed_config["zero3_save_16bit_model"] = _ask_field( + "Do you want to save 16-bit model weights when using ZeRO Stage-3? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + deepspeed_config["zero3_init_flag"] = _ask_field( + "Do you want to enable `deepspeed.zero.Init` when using ZeRO Stage-3 for constructing massive models? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if deepspeed_config["zero3_init_flag"]: + if not is_transformers_available(): + raise Exception( + "When `zero3_init_flag` is set, it requires Transformers to be installed. " + "Please run `pip3 install transformers`." + ) + use_moe = _ask_field( + "Do you want to enable Mixture-of-Experts training (MoE)? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if use_moe: + deepspeed_config["deepspeed_moe_layer_cls_names"] = _ask_field( + "Specify the comma-separated list of transformers MoE layer class names (case-sensitive), e.g : " + " `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ... : ", + str, + ) + + if num_machines > 1: + launcher_query = "Which Type of launcher do you want to use?" + deepspeed_config["deepspeed_multinode_launcher"] = _ask_options( + launcher_query, + DEEPSPEED_MULTINODE_LAUNCHERS, + lambda x: DEEPSPEED_MULTINODE_LAUNCHERS[int(x)], + ) + + if deepspeed_config["deepspeed_multinode_launcher"] != DEEPSPEED_MULTINODE_LAUNCHERS[1]: + deepspeed_config["deepspeed_hostfile"] = _ask_field( + "DeepSpeed configures multi-node compute resources with hostfile. " + "Each row is of the format `hostname slots=[num_gpus]`, e.g., `localhost slots=2`; " + "for more information please refer official [documentation]" + "(https://www.deepspeed.ai/getting-started/#resource-configuration-multi-node). " + "Please specify the location of hostfile: ", + str, + ) + + is_exclusion_filter = _ask_field( + "Do you want to specify exclusion filter string? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if is_exclusion_filter: + deepspeed_config["deepspeed_exclusion_filter"] = _ask_field( + "DeepSpeed exclusion filter string: ", + str, + ) + + is_inclusion_filter = _ask_field( + "Do you want to specify inclusion filter string? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if is_inclusion_filter: + deepspeed_config["deepspeed_inclusion_filter"] = _ask_field( + "DeepSpeed inclusion filter string: ", + str, + ) + + fsdp_config = {} + + if distributed_type in [ + DistributedType.MULTI_GPU, + DistributedType.MULTI_NPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_SDAA, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_XPU, + DistributedType.MULTI_HPU, + ]: + use_fsdp = _ask_field( + "Do you want to use FullyShardedDataParallel? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if use_fsdp: + distributed_type = DistributedType.FSDP + if distributed_type == DistributedType.FSDP: + fsdp_config["fsdp_version"] = _ask_options( + "What should be your FSDP version? [2]: ", + [1, 2], + lambda x: int(x) + 1, + default=1, + ) + fsdp_version = fsdp_config["fsdp_version"] # extract to a variable to simplify usage later + + if fsdp_version == 1: + sharding_strategy_query = "What should be your sharding strategy?" + fsdp_config["fsdp_reshard_after_forward"] = _ask_options( + sharding_strategy_query, + FSDP_SHARDING_STRATEGY, + lambda x: FSDP_SHARDING_STRATEGY[int(x)], + ) + else: + fsdp_config["fsdp_reshard_after_forward"] = _ask_field( + "Do you want to enable resharding after forward? [YES/no]: ", + _convert_yes_no_to_bool, + default=True, + error_message="Please enter yes or no.", + ) + + fsdp_config["fsdp_offload_params"] = _ask_field( + "Do you want to offload parameters and gradients to CPU? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + + fsdp_wrap_query = "What should be your auto wrap policy?" + fsdp_config["fsdp_auto_wrap_policy"] = _ask_options( + fsdp_wrap_query, + FSDP_AUTO_WRAP_POLICY, + lambda x: FSDP_AUTO_WRAP_POLICY[int(x)], + ) + if fsdp_config["fsdp_auto_wrap_policy"] == FSDP_AUTO_WRAP_POLICY[0]: + use_no_split_modules = _ask_field( + "Do you want to use the model's `_no_split_modules` to wrap. Only applicable for 🤗 Transformers [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if not use_no_split_modules: + fsdp_config["fsdp_transformer_layer_cls_to_wrap"] = _ask_field( + "Specify the comma-separated list of transformer layer class names (case-sensitive) to wrap ,e.g, :" + "`BertLayer`, `GPTJBlock`, `T5Block`, `BertLayer,BertEmbeddings,BertSelfOutput` ...? : ", + str, + ) + elif fsdp_config["fsdp_auto_wrap_policy"] == FSDP_AUTO_WRAP_POLICY[1]: + fsdp_config["fsdp_min_num_params"] = _ask_field( + "What should be your FSDP's minimum number of parameters for Default Auto Wrapping Policy? [1e8]: ", + int, + default=100000000, + ) + # Removed in FSDP2, ask for user input for FSDP1 + if fsdp_version == 1: + fsdp_backward_prefetch_query = "What should be your FSDP's backward prefetch policy?" + fsdp_config["fsdp_backward_prefetch"] = _ask_options( + fsdp_backward_prefetch_query, + FSDP_BACKWARD_PREFETCH, + lambda x: FSDP_BACKWARD_PREFETCH[int(x)], + ) + + fsdp_state_dict_type_query = "What should be your FSDP's state dict type?" + fsdp_config["fsdp_state_dict_type"] = _ask_options( + fsdp_state_dict_type_query, + FSDP_STATE_DICT_TYPE if fsdp_version == 1 else FSDP2_STATE_DICT_TYPE, + lambda x: FSDP_STATE_DICT_TYPE[int(x)] if fsdp_version == 1 else FSDP2_STATE_DICT_TYPE[int(x)], + default=0, + ) + # Not implemented in FSDP2, ask for user input for FSDP1 + if fsdp_version == 1: + fsdp_config["fsdp_forward_prefetch"] = _ask_field( + "Do you want to enable FSDP's forward prefetch policy? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + # Obsolete in FSDP2, ask for user input for FSDP1 + if fsdp_version == 1: + fsdp_config["fsdp_use_orig_params"] = _ask_field( + "Do you want to enable FSDP's `use_orig_params` feature? [YES/no]: ", + _convert_yes_no_to_bool, + default=True, + error_message="Please enter yes or no.", + ) + fsdp_config["fsdp_cpu_ram_efficient_loading"] = _ask_field( + "Do you want to enable CPU RAM efficient model loading? Only applicable for 🤗 Transformers models. [YES/no]: ", + _convert_yes_no_to_bool, + default=True, + error_message="Please enter yes or no.", + ) + # Obsolete in FSDP2, ask for user input for FSDP1 + if fsdp_version == 1: + if fsdp_config["fsdp_cpu_ram_efficient_loading"]: + fsdp_config["fsdp_sync_module_states"] = True + else: + fsdp_config["fsdp_sync_module_states"] = _ask_field( + "Do you want each individually wrapped FSDP unit to broadcast module parameters from rank 0 at the start? [YES/no]: ", + _convert_yes_no_to_bool, + default=True, + error_message="Please enter yes or no.", + ) + fsdp_config["fsdp_activation_checkpointing"] = _ask_field( + "Do you want to enable FSDP activation checkpointing? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + + parallelism_config = {} + + if fsdp_config.get("fsdp_version", 1) == 2: + use_parallelism_config = _ask_field( + "Do you want to use the parallelism config? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + + if use_parallelism_config: + prefix = "parallelism_config_" + parallelism_config[prefix + "dp_replicate_size"] = _ask_field( + "What is the data parallelism replicate size? [1]: ", + int, + default=1, + error_message="Please enter an integer.", + ) + + parallelism_config[prefix + "dp_shard_size"] = _ask_field( + "What is the FSDP shard size? [1]: ", + int, + default=1, + error_message="Please enter an integer.", + ) + + parallelism_config[prefix + "tp_size"] = _ask_field( + "What is the tensor parallelism size? [1]: ", + int, + default=1, + error_message="Please enter an integer.", + ) + + parallelism_config[prefix + "cp_size"] = _ask_field( + "What is the context parallelism size? [1]: ", + int, + default=1, + error_message="Please enter an integer.", + ) + if parallelism_config[prefix + "cp_size"] > 1: + parallelism_config[prefix + "cp_comm_strategy"] = _ask_options( + "What is the compute parallelism communication strategy?", + ["allgather", "alltoall"], + lambda x: ["allgather", "alltoall"][int(x)], + default=0, + ) + + megatron_lm_config = {} + if distributed_type in [DistributedType.MULTI_GPU]: + use_megatron_lm = _ask_field( + "Do you want to use Megatron-LM ? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if use_megatron_lm: + distributed_type = DistributedType.MEGATRON_LM + if distributed_type == DistributedType.MEGATRON_LM: + prefix = "megatron_lm_" + megatron_lm_config[prefix + "tp_degree"] = _ask_field( + "What is the Tensor Parallelism degree/size? [1]:", + int, + default=1, + error_message="Please enter an integer.", + ) + if megatron_lm_config[prefix + "tp_degree"] > 1: + megatron_lm_config[prefix + "sequence_parallelism"] = _ask_field( + "Do you want to enable Sequence Parallelism? [YES/no]: ", + _convert_yes_no_to_bool, + default=True, + error_message="Please enter yes or no.", + ) + + megatron_lm_config[prefix + "pp_degree"] = _ask_field( + "What is the Pipeline Parallelism degree/size? [1]:", + int, + default=1, + error_message="Please enter an integer.", + ) + if megatron_lm_config[prefix + "pp_degree"] > 1: + megatron_lm_config[prefix + "num_micro_batches"] = _ask_field( + "What is the number of micro-batches? [1]:", + int, + default=1, + error_message="Please enter an integer.", + ) + + megatron_lm_config[prefix + "recompute_activations"] = _ask_field( + "Do you want to enable selective activation recomputation? [YES/no]: ", + _convert_yes_no_to_bool, + default=True, + error_message="Please enter yes or no.", + ) + + megatron_lm_config[prefix + "use_distributed_optimizer"] = _ask_field( + "Do you want to use distributed optimizer " + "which shards optimizer state and gradients across data parallel ranks? [YES/no]: ", + _convert_yes_no_to_bool, + default=True, + error_message="Please enter yes or no.", + ) + + megatron_lm_config[prefix + "gradient_clipping"] = _ask_field( + "What is the gradient clipping value based on global L2 Norm (0 to disable)? [1.0]: ", + float, + default=1.0, + ) + # TPU specific defaults + tpu_commands = None + tpu_command_file = None + tpu_downcast_bf16 = "no" + tpu_env = [] + tpu_name = None + tpu_vm = None + tpu_zone = None + tpu_use_sudo = False + tpu_use_cluster = False + + if distributed_type in [ + DistributedType.MULTI_CPU, + DistributedType.MULTI_XPU, + DistributedType.MULTI_HPU, + DistributedType.MULTI_GPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_SDAA, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_NPU, + DistributedType.XLA, + ]: + machine_type = str(distributed_type).split(".")[1].replace("MULTI_", "") + if machine_type == "TPU": + machine_type += " cores" + elif machine_type == "CPU": + machine_type = "processes" + else: + machine_type += "(s)" + num_processes = _ask_field( + f"How many {machine_type} should be used for distributed training? [1]:", + int, + default=1, + error_message="Please enter an integer.", + ) + elif distributed_type in [DistributedType.FSDP, DistributedType.DEEPSPEED, DistributedType.MEGATRON_LM]: + num_processes = _ask_field( + "How many GPU(s) should be used for distributed training? [1]:", + int, + default=1, + error_message="Please enter an integer.", + ) + else: + num_processes = 1 + + if (distributed_type == DistributedType.MULTI_GPU) and (num_machines == 1) and (num_processes == 1): + raise ValueError( + f"Specified distributed type {distributed_type} but only using 1 GPU on a single machine. Please select `No distributed training` for the type of machine you are using." + ) + + if ( + distributed_type + in [ + DistributedType.MULTI_GPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_SDAA, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_NPU, + DistributedType.MULTI_XPU, + DistributedType.MULTI_HPU, + DistributedType.NO, + ] + and not use_cpu + and not use_mps + ): + if is_npu_available(): + machine_type = "NPU(s)" + elif is_mlu_available(): + machine_type = "MLU(s)" + elif is_sdaa_available(): + machine_type = "SDAA(s)" + elif is_musa_available(): + machine_type = "MUSA(s)" + elif is_xpu_available(): + machine_type = "XPU(s)" + elif is_hpu_available(): + machine_type = "HPU(s)" + else: + machine_type = "GPU(s)" + gpu_ids = _ask_field( + f"What {machine_type} (by id) should be used for training on this machine as a comma-separated list? [all]:", + default="all", + ) + + # CPU affinity is only supported on NVIDIA hardware for now + enable_cpu_affinity = False + if distributed_type in (DistributedType.NO, DistributedType.MULTI_GPU) and not use_cpu and not use_mps: + enable_cpu_affinity = _ask_field( + "Would you like to enable numa efficiency? (Currently only supported on NVIDIA hardware). [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + + fp8_config = None + if distributed_type == DistributedType.XLA: + mixed_precision = "no" + main_training_function = _ask_field( + "What is the name of the function in your script that should be launched in all parallel scripts? [main]: ", + default="main", + ) + tpu_use_cluster = _ask_field( + "Are you using a TPU cluster? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if tpu_use_cluster: + tpu_name = _ask_field( + "What is the name of your TPU cluster? ", + default=None, + error_message="Please enter the name of your TPU cluster.", + ) + tpu_zone = _ask_field( + "What is the zone of your TPU cluster? ", + default=None, + error_message="Please enter the zone of your TPU cluster.", + ) + tpu_use_sudo = _ask_field( + "To run a python script in a TPU pod, should `sudo` be used? [yes/NO]: ", + default=False, + error_message="Please enter yes or no.", + ) + run_commands = _ask_field( + "Do you have code you wish to run on startup in each pod? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if run_commands: + use_command_file = _ask_field( + "Is this code located in a bash script? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if use_command_file: + tpu_command_file = _ask_field( + "What is the path to your bash script? ", + default=None, + error_message="Please enter the path to your bash script.", + ) + tpu_command_file = os.path.abspath(tpu_command_file) + else: + print("Please enter each command separately you wish to run on startup in each pod.") + tpu_commands = [] + another_command = True + while another_command: + tpu_commands.append( + _ask_field( + "Please enter a single command to be ran ", + default=None, + error_message="Please enter the commands you wish to run on startup in each pod as a single string.", + ) + ) + another_command = _ask_field( + "Do you wish to add another command? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + tpu_vm = _ask_field( + "If not using an instance group, what are the names of the Compute VM instances to be used, separated by a comma: ", + default="", + ).split(",") + tpu_env = _ask_field( + "What environment variables do you wish to set in each pod, separated by a comma: ", + default="", + ).split(",") + + else: + main_training_function = "main" + if distributed_type == DistributedType.DEEPSPEED and use_deepspeed_config: + mixed_precision = None + else: + mixed_precision = _ask_options( + "Do you wish to use mixed precision?", + ["no", "fp16", "bf16", "fp8"], + _convert_mixed_precision, + ) + if mixed_precision == "fp8": + if not is_fp8_available(): + raise ValueError("FP8 (either Transformer Engine or MSAMP) is not installed on this machine.") + fp8_config = {} + fp8_config["backend"] = _ask_options( + "Which FP8 backend do you want to use?", + ["te", "msamp"], + _convert_fp8_backend, + ) + if fp8_config["backend"] == "TE": + if not is_transformer_engine_available(): + raise ValueError("TransformersEngine was selected, but it is not installed on this machine.") + fp8_config["use_autocast_during_eval"] = _ask_field( + "Do you want to use FP8 autocast during eval mode? Generally better metrics are found when this is disabled [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + ) + fp8_config["margin"] = _ask_field( + "What margin should be used for gradient scaling? [0]: ", + int, + default=0, + ) + fp8_config["interval"] = _ask_field( + "What interval should be used for for how often the scaling factor is recomputed? [1]: ", + int, + default=1, + ) + fp8_config["fp8_format"] = _ask_options( + "Which weight format should be used?", + ["HYBRID", "E4M3", "E5M2"], + lambda i: ["HYBRID", "E4M3", "E5M2"][i], + default=0, + ) + fp8_config["amax_history_length"] = _ask_field( + "What length of history should be used for the amax scaling factor computation? [1024]: ", + int, + default=1024, + ) + fp8_config["amax_compute_algorithm"] = _ask_options( + "Which algorithm should be used for the amax scaling factor computation?", + ["max", "most_recent"], + lambda x: "max" if x == 0 else "most_recent", + default=0, + ) + fp8_config["override_linear_precision"] = _ask_field( + "Do you want to to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + ) + if fp8_config["override_linear_precision"]: + fprop = _ask_field( + "Should `fprop` be executed in higher precision? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + ) + dgrad = _ask_field( + "Should `dgrad` be executed in higher precision? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + ) + wgrad = _ask_field( + "Should `wgrad` be executed in higher precision? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + ) + fp8_config["override_linear_precision"] = (fprop, dgrad, wgrad) + else: + fp8_config["override_linear_precision"] = (False, False, False) + + elif fp8_config["backend"] == "MSAMP": + if not is_msamp_available(): + raise ValueError("MSAMP was selected, but it is not installed on this machine.") + fp8_config["optimization_level"] = _ask_options( + "Which optimization level should be used?", + ["O1", "O2"], + lambda x: "O1" if x == 0 else "O2", + default=1, + ) + + if use_dynamo and mixed_precision == "no" and not use_cpu: + print( + "Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts." + ) + + if distributed_type == DistributedType.XLA and mixed_precision == "bf16": + tpu_downcast_bf16 = _ask_field( + "Should `torch.float` be cast as `bfloat16` and `torch.double` remain `float32` on TPUs?", default="no" + ) + + return ClusterConfig( + compute_environment=ComputeEnvironment.LOCAL_MACHINE, + distributed_type=distributed_type, + num_processes=num_processes, + gpu_ids=gpu_ids, + mixed_precision=mixed_precision, + downcast_bf16=tpu_downcast_bf16, + machine_rank=machine_rank, + num_machines=num_machines, + main_process_ip=main_process_ip, + main_process_port=main_process_port, + main_training_function=main_training_function, + fp8_config=fp8_config, + deepspeed_config=deepspeed_config, + fsdp_config=fsdp_config, + parallelism_config=parallelism_config, + megatron_lm_config=megatron_lm_config, + ipex_config=ipex_config, + mpirun_config=mpirun_config, + use_cpu=use_cpu, + rdzv_backend=rdzv_backend, + same_network=same_network, + commands=tpu_commands, + command_file=tpu_command_file, + tpu_env=tpu_env, + tpu_name=tpu_name, + tpu_vm=tpu_vm, + tpu_zone=tpu_zone, + tpu_use_sudo=tpu_use_sudo, + tpu_use_cluster=tpu_use_cluster, + dynamo_config=dynamo_config, + debug=debug, + enable_cpu_affinity=enable_cpu_affinity, + ) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/config.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/config.py new file mode 100644 index 0000000000000000000000000000000000000000..72414f2abe62d76bd5133f4b0ed99bf34133f6f6 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/config.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python + +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import os + +from accelerate.utils import ComputeEnvironment + +from .cluster import get_cluster_input +from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 +from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 +from .sagemaker import get_sagemaker_input + + +description = "Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine" + + +def get_user_input(): + compute_environment = _ask_options( + "In which compute environment are you running?", + ["This machine", "AWS (Amazon SageMaker)"], + _convert_compute_environment, + ) + if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: + config = get_sagemaker_input() + else: + config = get_cluster_input() + return config + + +def config_command_parser(subparsers=None): + if subparsers is not None: + parser = subparsers.add_parser("config", description=description) + else: + parser = argparse.ArgumentParser("Accelerate config command", description=description) + + parser.add_argument( + "--config_file", + default=None, + help=( + "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " + "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " + "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " + "with 'huggingface'." + ), + ) + + if subparsers is not None: + parser.set_defaults(func=config_command) + return parser + + +def config_command(args): + config = get_user_input() + if args.config_file is not None: + config_file = args.config_file + else: + if not os.path.isdir(cache_dir): + os.makedirs(cache_dir) + config_file = default_yaml_config_file + + if config_file.endswith(".json"): + config.to_json_file(config_file) + else: + config.to_yaml_file(config_file) + print(f"accelerate configuration saved at {config_file}") + + +def main(): + parser = config_command_parser() + args = parser.parse_args() + config_command(args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/config_args.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/config_args.py new file mode 100644 index 0000000000000000000000000000000000000000..75664a95ef6edd08bf7f1158c663cac9d44dd550 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/config_args.py @@ -0,0 +1,256 @@ +#!/usr/bin/env python + +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import os +from dataclasses import dataclass +from enum import Enum +from typing import Optional, Union + +import yaml + +from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType +from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION + + +hf_cache_home = os.path.expanduser( + os.environ.get("HF_HOME", os.path.join(os.environ.get("XDG_CACHE_HOME", "~/.cache"), "huggingface")) +) +cache_dir = os.path.join(hf_cache_home, "accelerate") +default_json_config_file = os.path.join(cache_dir, "default_config.yaml") +default_yaml_config_file = os.path.join(cache_dir, "default_config.yaml") + +# For backward compatibility: the default config is the json one if it's the only existing file. +if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file): + default_config_file = default_yaml_config_file +else: + default_config_file = default_json_config_file + + +def load_config_from_file(config_file): + if config_file is not None: + if not os.path.isfile(config_file): + raise FileNotFoundError( + f"The passed configuration file `{config_file}` does not exist. " + "Please pass an existing file to `accelerate launch`, or use the default one " + "created through `accelerate config` and run `accelerate launch` " + "without the `--config_file` argument." + ) + else: + config_file = default_config_file + with open(config_file, encoding="utf-8") as f: + if config_file.endswith(".json"): + if ( + json.load(f).get("compute_environment", ComputeEnvironment.LOCAL_MACHINE) + == ComputeEnvironment.LOCAL_MACHINE + ): + config_class = ClusterConfig + else: + config_class = SageMakerConfig + return config_class.from_json_file(json_file=config_file) + else: + if ( + yaml.safe_load(f).get("compute_environment", ComputeEnvironment.LOCAL_MACHINE) + == ComputeEnvironment.LOCAL_MACHINE + ): + config_class = ClusterConfig + else: + config_class = SageMakerConfig + return config_class.from_yaml_file(yaml_file=config_file) + + +@dataclass +class BaseConfig: + compute_environment: ComputeEnvironment + distributed_type: Union[DistributedType, SageMakerDistributedType] + mixed_precision: str + use_cpu: bool + debug: bool + + def to_dict(self): + result = self.__dict__ + # For serialization, it's best to convert Enums to strings (or their underlying value type). + + def _convert_enums(value): + if isinstance(value, Enum): + return value.value + if isinstance(value, dict): + if not bool(value): + return None + for key1, value1 in value.items(): + value[key1] = _convert_enums(value1) + return value + + for key, value in result.items(): + result[key] = _convert_enums(value) + result = {k: v for k, v in result.items() if v is not None} + return result + + @staticmethod + def process_config(config_dict): + """ + Processes `config_dict` and sets default values for any missing keys + """ + if "compute_environment" not in config_dict: + config_dict["compute_environment"] = ComputeEnvironment.LOCAL_MACHINE + if "distributed_type" not in config_dict: + raise ValueError("A `distributed_type` must be specified in the config file.") + if "num_processes" not in config_dict and config_dict["distributed_type"] == DistributedType.NO: + config_dict["num_processes"] = 1 + if "mixed_precision" not in config_dict: + config_dict["mixed_precision"] = "fp16" if ("fp16" in config_dict and config_dict["fp16"]) else None + if "fp16" in config_dict: # Convert the config to the new format. + del config_dict["fp16"] + if "dynamo_backend" in config_dict: # Convert the config to the new format. + dynamo_backend = config_dict.pop("dynamo_backend") + config_dict["dynamo_config"] = {} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend} + if "use_cpu" not in config_dict: + config_dict["use_cpu"] = False + if "debug" not in config_dict: + config_dict["debug"] = False + if "enable_cpu_affinity" not in config_dict: + config_dict["enable_cpu_affinity"] = False + return config_dict + + @classmethod + def from_json_file(cls, json_file=None): + json_file = default_json_config_file if json_file is None else json_file + with open(json_file, encoding="utf-8") as f: + config_dict = json.load(f) + config_dict = cls.process_config(config_dict) + extra_keys = sorted(set(config_dict.keys()) - set(cls.__dataclass_fields__.keys())) + if len(extra_keys) > 0: + raise ValueError( + f"The config file at {json_file} had unknown keys ({extra_keys}), please try upgrading your `accelerate`" + " version or fix (and potentially remove) these keys from your config file." + ) + + return cls(**config_dict) + + def to_json_file(self, json_file): + with open(json_file, "w", encoding="utf-8") as f: + content = json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n" + f.write(content) + + @classmethod + def from_yaml_file(cls, yaml_file=None): + yaml_file = default_yaml_config_file if yaml_file is None else yaml_file + with open(yaml_file, encoding="utf-8") as f: + config_dict = yaml.safe_load(f) + config_dict = cls.process_config(config_dict) + extra_keys = sorted(set(config_dict.keys()) - set(cls.__dataclass_fields__.keys())) + if len(extra_keys) > 0: + raise ValueError( + f"The config file at {yaml_file} had unknown keys ({extra_keys}), please try upgrading your `accelerate`" + " version or fix (and potentially remove) these keys from your config file." + ) + return cls(**config_dict) + + def to_yaml_file(self, yaml_file): + with open(yaml_file, "w", encoding="utf-8") as f: + yaml.safe_dump(self.to_dict(), f) + + def __post_init__(self): + if isinstance(self.compute_environment, str): + self.compute_environment = ComputeEnvironment(self.compute_environment) + if isinstance(self.distributed_type, str): + if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: + self.distributed_type = SageMakerDistributedType(self.distributed_type) + else: + self.distributed_type = DistributedType(self.distributed_type) + if getattr(self, "dynamo_config", None) is None: + self.dynamo_config = {} + + +@dataclass +class ClusterConfig(BaseConfig): + num_processes: int = -1 # For instance if we use SLURM and the user manually passes it in + machine_rank: int = 0 + num_machines: int = 1 + gpu_ids: Optional[str] = None + main_process_ip: Optional[str] = None + main_process_port: Optional[int] = None + rdzv_backend: Optional[str] = "static" + same_network: Optional[bool] = False + main_training_function: str = "main" + enable_cpu_affinity: bool = False + + # args for FP8 training + fp8_config: dict = None + # args for deepspeed_plugin + deepspeed_config: dict = None + # args for fsdp + fsdp_config: dict = None + # args for parallelism config + parallelism_config: dict = None + # args for megatron_lm + megatron_lm_config: dict = None + # args for ipex + ipex_config: dict = None + # args for mpirun + mpirun_config: dict = None + # args for TPU + downcast_bf16: bool = False + + # args for TPU pods + tpu_name: str = None + tpu_zone: str = None + tpu_use_cluster: bool = False + tpu_use_sudo: bool = False + command_file: str = None + commands: list[str] = None + tpu_vm: list[str] = None + tpu_env: list[str] = None + + # args for dynamo + dynamo_config: dict = None + + def __post_init__(self): + if self.deepspeed_config is None: + self.deepspeed_config = {} + if self.fsdp_config is None: + self.fsdp_config = {} + if self.megatron_lm_config is None: + self.megatron_lm_config = {} + if self.ipex_config is None: + self.ipex_config = {} + if self.mpirun_config is None: + self.mpirun_config = {} + if self.fp8_config is None: + self.fp8_config = {} + if self.parallelism_config is None: + self.parallelism_config = {} + return super().__post_init__() + + +@dataclass +class SageMakerConfig(BaseConfig): + ec2_instance_type: str + iam_role_name: str + image_uri: Optional[str] = None + profile: Optional[str] = None + region: str = "us-east-1" + num_machines: int = 1 + gpu_ids: str = "all" + base_job_name: str = f"accelerate-sagemaker-{num_machines}" + pytorch_version: str = SAGEMAKER_PYTORCH_VERSION + transformers_version: str = SAGEMAKER_TRANSFORMERS_VERSION + py_version: str = SAGEMAKER_PYTHON_VERSION + sagemaker_inputs_file: str = None + sagemaker_metrics_file: str = None + additional_args: dict = None + dynamo_config: dict = None + enable_cpu_affinity: bool = False diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/config_utils.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/config_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..24ee971383c8fdda1491e2b5795446790755ac70 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/config_utils.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python + +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse + +from ...utils.dataclasses import ( + ComputeEnvironment, + DistributedType, + DynamoBackend, + FP8BackendType, + PrecisionType, + SageMakerDistributedType, +) +from ..menu import BulletMenu + + +DYNAMO_BACKENDS = [ + "EAGER", + "AOT_EAGER", + "INDUCTOR", + "AOT_TS_NVFUSER", + "NVPRIMS_NVFUSER", + "CUDAGRAPHS", + "OFI", + "FX2TRT", + "ONNXRT", + "TENSORRT", + "AOT_TORCHXLA_TRACE_ONCE", + "TORHCHXLA_TRACE_ONCE", + "IPEX", + "TVM", +] + + +def _ask_field(input_text, convert_value=None, default=None, error_message=None): + ask_again = True + while ask_again: + result = input(input_text) + try: + if default is not None and len(result) == 0: + return default + return convert_value(result) if convert_value is not None else result + except Exception: + if error_message is not None: + print(error_message) + + +def _ask_options(input_text, options=[], convert_value=None, default=0): + menu = BulletMenu(input_text, options) + result = menu.run(default_choice=default) + return convert_value(result) if convert_value is not None else result + + +def _convert_compute_environment(value): + value = int(value) + return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value]) + + +def _convert_distributed_mode(value): + value = int(value) + return DistributedType( + [ + "NO", + "MULTI_CPU", + "MULTI_XPU", + "MULTI_HPU", + "MULTI_GPU", + "MULTI_NPU", + "MULTI_MLU", + "MULTI_SDAA", + "MULTI_MUSA", + "XLA", + ][value] + ) + + +def _convert_dynamo_backend(value): + value = int(value) + return DynamoBackend(DYNAMO_BACKENDS[value]).value + + +def _convert_mixed_precision(value): + value = int(value) + return PrecisionType(["no", "fp16", "bf16", "fp8"][value]) + + +def _convert_sagemaker_distributed_mode(value): + value = int(value) + return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value]) + + +def _convert_fp8_backend(value): + value = int(value) + return FP8BackendType(["TE", "MSAMP"][value]) + + +def _convert_yes_no_to_bool(value): + return {"yes": True, "no": False}[value.lower()] + + +class SubcommandHelpFormatter(argparse.RawDescriptionHelpFormatter): + """ + A custom formatter that will remove the usage line from the help message for subcommands. + """ + + def _format_usage(self, usage, actions, groups, prefix): + usage = super()._format_usage(usage, actions, groups, prefix) + usage = usage.replace(" [] ", "") + return usage diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/default.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/default.py new file mode 100644 index 0000000000000000000000000000000000000000..f5f267f8c47cccc80ce9ef53f970c2266472c117 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/default.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python + +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from pathlib import Path + +import torch + +from ...utils import ( + is_hpu_available, + is_mlu_available, + is_musa_available, + is_npu_available, + is_sdaa_available, + is_xpu_available, +) +from .config_args import ClusterConfig, default_json_config_file +from .config_utils import SubcommandHelpFormatter + + +description = "Create a default config file for Accelerate with only a few flags set." + + +def write_basic_config(mixed_precision="no", save_location: str = default_json_config_file): + """ + Creates and saves a basic cluster config to be used on a local machine with potentially multiple GPUs. Will also + set CPU if it is a CPU-only machine. + + Args: + mixed_precision (`str`, *optional*, defaults to "no"): + Mixed Precision to use. Should be one of "no", "fp16", or "bf16" + save_location (`str`, *optional*, defaults to `default_json_config_file`): + Optional custom save location. Should be passed to `--config_file` when using `accelerate launch`. Default + location is inside the huggingface cache folder (`~/.cache/huggingface`) but can be overridden by setting + the `HF_HOME` environmental variable, followed by `accelerate/default_config.yaml`. + """ + path = Path(save_location) + path.parent.mkdir(parents=True, exist_ok=True) + if path.exists(): + print( + f"Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`." + ) + return False + mixed_precision = mixed_precision.lower() + if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: + raise ValueError( + f"`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}" + ) + config = { + "compute_environment": "LOCAL_MACHINE", + "mixed_precision": mixed_precision, + } + if is_mlu_available(): + num_mlus = torch.mlu.device_count() + config["num_processes"] = num_mlus + config["use_cpu"] = False + if num_mlus > 1: + config["distributed_type"] = "MULTI_MLU" + else: + config["distributed_type"] = "NO" + if is_sdaa_available(): + num_sdaas = torch.sdaa.device_count() + config["num_processes"] = num_sdaas + config["use_cpu"] = False + if num_sdaas > 1: + config["distributed_type"] = "MULTI_SDAA" + else: + config["distributed_type"] = "NO" + elif is_musa_available(): + num_musas = torch.musa.device_count() + config["num_processes"] = num_musas + config["use_cpu"] = False + if num_musas > 1: + config["distributed_type"] = "MULTI_MUSA" + else: + config["distributed_type"] = "NO" + elif is_hpu_available(): + num_hpus = torch.hpu.device_count() + config["num_processes"] = num_hpus + config["use_cpu"] = False + if num_hpus > 1: + config["distributed_type"] = "MULTI_HPU" + else: + config["distributed_type"] = "NO" + elif torch.cuda.is_available(): + num_gpus = torch.cuda.device_count() + config["num_processes"] = num_gpus + config["use_cpu"] = False + if num_gpus > 1: + config["distributed_type"] = "MULTI_GPU" + else: + config["distributed_type"] = "NO" + elif is_xpu_available(): + num_xpus = torch.xpu.device_count() + config["num_processes"] = num_xpus + config["use_cpu"] = False + if num_xpus > 1: + config["distributed_type"] = "MULTI_XPU" + else: + config["distributed_type"] = "NO" + elif is_npu_available(): + num_npus = torch.npu.device_count() + config["num_processes"] = num_npus + config["use_cpu"] = False + if num_npus > 1: + config["distributed_type"] = "MULTI_NPU" + else: + config["distributed_type"] = "NO" + else: + num_xpus = 0 + config["use_cpu"] = True + config["num_processes"] = 1 + config["distributed_type"] = "NO" + config["debug"] = False + config["enable_cpu_affinity"] = False + config = ClusterConfig(**config) + config.to_json_file(path) + return path + + +def default_command_parser(parser, parents): + parser = parser.add_parser("default", parents=parents, help=description, formatter_class=SubcommandHelpFormatter) + parser.add_argument( + "--config_file", + default=default_json_config_file, + help=( + "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " + "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " + "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " + "with 'huggingface'." + ), + dest="save_location", + ) + + parser.add_argument( + "--mixed_precision", + choices=["no", "fp16", "bf16"], + type=str, + help="Whether or not to use mixed precision training. " + "Choose between FP16 and BF16 (bfloat16) training. " + "BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.", + default="no", + ) + parser.set_defaults(func=default_config_command) + return parser + + +def default_config_command(args): + config_file = write_basic_config(args.mixed_precision, args.save_location) + if config_file: + print(f"accelerate configuration saved at {config_file}") diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/sagemaker.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/sagemaker.py new file mode 100644 index 0000000000000000000000000000000000000000..5092ef31fc4715f901be6c1e7bfe80c0b140d767 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/sagemaker.py @@ -0,0 +1,274 @@ +#!/usr/bin/env python + +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import json +import os + +from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES +from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType +from ...utils.imports import is_boto3_available +from .config_args import SageMakerConfig +from .config_utils import ( + DYNAMO_BACKENDS, + _ask_field, + _ask_options, + _convert_dynamo_backend, + _convert_mixed_precision, + _convert_sagemaker_distributed_mode, + _convert_yes_no_to_bool, +) + + +if is_boto3_available(): + import boto3 # noqa: F401 + + +def _create_iam_role_for_sagemaker(role_name): + iam_client = boto3.client("iam") + + sagemaker_trust_policy = { + "Version": "2012-10-17", + "Statement": [ + {"Effect": "Allow", "Principal": {"Service": "sagemaker.amazonaws.com"}, "Action": "sts:AssumeRole"} + ], + } + try: + # create the role, associated with the chosen trust policy + iam_client.create_role( + RoleName=role_name, AssumeRolePolicyDocument=json.dumps(sagemaker_trust_policy, indent=2) + ) + policy_document = { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "sagemaker:*", + "ecr:GetDownloadUrlForLayer", + "ecr:BatchGetImage", + "ecr:BatchCheckLayerAvailability", + "ecr:GetAuthorizationToken", + "cloudwatch:PutMetricData", + "cloudwatch:GetMetricData", + "cloudwatch:GetMetricStatistics", + "cloudwatch:ListMetrics", + "logs:CreateLogGroup", + "logs:CreateLogStream", + "logs:DescribeLogStreams", + "logs:PutLogEvents", + "logs:GetLogEvents", + "s3:CreateBucket", + "s3:ListBucket", + "s3:GetBucketLocation", + "s3:GetObject", + "s3:PutObject", + ], + "Resource": "*", + } + ], + } + # attach policy to role + iam_client.put_role_policy( + RoleName=role_name, + PolicyName=f"{role_name}_policy_permission", + PolicyDocument=json.dumps(policy_document, indent=2), + ) + except iam_client.exceptions.EntityAlreadyExistsException: + print(f"role {role_name} already exists. Using existing one") + + +def _get_iam_role_arn(role_name): + iam_client = boto3.client("iam") + return iam_client.get_role(RoleName=role_name)["Role"]["Arn"] + + +def get_sagemaker_input(): + credentials_configuration = _ask_options( + "How do you want to authorize?", + ["AWS Profile", "Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) "], + int, + ) + aws_profile = None + if credentials_configuration == 0: + aws_profile = _ask_field("Enter your AWS Profile name: [default] ", default="default") + os.environ["AWS_PROFILE"] = aws_profile + else: + print( + "Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with," + "`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`" + ) + aws_access_key_id = _ask_field("AWS Access Key ID: ") + os.environ["AWS_ACCESS_KEY_ID"] = aws_access_key_id + + aws_secret_access_key = _ask_field("AWS Secret Access Key: ") + os.environ["AWS_SECRET_ACCESS_KEY"] = aws_secret_access_key + + aws_region = _ask_field("Enter your AWS Region: [us-east-1]", default="us-east-1") + os.environ["AWS_DEFAULT_REGION"] = aws_region + + role_management = _ask_options( + "Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?", + ["Provide IAM Role name", "Create new IAM role using credentials"], + int, + ) + if role_management == 0: + iam_role_name = _ask_field("Enter your IAM role name: ") + else: + iam_role_name = "accelerate_sagemaker_execution_role" + print(f'Accelerate will create an iam role "{iam_role_name}" using the provided credentials') + _create_iam_role_for_sagemaker(iam_role_name) + + is_custom_docker_image = _ask_field( + "Do you want to use custom Docker image? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + docker_image = None + if is_custom_docker_image: + docker_image = _ask_field("Enter your Docker image: ", lambda x: str(x).lower()) + + is_sagemaker_inputs_enabled = _ask_field( + "Do you want to provide SageMaker input channels with data locations? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + sagemaker_inputs_file = None + if is_sagemaker_inputs_enabled: + sagemaker_inputs_file = _ask_field( + "Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): ", + lambda x: str(x).lower(), + ) + + is_sagemaker_metrics_enabled = _ask_field( + "Do you want to enable SageMaker metrics? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + sagemaker_metrics_file = None + if is_sagemaker_metrics_enabled: + sagemaker_metrics_file = _ask_field( + "Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): ", + lambda x: str(x).lower(), + ) + + distributed_type = _ask_options( + "What is the distributed mode?", + ["No distributed training", "Data parallelism"], + _convert_sagemaker_distributed_mode, + ) + dynamo_config = {} + use_dynamo = _ask_field( + "Do you wish to optimize your script with torch dynamo?[yes/NO]:", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if use_dynamo: + prefix = "dynamo_" + dynamo_config[prefix + "backend"] = _ask_options( + "Which dynamo backend would you like to use?", + [x.lower() for x in DYNAMO_BACKENDS], + _convert_dynamo_backend, + default=2, + ) + use_custom_options = _ask_field( + "Do you want to customize the defaults sent to torch.compile? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + + if use_custom_options: + dynamo_config[prefix + "mode"] = _ask_options( + "Which mode do you want to use?", + TORCH_DYNAMO_MODES, + lambda x: TORCH_DYNAMO_MODES[int(x)], + default="default", + ) + dynamo_config[prefix + "use_fullgraph"] = _ask_field( + "Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + dynamo_config[prefix + "use_dynamic"] = _ask_field( + "Do you want to enable dynamic shape tracing? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + dynamo_config[prefix + "use_regional_compilation"] = _ask_field( + "Do you want to enable regional compilation? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + + ec2_instance_query = "Which EC2 instance type you want to use for your training?" + if distributed_type != SageMakerDistributedType.NO: + ec2_instance_type = _ask_options( + ec2_instance_query, SAGEMAKER_PARALLEL_EC2_INSTANCES, lambda x: SAGEMAKER_PARALLEL_EC2_INSTANCES[int(x)] + ) + else: + ec2_instance_query += "? [ml.p3.2xlarge]:" + ec2_instance_type = _ask_field(ec2_instance_query, lambda x: str(x).lower(), default="ml.p3.2xlarge") + + debug = False + if distributed_type != SageMakerDistributedType.NO: + debug = _ask_field( + "Should distributed operations be checked while running for errors? This can avoid timeout issues but will be slower. [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + + num_machines = 1 + if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): + num_machines = _ask_field( + "How many machines do you want use? [1]: ", + int, + default=1, + ) + + mixed_precision = _ask_options( + "Do you wish to use FP16 or BF16 (mixed precision)?", + ["no", "fp16", "bf16", "fp8"], + _convert_mixed_precision, + ) + + if use_dynamo and mixed_precision == "no": + print( + "Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts." + ) + + return SageMakerConfig( + image_uri=docker_image, + compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER, + distributed_type=distributed_type, + use_cpu=False, + dynamo_config=dynamo_config, + ec2_instance_type=ec2_instance_type, + profile=aws_profile, + region=aws_region, + iam_role_name=iam_role_name, + mixed_precision=mixed_precision, + num_machines=num_machines, + sagemaker_inputs_file=sagemaker_inputs_file, + sagemaker_metrics_file=sagemaker_metrics_file, + debug=debug, + ) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/update.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/update.py new file mode 100644 index 0000000000000000000000000000000000000000..5f025594b04ada3e3a78687befc5c1bc1d236adf --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/update.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python + +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from pathlib import Path + +from .config_args import default_config_file, load_config_from_file +from .config_utils import SubcommandHelpFormatter + + +description = "Update an existing config file with the latest defaults while maintaining the old configuration." + + +def update_config(args): + """ + Update an existing config file with the latest defaults while maintaining the old configuration. + """ + config_file = args.config_file + if config_file is None and Path(default_config_file).exists(): + config_file = default_config_file + elif not Path(config_file).exists(): + raise ValueError(f"The passed config file located at {config_file} doesn't exist.") + config = load_config_from_file(config_file) + + if config_file.endswith(".json"): + config.to_json_file(config_file) + else: + config.to_yaml_file(config_file) + return config_file + + +def update_command_parser(parser, parents): + parser = parser.add_parser("update", parents=parents, help=description, formatter_class=SubcommandHelpFormatter) + parser.add_argument( + "--config_file", + default=None, + help=( + "The path to the config file to update. Will default to a file named default_config.yaml in the cache " + "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " + "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " + "with 'huggingface'." + ), + ) + + parser.set_defaults(func=update_config_command) + return parser + + +def update_config_command(args): + config_file = update_config(args) + print(f"Sucessfully updated the configuration file at {config_file}.") diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/env.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/env.py new file mode 100644 index 0000000000000000000000000000000000000000..3dd2170aea8ba48a08e31c8031c0447825ec4797 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/env.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python + +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import os +import platform +import subprocess + +import numpy as np +import psutil +import torch + +from accelerate import __version__ as version +from accelerate.commands.config import default_config_file, load_config_from_file + +from ..utils import is_mlu_available, is_musa_available, is_npu_available, is_sdaa_available, is_xpu_available + + +def env_command_parser(subparsers=None): + if subparsers is not None: + parser = subparsers.add_parser("env") + else: + parser = argparse.ArgumentParser("Accelerate env command") + + parser.add_argument( + "--config_file", default=None, help="The config file to use for the default values in the launching script." + ) + + if subparsers is not None: + parser.set_defaults(func=env_command) + return parser + + +def env_command(args): + pt_version = torch.__version__ + pt_cuda_available = torch.cuda.is_available() + pt_xpu_available = is_xpu_available() + pt_mlu_available = is_mlu_available() + pt_sdaa_available = is_sdaa_available() + pt_musa_available = is_musa_available() + pt_npu_available = is_npu_available() + + accelerator = "N/A" + if pt_cuda_available: + accelerator = "CUDA" + elif pt_xpu_available: + accelerator = "XPU" + elif pt_mlu_available: + accelerator = "MLU" + elif pt_sdaa_available: + accelerator = "SDAA" + elif pt_musa_available: + accelerator = "MUSA" + elif pt_npu_available: + accelerator = "NPU" + + accelerate_config = "Not found" + # Get the default from the config file. + if args.config_file is not None or os.path.isfile(default_config_file): + accelerate_config = load_config_from_file(args.config_file).to_dict() + + # if we can run which, get it + command = None + bash_location = "Not found" + if os.name == "nt": + command = ["where", "accelerate"] + elif os.name == "posix": + command = ["which", "accelerate"] + if command is not None: + bash_location = subprocess.check_output(command, text=True, stderr=subprocess.STDOUT).strip() + info = { + "`Accelerate` version": version, + "Platform": platform.platform(), + "`accelerate` bash location": bash_location, + "Python version": platform.python_version(), + "Numpy version": np.__version__, + "PyTorch version": f"{pt_version}", + "PyTorch accelerator": accelerator, + "System RAM": f"{psutil.virtual_memory().total / 1024**3:.2f} GB", + } + if pt_cuda_available: + info["GPU type"] = torch.cuda.get_device_name() + elif pt_xpu_available: + info["XPU type"] = torch.xpu.get_device_name() + elif pt_mlu_available: + info["MLU type"] = torch.mlu.get_device_name() + elif pt_sdaa_available: + info["SDAA type"] = torch.sdaa.get_device_name() + elif pt_musa_available: + info["MUSA type"] = torch.musa.get_device_name() + elif pt_npu_available: + info["CANN version"] = torch.version.cann + + print("\nCopy-and-paste the text below in your GitHub issue\n") + print("\n".join([f"- {prop}: {val}" for prop, val in info.items()])) + + print("- `Accelerate` default config:" if args.config_file is None else "- `Accelerate` config passed:") + accelerate_config_str = ( + "\n".join([f"\t- {prop}: {val}" for prop, val in accelerate_config.items()]) + if isinstance(accelerate_config, dict) + else f"\t{accelerate_config}" + ) + print(accelerate_config_str) + + info["`Accelerate` configs"] = accelerate_config + + return info + + +def main() -> int: + parser = env_command_parser() + args = parser.parse_args() + env_command(args) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/estimate.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/estimate.py new file mode 100644 index 0000000000000000000000000000000000000000..77571777c6c8e78b7729e4b29e1a98cea6e95de7 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/estimate.py @@ -0,0 +1,312 @@ +#!/usr/bin/env python + +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import torch +from huggingface_hub import model_info +from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError + +from accelerate import init_empty_weights +from accelerate.commands.utils import CustomArgumentParser +from accelerate.utils import ( + calculate_maximum_sizes, + convert_bytes, + is_timm_available, + is_transformers_available, +) + + +if is_transformers_available(): + import transformers + from transformers import AutoConfig, AutoModel + +if is_timm_available(): + import timm + + +def verify_on_hub(repo: str, token: str = None): + "Verifies that the model is on the hub and returns the model info." + try: + return model_info(repo, token=token) + except (OSError, GatedRepoError): + return "gated" + except RepositoryNotFoundError: + return "repo" + + +def check_has_model(error): + """ + Checks what library spawned `error` when a model is not found + """ + if is_timm_available() and isinstance(error, RuntimeError) and "Unknown model" in error.args[0]: + return "timm" + elif ( + is_transformers_available() + and isinstance(error, OSError) + and "does not appear to have a file named" in error.args[0] + ): + return "transformers" + else: + return "unknown" + + +def create_empty_model(model_name: str, library_name: str, trust_remote_code: bool = False, access_token: str = None): + """ + Creates an empty model in full precision from its parent library on the `Hub` to calculate the overall memory + consumption. + + Args: + model_name (`str`): + The model name on the Hub + library_name (`str`): + The library the model has an integration with, such as `transformers`. Will be used if `model_name` has no + metadata on the Hub to determine the library. + trust_remote_code (`bool`, `optional`, defaults to `False`): + Whether or not to allow for custom models defined on the Hub in their own modeling files. This option + should only be set to `True` for repositories you trust and in which you have read the code, as it will + execute code present on the Hub on your local machine. + access_token (`str`, `optional`, defaults to `None`): + The access token to use to access private or gated models on the Hub. (for use on the Gradio app) + + Returns: + `torch.nn.Module`: The torch model that has been initialized on the `meta` device. + + """ + model_info = verify_on_hub(model_name, access_token) + # Simplified errors + if model_info == "gated": + raise GatedRepoError( + f"Repo for model `{model_name}` is gated. You must be authenticated to access it. Please run `huggingface-cli login`." + ) + elif model_info == "repo": + raise RepositoryNotFoundError( + f"Repo for model `{model_name}` does not exist on the Hub. If you are trying to access a private repo," + " make sure you are authenticated via `huggingface-cli login` and have access." + ) + if library_name is None: + library_name = getattr(model_info, "library_name", False) + if not library_name: + raise ValueError( + f"Model `{model_name}` does not have any library metadata on the Hub, please manually pass in a `--library_name` to use (such as `transformers`)" + ) + if library_name == "transformers": + if not is_transformers_available(): + raise ImportError( + f"To check `{model_name}`, `transformers` must be installed. Please install it via `pip install transformers`" + ) + print(f"Loading pretrained config for `{model_name}` from `transformers`...") + if model_info.config is None: + raise RuntimeError(f"Tried to load `{model_name}` with `transformers` but it does not have any metadata.") + + auto_map = model_info.config.get("auto_map", False) + config = AutoConfig.from_pretrained(model_name, trust_remote_code=trust_remote_code, token=access_token) + with init_empty_weights(): + # remote code could specify a specific `AutoModel` class in the `auto_map` + constructor = AutoModel + if isinstance(auto_map, dict): + value = None + for key in auto_map.keys(): + if key.startswith("AutoModelFor"): + value = key + break + if value is not None: + constructor = getattr(transformers, value) + # we need to pass the dtype, otherwise it is going to use the torch_dtype that is saved in the config + model = constructor.from_config(config, torch_dtype=torch.float32, trust_remote_code=trust_remote_code) + elif library_name == "timm": + if not is_timm_available(): + raise ImportError( + f"To check `{model_name}`, `timm` must be installed. Please install it via `pip install timm`" + ) + print(f"Loading pretrained config for `{model_name}` from `timm`...") + with init_empty_weights(): + model = timm.create_model(model_name, pretrained=False) + else: + raise ValueError( + f"Library `{library_name}` is not supported yet, please open an issue on GitHub for us to add support." + ) + return model + + +def create_ascii_table(headers: list, rows: list, title: str): + "Creates a pretty table from a list of rows, minimal version of `tabulate`." + sep_char, in_between = "│", "─" + column_widths = [] + for i in range(len(headers)): + column_values = [row[i] for row in rows] + [headers[i]] + max_column_width = max(len(value) for value in column_values) + column_widths.append(max_column_width) + + formats = [f"%{column_widths[i]}s" for i in range(len(rows[0]))] + + pattern = f"{sep_char}{sep_char.join(formats)}{sep_char}" + diff = 0 + + def make_row(left_char, middle_char, right_char): + return f"{left_char}{middle_char.join([in_between * n for n in column_widths])}{in_between * diff}{right_char}" + + separator = make_row("├", "┼", "┤") + if len(title) > sum(column_widths): + diff = abs(len(title) - len(separator)) + column_widths[-1] += diff + + # Update with diff + separator = make_row("├", "┼", "┤") + initial_rows = [ + make_row("┌", in_between, "┐"), + f"{sep_char}{title.center(len(separator) - 2)}{sep_char}", + make_row("├", "┬", "┤"), + ] + table = "\n".join(initial_rows) + "\n" + column_widths[-1] += diff + centered_line = [text.center(column_widths[i]) for i, text in enumerate(headers)] + table += f"{pattern % tuple(centered_line)}\n{separator}\n" + for i, line in enumerate(rows): + centered_line = [t.center(column_widths[i]) for i, t in enumerate(line)] + table += f"{pattern % tuple(centered_line)}\n" + table += f"└{'┴'.join([in_between * n for n in column_widths])}┘" + + return table + + +def estimate_command_parser(subparsers=None): + if subparsers is not None: + parser = subparsers.add_parser("estimate-memory") + else: + parser = CustomArgumentParser(description="Model size estimator for fitting a model onto CUDA memory.") + + parser.add_argument("model_name", type=str, help="The model name on the Hugging Face Hub.") + parser.add_argument( + "--library_name", + type=str, + help="The library the model has an integration with, such as `transformers`, needed only if this information is not stored on the Hub.", + choices=["timm", "transformers"], + ) + parser.add_argument( + "--dtypes", + type=str, + nargs="+", + default=["float32", "float16", "int8", "int4"], + help="The dtypes to use for the model, must be one (or many) of `float32`, `float16`, `int8`, and `int4`", + choices=["float32", "float16", "int8", "int4"], + ) + parser.add_argument( + "--trust_remote_code", + action="store_true", + help="""Whether or not to allow for custom models defined on the Hub in their own modeling files. This flag + should only be used for repositories you trust and in which you have read the code, as it will execute + code present on the Hub on your local machine.""", + default=False, + ) + + if subparsers is not None: + parser.set_defaults(func=estimate_command) + return parser + + +def estimate_training_usage(bytes: int, mixed_precision: str, msamp_config: str = None) -> dict: + """ + Given an amount of `bytes` and `mixed_precision`, calculates how much training memory is needed for a batch size of + 1. + + Args: + bytes (`int`): + The size of the model being trained. + mixed_precision (`str`): + The mixed precision that would be ran. + msamp_config (`str`): + The msamp config to estimate the training memory for if `mixed_precision` is set to `"fp8"`. + """ + memory_sizes = {"model": -1, "optimizer": -1, "gradients": -1, "step": -1} + fp32_size = bytes + fp16_size = bytes // 2 + + if mixed_precision == "float32": + memory_sizes["model"] = fp32_size + memory_sizes["gradients"] = fp32_size + memory_sizes["optimizer"] = fp32_size * 2 + memory_sizes["step"] = fp32_size * 4 + elif mixed_precision in ("float16", "bfloat16") or (mixed_precision == "fp8" and msamp_config is None): + # With native `TransformersEngine`, there is no memory savings with FP8 + # With mixed precision training, the model has weights stored + # in FP16 and FP32 + memory_sizes["model"] = fp32_size + # 1.5 from weight gradient + computation (GEMM) + memory_sizes["gradients"] = fp32_size + fp16_size + # 2x from optimizer states + memory_sizes["optimizer"] = fp32_size * 2 # Optimizer states + memory_sizes["step"] = memory_sizes["optimizer"] + return memory_sizes + + +def gather_data(args): + "Creates an empty model and gathers the data for the sizes" + try: + model = create_empty_model( + args.model_name, library_name=args.library_name, trust_remote_code=args.trust_remote_code + ) + except (RuntimeError, OSError) as e: + library = check_has_model(e) + if library != "unknown": + raise RuntimeError( + f"Tried to load `{args.model_name}` with `{library}` but a possible model to load was not found inside the repo." + ) + raise e + + total_size, largest_layer = calculate_maximum_sizes(model) + + data = [] + + for dtype in args.dtypes: + dtype_total_size = total_size + dtype_largest_layer = largest_layer[0] + dtype_training_size = estimate_training_usage(dtype_total_size, dtype) + if dtype == "float16": + dtype_total_size /= 2 + dtype_largest_layer /= 2 + elif dtype == "int8": + dtype_total_size /= 4 + dtype_largest_layer /= 4 + elif dtype == "int4": + dtype_total_size /= 8 + dtype_largest_layer /= 8 + data.append([dtype, dtype_largest_layer, dtype_total_size, dtype_training_size]) + return data + + +def estimate_command(args): + data = gather_data(args) + for row in data: + for i, item in enumerate(row): + if isinstance(item, (int, float)): + row[i] = convert_bytes(item) + elif isinstance(item, dict): + training_usage = max(item.values()) + row[i] = convert_bytes(training_usage) if training_usage != -1 else "N/A" + + headers = ["dtype", "Largest Layer", "Total Size", "Training using Adam"] + + title = f"Memory Usage for loading `{args.model_name}`" + table = create_ascii_table(headers, data, title) + print(table) + + +def main(): + parser = estimate_command_parser() + args = parser.parse_args() + estimate_command(args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/launch.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..fe7609957ec2838061abb8fb41fd3aebc00c3b22 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/launch.py @@ -0,0 +1,1258 @@ +#!/usr/bin/env python + +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import importlib +import logging +import os +import subprocess +import sys +from pathlib import Path + +import psutil +import torch + +from accelerate.commands.config import default_config_file, load_config_from_file +from accelerate.commands.config.config_args import SageMakerConfig +from accelerate.commands.config.config_utils import DYNAMO_BACKENDS +from accelerate.commands.utils import CustomArgumentParser +from accelerate.state import get_int_from_env +from accelerate.utils import ( + ComputeEnvironment, + DistributedType, + PrepareForLaunch, + _filter_args, + check_cuda_p2p_ib_support, + convert_dict_to_env_variables, + is_bf16_available, + is_deepspeed_available, + is_hpu_available, + is_mlu_available, + is_musa_available, + is_npu_available, + is_rich_available, + is_sagemaker_available, + is_sdaa_available, + is_torch_xla_available, + is_xpu_available, + patch_environment, + prepare_deepspeed_cmd_env, + prepare_multi_gpu_env, + prepare_sagemager_args_inputs, + prepare_simple_launcher_cmd_env, + prepare_tpu, + str_to_bool, +) +from accelerate.utils.constants import DEEPSPEED_MULTINODE_LAUNCHERS, TORCH_DYNAMO_MODES + + +if is_rich_available(): + from rich import get_console + from rich.logging import RichHandler + + FORMAT = "%(message)s" + logging.basicConfig(format=FORMAT, datefmt="[%X]", handlers=[RichHandler()]) + + +logger = logging.getLogger(__name__) + + +options_to_group = { + "multi_gpu": "Distributed GPUs", + "tpu": "TPU", + "use_deepspeed": "DeepSpeed Arguments", + "use_fsdp": "FSDP Arguments", + "use_megatron_lm": "Megatron-LM Arguments", + "fp8_backend": "FP8 Arguments", +} + + +def clean_option(option): + "Finds all cases of - after the first two characters and changes them to _" + if "fp8_backend" in option: + option = "--fp8_backend" + if option.startswith("--"): + return option[2:].replace("-", "_") + + +class CustomHelpFormatter(argparse.HelpFormatter): + """ + This is a custom help formatter that will hide all arguments that are not used in the command line when the help is + called. This is useful for the case where the user is using a specific platform and only wants to see the arguments + for that platform. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.titles = [ + "Hardware Selection Arguments", + "Resource Selection Arguments", + "Training Paradigm Arguments", + "positional arguments", + "optional arguments", + ] + + def add_argument(self, action: argparse.Action): + if "accelerate" in sys.argv[0] and "launch" in sys.argv[1:]: + args = sys.argv[2:] + else: + args = sys.argv[1:] + + if len(args) > 1: + args = list(map(clean_option, args)) + used_platforms = [arg for arg in args if arg in options_to_group.keys()] + used_titles = [options_to_group[o] for o in used_platforms] + if action.container.title not in self.titles + used_titles: + action.help = argparse.SUPPRESS + elif action.container.title == "Hardware Selection Arguments": + if set(action.option_strings).isdisjoint(set(args)): + action.help = argparse.SUPPRESS + else: + action.help = action.help + " (currently selected)" + elif action.container.title == "Training Paradigm Arguments": + if set(action.option_strings).isdisjoint(set(args)): + action.help = argparse.SUPPRESS + else: + action.help = action.help + " (currently selected)" + + action.option_strings = [s for s in action.option_strings if "-" not in s[2:]] + super().add_argument(action) + + def end_section(self): + if len(self._current_section.items) < 2: + self._current_section.items = [] + self._current_section.heading = "" + super().end_section() + + +def launch_command_parser(subparsers=None): + description = "Launch a python script in a distributed scenario. Arguments can be passed in with either hyphens (`--num-processes=2`) or underscores (`--num_processes=2`)" + if subparsers is not None: + parser = subparsers.add_parser( + "launch", description=description, add_help=False, allow_abbrev=False, formatter_class=CustomHelpFormatter + ) + else: + parser = CustomArgumentParser( + "Accelerate launch command", + description=description, + add_help=False, + allow_abbrev=False, + formatter_class=CustomHelpFormatter, + ) + + parser.add_argument("-h", "--help", action="help", help="Show this help message and exit.") + + parser.add_argument( + "--config_file", + default=None, + help="The config file to use for the default values in the launching script.", + ) + parser.add_argument( + "--quiet", + "-q", + action="store_true", + help="Silence subprocess errors from the launch stack trace and only show the relevant tracebacks. (Only applicable to DeepSpeed and single-process configurations)", + ) + # Hardware selection arguments + hardware_args = parser.add_argument_group( + "Hardware Selection Arguments", "Arguments for selecting the hardware to be used." + ) + hardware_args.add_argument( + "--cpu", default=False, action="store_true", help="Whether or not to force the training on the CPU." + ) + hardware_args.add_argument( + "--multi_gpu", + default=False, + action="store_true", + help="Whether or not this should launch a distributed GPU training.", + ) + hardware_args.add_argument( + "--tpu", default=False, action="store_true", help="Whether or not this should launch a TPU training." + ) + hardware_args.add_argument( + "--ipex", + default=False, + action="store_true", + help="Whether or not this should launch a Intel PyTorch Extension (IPEX) training.", + ) + + # Resource selection arguments + resource_args = parser.add_argument_group( + "Resource Selection Arguments", "Arguments for fine-tuning how available hardware should be used." + ) + resource_args.add_argument( + "--mixed_precision", + type=str, + choices=["no", "fp16", "bf16", "fp8"], + help="Whether or not to use mixed precision training. " + "Choose between FP16 and BF16 (bfloat16) training. " + "BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.", + ) + resource_args.add_argument( + "--num_processes", type=int, default=None, help="The total number of processes to be launched in parallel." + ) + resource_args.add_argument( + "--num_machines", type=int, default=None, help="The total number of machines used in this training." + ) + resource_args.add_argument( + "--num_cpu_threads_per_process", + type=int, + default=None, + help="The number of CPU threads per process. Can be tuned for optimal performance.", + ) + resource_args.add_argument( + "--enable_cpu_affinity", + default=False, + action="store_true", + help="Whether or not CPU affinity and balancing should be enabled. Currently only supported on NVIDIA hardware.", + ) + # Dynamo arguments + resource_args.add_argument( + "--dynamo_backend", + type=str, + choices=["no"] + [b.lower() for b in DYNAMO_BACKENDS], + help="Choose a backend to optimize your training with dynamo, see more at " + "https://github.com/pytorch/torchdynamo.", + ) + resource_args.add_argument( + "--dynamo_mode", + type=str, + default="default", + choices=TORCH_DYNAMO_MODES, + help="Choose a mode to optimize your training with dynamo.", + ) + resource_args.add_argument( + "--dynamo_use_fullgraph", + default=False, + action="store_true", + help="Whether to use full graph mode for dynamo or it is ok to break model into several subgraphs", + ) + resource_args.add_argument( + "--dynamo_use_dynamic", + default=False, + action="store_true", + help="Whether to enable dynamic shape tracing.", + ) + resource_args.add_argument( + "--dynamo_use_regional_compilation", + default=False, + action="store_true", + help="Whether to enable regional compilation.", + ) + + # Training Paradigm arguments + paradigm_args = parser.add_argument_group( + "Training Paradigm Arguments", "Arguments for selecting which training paradigm to be used." + ) + paradigm_args.add_argument( + "--use_deepspeed", + default=False, + action="store_true", + help="Whether to use deepspeed.", + ) + paradigm_args.add_argument( + "--use_fsdp", + default=False, + action="store_true", + help="Whether to use fsdp.", + ) + paradigm_args.add_argument( + "--use_parallelism_config", + default=False, + action="store_true", + help="Whether to use the parallelism config to configure the N-d distributed training.", + ) + paradigm_args.add_argument( + "--use_megatron_lm", + default=False, + action="store_true", + help="Whether to use Megatron-LM.", + ) + + paradigm_args.add_argument( + "--use_xpu", + default=None, + action="store_true", + help="Whether to use IPEX plugin to speed up training on XPU specifically. This argument is deprecated and ignored, will be removed in Accelerate v1.20.", + ) + + # distributed GPU training arguments + distributed_args = parser.add_argument_group("Distributed GPUs", "Arguments related to distributed GPU training.") + distributed_args.add_argument( + "--gpu_ids", + default=None, + help="What GPUs (by id) should be used for training on this machine as a comma-separated list", + ) + distributed_args.add_argument( + "--same_network", + default=False, + action="store_true", + help="Whether all machines used for multinode training exist on the same local network.", + ) + distributed_args.add_argument( + "--machine_rank", type=int, default=None, help="The rank of the machine on which this script is launched." + ) + distributed_args.add_argument( + "--main_process_ip", type=str, default=None, help="The IP address of the machine of rank 0." + ) + distributed_args.add_argument( + "--main_process_port", + type=int, + default=None, + help="The port to use to communicate with the machine of rank 0.", + ) + distributed_args.add_argument( + "-t", + "--tee", + default="0", + type=str, + help="Tee std streams into a log file and also to console.", + ) + distributed_args.add_argument( + "--log_dir", + type=str, + default=None, + help=( + "Base directory to use for log files when using torchrun/torch.distributed.run as launcher. " + "Use with --tee to redirect std streams info log files." + ), + ) + distributed_args.add_argument( + "--role", + type=str, + default="default", + help="User-defined role for the workers.", + ) + # Rendezvous related arguments + distributed_args.add_argument( + "--rdzv_backend", + type=str, + default="static", + help="The rendezvous method to use, such as 'static' (the default) or 'c10d'", + ) + distributed_args.add_argument( + "--rdzv_conf", + type=str, + default="", + help="Additional rendezvous configuration (=,=,...).", + ) + distributed_args.add_argument( + "--max_restarts", + type=int, + default=0, + help="Maximum number of worker group restarts before failing.", + ) + distributed_args.add_argument( + "--monitor_interval", + type=float, + default=0.1, + help="Interval, in seconds, to monitor the state of workers.", + ) + parser.add_argument( + "-m", + "--module", + action="store_true", + help="Change each process to interpret the launch script as a Python module, executing with the same behavior as 'python -m'.", + ) + parser.add_argument( + "--no_python", + action="store_true", + help="Skip prepending the training script with 'python' - just execute it directly. Useful when the script is not a Python script.", + ) + + # TPU arguments + tpu_args = parser.add_argument_group("TPU", "Arguments related to TPU.") + tpu_args.add_argument( + "--tpu_cluster", + action="store_true", + dest="tpu_use_cluster", + help="Whether to use a GCP TPU pod for training.", + ) + tpu_args.add_argument( + "--no_tpu_cluster", + action="store_false", + dest="tpu_use_cluster", + help="Should not be passed explicitly, this is for internal use only.", + ) + tpu_args.add_argument( + "--tpu_use_sudo", + action="store_true", + help="Whether to use `sudo` when running the TPU training script in each pod.", + ) + tpu_args.add_argument( + "--vm", + type=str, + action="append", + help=( + "List of single Compute VM instance names. " + "If not provided we assume usage of instance groups. For TPU pods." + ), + ) + tpu_args.add_argument( + "--env", + type=str, + action="append", + help="List of environment variables to set on the Compute VM instances. For TPU pods.", + ) + tpu_args.add_argument( + "--main_training_function", + type=str, + default=None, + help="The name of the main function to be executed in your script (only for TPU training).", + ) + tpu_args.add_argument( + "--downcast_bf16", + action="store_true", + help="Whether when using bf16 precision on TPUs if both float and double tensors are cast to bfloat16 or if double tensors remain as float32.", + ) + + # DeepSpeed arguments + deepspeed_args = parser.add_argument_group("DeepSpeed Arguments", "Arguments related to DeepSpeed.") + deepspeed_args.add_argument( + "--deepspeed_config_file", + default=None, + type=str, + help="DeepSpeed config file.", + ) + deepspeed_args.add_argument( + "--zero_stage", + default=None, + type=int, + help="DeepSpeed's ZeRO optimization stage (useful only when `use_deepspeed` flag is passed). " + "If unspecified, will default to `2`.", + ) + deepspeed_args.add_argument( + "--offload_optimizer_device", + default=None, + type=str, + help="Decides where (none|cpu|nvme) to offload optimizer states (useful only when `use_deepspeed` flag is passed). " + "If unspecified, will default to 'none'.", + ) + deepspeed_args.add_argument( + "--offload_param_device", + default=None, + type=str, + help="Decides where (none|cpu|nvme) to offload parameters (useful only when `use_deepspeed` flag is passed). " + "If unspecified, will default to 'none'.", + ) + deepspeed_args.add_argument( + "--offload_optimizer_nvme_path", + default=None, + type=str, + help="Decides Nvme Path to offload optimizer states (useful only when `use_deepspeed` flag is passed). " + "If unspecified, will default to 'none'.", + ) + deepspeed_args.add_argument( + "--offload_param_nvme_path", + default=None, + type=str, + help="Decides Nvme Path to offload parameters (useful only when `use_deepspeed` flag is passed). " + "If unspecified, will default to 'none'.", + ) + deepspeed_args.add_argument( + "--gradient_accumulation_steps", + default=None, + type=int, + help="No of gradient_accumulation_steps used in your training script (useful only when `use_deepspeed` flag is passed). " + "If unspecified, will default to `1`.", + ) + deepspeed_args.add_argument( + "--gradient_clipping", + default=None, + type=float, + help="gradient clipping value used in your training script (useful only when `use_deepspeed` flag is passed). " + "If unspecified, will default to `1.0`.", + ) + deepspeed_args.add_argument( + "--zero3_init_flag", + default=None, + type=str, + help="Decides Whether (true|false) to enable `deepspeed.zero.Init` for constructing massive models. " + "Only applicable with DeepSpeed ZeRO Stage-3. If unspecified, will default to `true`.", + ) + deepspeed_args.add_argument( + "--zero3_save_16bit_model", + default=None, + type=str, + help="Decides Whether (true|false) to save 16-bit model weights when using ZeRO Stage-3. " + "Only applicable with DeepSpeed ZeRO Stage-3. If unspecified, will default to `false`.", + ) + deepspeed_args.add_argument( + "--deepspeed_hostfile", + default=None, + type=str, + help="DeepSpeed hostfile for configuring multi-node compute resources.", + ) + deepspeed_args.add_argument( + "--deepspeed_exclusion_filter", + default=None, + type=str, + help="DeepSpeed exclusion filter string when using mutli-node setup.", + ) + deepspeed_args.add_argument( + "--deepspeed_inclusion_filter", + default=None, + type=str, + help="DeepSpeed inclusion filter string when using mutli-node setup.", + ) + deepspeed_args.add_argument( + "--deepspeed_multinode_launcher", + default=None, + type=str, + help="DeepSpeed multi-node launcher to use, e.g. `pdsh`, `standard`, `openmpi`, `mvapich`, `mpich`, `slurm`, `nossh` (requires DeepSpeed >= 0.14.5). If unspecified, will default to `pdsh`.", + ) + deepspeed_args.add_argument( + "--deepspeed_moe_layer_cls_names", + default=None, + type=str, + help="comma-separated list of transformer MoE layer class names (case-sensitive) to wrap ,e.g, `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ..." + " (useful only when `use_deepspeed` flag is passed).", + ) + + # fsdp arguments + fsdp_args = parser.add_argument_group("FSDP Arguments", "Arguments related to Fully Shared Data Parallelism.") + fsdp_args.add_argument( + "--fsdp_version", + type=str, + default="1", + choices=["1", "2"], + help="FSDP version to use. (useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_offload_params", + default="false", + type=str, + help="Decides Whether (true|false) to offload parameters and gradients to CPU. (useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_min_num_params", + type=int, + default=1e8, + help="FSDP's minimum number of parameters for Default Auto Wrapping. (useful only when `use_fsdp` flag is passed).", + ) + # We enable this for backwards compatibility, throw a warning if this is set in `FullyShardedDataParallelPlugin` + fsdp_args.add_argument( + "--fsdp_sharding_strategy", + type=str, + default="FULL_SHARD", + help="FSDP's sharding strategy. (useful only when `use_fsdp` flag is passed and `fsdp_version=1`).", + ) + fsdp_args.add_argument( + "--fsdp_reshard_after_forward", + type=str, + default="true", + help="FSDP's Reshard After Forward Strategy. (useful only when `use_fsdp` flag is passed). Supports either boolean (FSDP2) or `FULL_SHARD | SHARD_GRAD_OP | NO_RESHARD` (FSDP1).", + ) + fsdp_args.add_argument( + "--fsdp_auto_wrap_policy", + type=str, + default=None, + help="FSDP's auto wrap policy. (useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_transformer_layer_cls_to_wrap", + default=None, + type=str, + help="Transformer layer class name (case-sensitive) to wrap ,e.g, `BertLayer`, `GPTJBlock`, `T5Block` .... " + "(useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_backward_prefetch", + default=None, + type=str, + help="FSDP's backward prefetch policy. (useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_state_dict_type", + default=None, + type=str, + help="FSDP's state dict type. (useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_forward_prefetch", + default="false", + type=str, + help="If True, then FSDP explicitly prefetches the next upcoming " + "all-gather while executing in the forward pass (useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_use_orig_params", + default="true", + type=str, + help="If True, allows non-uniform `requires_grad` during init, which means support for interspersed frozen and trainable paramteres." + " (useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_cpu_ram_efficient_loading", + default="true", + type=str, + help="If True, only the first process loads the pretrained model checkoint while all other processes have empty weights. " + "Only applicable for 🤗 Transformers. When using this, `--fsdp_sync_module_states` needs to True. " + "(useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_sync_module_states", + default="true", + type=str, + help="If True, each individually wrapped FSDP unit will broadcast module parameters from rank 0." + " (useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_activation_checkpointing", + default="false", + type=str, + help="Decides Whether (true|false) intermediate activations are freed during the forward pass, and a checkpoint is left as a placeholder. (useful only when `use_fsdp` flag is passed).", + ) + + # megatron_lm args + megatron_lm_args = parser.add_argument_group("Megatron-LM Arguments", "Arguments related to Megatron-LM.") + megatron_lm_args.add_argument( + "--megatron_lm_tp_degree", + type=int, + default=1, + help="Megatron-LM's Tensor Parallelism (TP) degree. (useful only when `use_megatron_lm` flag is passed).", + ) + megatron_lm_args.add_argument( + "--megatron_lm_pp_degree", + type=int, + default=1, + help="Megatron-LM's Pipeline Parallelism (PP) degree. (useful only when `use_megatron_lm` flag is passed).", + ) + megatron_lm_args.add_argument( + "--megatron_lm_num_micro_batches", + type=int, + default=None, + help="Megatron-LM's number of micro batches when PP degree > 1. (useful only when `use_megatron_lm` flag is passed).", + ) + megatron_lm_args.add_argument( + "--megatron_lm_sequence_parallelism", + default=None, + type=str, + help="Decides Whether (true|false) to enable Sequence Parallelism when TP degree > 1. " + "(useful only when `use_megatron_lm` flag is passed).", + ) + megatron_lm_args.add_argument( + "--megatron_lm_recompute_activations", + default=None, + type=str, + help="Decides Whether (true|false) to enable Selective Activation Recomputation. " + "(useful only when `use_megatron_lm` flag is passed).", + ) + megatron_lm_args.add_argument( + "--megatron_lm_use_distributed_optimizer", + default=None, + type=str, + help="Decides Whether (true|false) to use distributed optimizer " + "which shards optimizer state and gradients across Data Pralellel (DP) ranks. " + "(useful only when `use_megatron_lm` flag is passed).", + ) + megatron_lm_args.add_argument( + "--megatron_lm_gradient_clipping", + default=1.0, + type=float, + help="Megatron-LM's gradient clipping value based on global L2 Norm (0 to disable). " + "(useful only when `use_megatron_lm` flag is passed).", + ) + + # FP8 arguments + fp8_args = parser.add_argument_group( + "FP8 Arguments", "Arguments related to FP8 training (requires `--mixed_precision=fp8`)" + ) + fp8_args.add_argument( + "--fp8_backend", + type=str, + choices=["te", "msamp"], + help="Choose a backend to train with FP8 (te: TransformerEngine, msamp: MS-AMP)", + ) + fp8_args.add_argument( + "--fp8_use_autocast_during_eval", + default=False, + action="store_true", + help="Whether to use FP8 autocast during eval mode (useful only when `--fp8_backend=te` is passed). Generally better metrics are found when this is not passed.", + ) + fp8_args.add_argument( + "--fp8_margin", + type=int, + default=0, + help="The margin to use for the gradient scaling (useful only when `--fp8_backend=te` is passed).", + ) + fp8_args.add_argument( + "--fp8_interval", + type=int, + default=1, + help="The interval to use for how often the scaling factor is recomputed (useful only when `--fp8_backend=te` is passed).", + ) + fp8_args.add_argument( + "--fp8_format", + type=str, + default="HYBRID", + choices=["HYBRID", "E4M3", "E5M2"], + help="The format to use for the FP8 recipe (useful only when `--fp8_backend=te` is passed).", + ) + fp8_args.add_argument( + "--fp8_amax_history_len", + type=int, + default=1024, + help="The length of the history to use for the scaling factor computation (useful only when `--fp8_backend=te` is passed).", + ) + fp8_args.add_argument( + "--fp8_amax_compute_algo", + type=str, + default="most_recent", + choices=["max", "most_recent"], + help="The algorithm to use for the scaling factor computation. (useful only when `--fp8_backend=te` is passed).", + ) + fp8_args.add_argument( + "--fp8_override_linear_precision", + type=lambda x: tuple(map(str_to_bool, x.split(","))), + default=(False, False, False), + help="Whether or not to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision. Should be passed in a comma-separated string of booleans (useful only when `--fp8_backend=te` is passed).", + ) + fp8_args.add_argument( + "--fp8_opt_level", + type=str, + default="O2", + choices=["O1", "O2"], + help="What level of 8-bit collective communication should be used with MS-AMP (useful only when `--fp8_backend=msamp` is passed).", + ) + + # AWS arguments + aws_args = parser.add_argument_group("AWS Arguments", "Arguments related to AWS.") + aws_args.add_argument( + "--aws_access_key_id", + type=str, + default=None, + help="The AWS_ACCESS_KEY_ID used to launch the Amazon SageMaker training job", + ) + aws_args.add_argument( + "--aws_secret_access_key", + type=str, + default=None, + help="The AWS_SECRET_ACCESS_KEY used to launch the Amazon SageMaker training job.", + ) + parser.add_argument( + "--debug", + action="store_true", + help="Whether to print out the torch.distributed stack trace when something fails.", + ) + parser.add_argument( + "training_script", + type=str, + help=( + "The full path to the script to be launched in parallel, followed by all the arguments for the training " + "script." + ), + ) + + # MPI arguments + mpirun_args = parser.add_argument_group("MPI Arguments", "Arguments related to mpirun for Multi-CPU") + mpirun_args.add_argument( + "--mpirun_hostfile", + type=str, + default=None, + help="Location for a hostfile for using Accelerate to launch a multi-CPU training job with mpirun. This will " + "get passed to the MPI --hostfile or -f parameter, depending on which MPI program is installed.", + ) + mpirun_args.add_argument( + "--mpirun_ccl", + type=int, + default=1, + help="The number of oneCCL worker threads when using Accelerate to launch multi-CPU training with mpirun.", + ) + + # ParallelismConfig arguments + parallelism_config_args = parser.add_argument_group( + "ParallelismConfig Arguments", + "Arguments related to the ParallelismConfig used for distributed training.", + ) + parallelism_config_args.add_argument( + "--parallelism_config_dp_replicate_size", + type=int, + default=1, + help="The number of processes for data parallel training. Defaults to 1 (no data parallelism).", + ) + + parallelism_config_args.add_argument( + "--parallelism_config_dp_shard_size", + type=int, + default=1, + help="The number of processes for FSDP sharding. Defaults to 1 (No FSDP sharding).", + ) + + parallelism_config_args.add_argument( + "--parallelism_config_tp_size", + type=int, + default=1, + help="The number of processes for tensor parallel training. Defaults to 1 (no tensor parallelism).", + ) + + parallelism_config_args.add_argument( + "--parallelism_config_cp_size", + type=int, + default=1, + help="The number of processese for context parallel training. Defaults to 1 (no context parallelism).", + ) + parallelism_config_args.add_argument( + "--parallelism_config_cp_comm_strategy", + type=str, + default="allgather", + help="The communication strategy for context parallel training. Defaults to 'allgather'. Other option is alltoall", + ) + + # Other arguments of the training scripts + parser.add_argument("training_script_args", nargs=argparse.REMAINDER, help="Arguments of the training script.") + + if subparsers is not None: + parser.set_defaults(func=launch_command) + return parser + + +def simple_launcher(args): + cmd, current_env = prepare_simple_launcher_cmd_env(args) + + process = subprocess.Popen(cmd, env=current_env) + process.wait() + if process.returncode != 0: + if not args.quiet: + raise subprocess.CalledProcessError(returncode=process.returncode, cmd=cmd) + else: + sys.exit(1) + + +def multi_gpu_launcher(args): + import torch.distributed.run as distrib_run + + current_env = prepare_multi_gpu_env(args) + if not check_cuda_p2p_ib_support(): + message = "Using RTX 4000 series which doesn't support faster communication speedups. Ensuring P2P and IB communications are disabled." + warn = False + if "NCCL_P2P_DISABLE" not in current_env: + current_env["NCCL_P2P_DISABLE"] = "1" + warn = True + if "NCCL_IB_DISABLE" not in current_env: + current_env["NCCL_IB_DISABLE"] = "1" + warn = True + if warn: + logger.warning(message) + + debug = getattr(args, "debug", False) + args = _filter_args( + args, + distrib_run.get_args_parser(), + ["--training_script", args.training_script, "--training_script_args", args.training_script_args], + ) + + with patch_environment(**current_env): + try: + distrib_run.run(args) + except Exception: + if is_rich_available() and debug: + console = get_console() + console.print("\n[bold red]Using --debug, `torch.distributed` Stack Trace:[/bold red]") + console.print_exception(suppress=[__file__], show_locals=False) + else: + raise + + +def deepspeed_launcher(args): + import torch.distributed.run as distrib_run + + if not is_deepspeed_available(): + raise ImportError("DeepSpeed is not installed => run `pip3 install deepspeed` or build it from source.") + else: + from deepspeed.launcher.runner import DEEPSPEED_ENVIRONMENT_NAME + + cmd, current_env = prepare_deepspeed_cmd_env(args) + if not check_cuda_p2p_ib_support(): + message = "Using RTX 4000 series which doesn't support faster communication speedups. Ensuring P2P and IB communications are disabled." + warn = False + if "NCCL_P2P_DISABLE" not in current_env: + current_env["NCCL_P2P_DISABLE"] = "1" + warn = True + if "NCCL_IB_DISABLE" not in current_env: + current_env["NCCL_IB_DISABLE"] = "1" + warn = True + if warn: + logger.warning(message) + + if args.num_machines > 1 and args.deepspeed_multinode_launcher != DEEPSPEED_MULTINODE_LAUNCHERS[1]: + with open(DEEPSPEED_ENVIRONMENT_NAME, "a") as f: + valid_env_items = convert_dict_to_env_variables(current_env) + if len(valid_env_items) > 1: + f.writelines(valid_env_items) + + process = subprocess.Popen(cmd, env=current_env) + process.wait() + if process.returncode != 0: + if not args.quiet: + raise subprocess.CalledProcessError(returncode=process.returncode, cmd=cmd) + else: + sys.exit(1) + else: + debug = getattr(args, "debug", False) + args = _filter_args( + args, + distrib_run.get_args_parser(), + ["--training_script", args.training_script, "--training_script_args", args.training_script_args], + ) + with patch_environment(**current_env): + try: + distrib_run.run(args) + except Exception: + if is_rich_available() and debug: + console = get_console() + console.print("\n[bold red]Using --debug, `torch.distributed` Stack Trace:[/bold red]") + console.print_exception(suppress=[__file__], show_locals=False) + else: + raise + + +def tpu_launcher(args): + import torch_xla.distributed.xla_multiprocessing as xmp + + if args.no_python: + raise ValueError("--no_python cannot be used with TPU launcher") + + args, current_env = prepare_tpu(args, {}) + + if args.module: + mod_name = args.training_script + else: + # Import training_script as a module + script_path = Path(args.training_script) + sys.path.append(str(script_path.parent.resolve())) + mod_name = script_path.stem + + mod = importlib.import_module(mod_name) + if not hasattr(mod, args.main_training_function): + raise ValueError( + f"Your training script should have a function named {args.main_training_function}, or you should pass a " + "different value to `--main_training_function`." + ) + + # Patch sys.argv + sys.argv = [mod.__file__] + args.training_script_args + + main_function = getattr(mod, args.main_training_function) + with patch_environment(**current_env): + xmp.spawn(PrepareForLaunch(main_function), args=()) + + +def tpu_pod_launcher(args): + from torch_xla.distributed import xla_dist + + current_env = {} + args, current_env = prepare_tpu(args, current_env, True) + debug = getattr(args, "debug", False) + + training_script = args.training_script + training_script_args = args.training_script_args + new_args = _filter_args( + args, xla_dist.get_args_parser(), ["--tpu", args.tpu_name, "--positional", "", "--restart-tpuvm-pod-server"] + ) + + if args.tpu_use_sudo: + new_cmd = ["sudo"] + else: + new_cmd = [] + + new_cmd += [ + "accelerate-launch", + "--tpu", + "--no_tpu_cluster", + "--num_machines", + "1", + "--mixed_precision", + "no", + "--dynamo_backend", + "no", + "--num_processes", + str(args.num_processes), + "--main_training_function", + str(args.main_training_function), + training_script, + ] + training_script_args + + new_args.positional = new_cmd + bad_flags = "" + for arg in vars(new_args): + if arg.startswith("docker_"): + value = getattr(new_args, arg) + if value != "" and value is not None: + bad_flags += f'{arg}="{value}"\n' + if bad_flags != "": + raise ValueError( + f"Docker containers are not supported for TPU pod launcher currently, please remove the following flags:\n{bad_flags}" + ) + new_args.env = [f"{k}={v}" for k, v in current_env.items()] + new_args.env.append("ACCELERATE_IN_TPU_POD=1") + try: + xla_dist.resolve_and_execute(new_args) + except Exception: + if is_rich_available() and debug: + console = get_console() + console.print("\n[bold red]Using --debug, `torch_xla.xla_dist` Stack Trace:[/bold red]") + console.print_exception(suppress=[__file__], show_locals=False) + else: + raise + + +def sagemaker_launcher(sagemaker_config: SageMakerConfig, args): + if not is_sagemaker_available(): + raise ImportError( + "Please install sagemaker to be able to launch training on Amazon SageMaker with `pip install accelerate[sagemaker]`" + ) + if args.module or args.no_python: + raise ValueError( + "SageMaker requires a python training script file and cannot be used with --module or --no_python" + ) + + from sagemaker.huggingface import HuggingFace + + args, sagemaker_inputs = prepare_sagemager_args_inputs(sagemaker_config, args) + + huggingface_estimator = HuggingFace(**args) + + huggingface_estimator.fit(inputs=sagemaker_inputs) + print(f"You can find your model data at: {huggingface_estimator.model_data}") + + +def _validate_launch_command(args): + # Sanity checks + if sum([args.multi_gpu, args.cpu, args.tpu, args.use_deepspeed, args.use_fsdp]) > 1: + raise ValueError( + "You can only use one of `--cpu`, `--multi_gpu`, `--tpu`, `--use_deepspeed`, `--use_fsdp` at a time." + ) + if args.multi_gpu and (args.num_processes is not None) and (args.num_processes < 2): + raise ValueError("You need to use at least 2 processes to use `--multi_gpu`.") + + if (not args.use_fsdp or args.fsdp_version == 1) and args.use_parallelism_config: + raise ValueError("You cannot use `--use_parallelism_config` without `--use_fsdp` and `--fsdp_version=2`. ") + + defaults = None + warned = [] + mp_from_config_flag = False + # Get the default from the config file. + if args.config_file is not None or os.path.isfile(default_config_file) and not args.cpu: + defaults = load_config_from_file(args.config_file) + if ( + not args.multi_gpu + and not args.tpu + and not args.tpu_use_cluster + and not args.use_deepspeed + and not args.use_fsdp + and not args.use_megatron_lm + ): + args.use_deepspeed = defaults.distributed_type == DistributedType.DEEPSPEED + args.multi_gpu = ( + True + if defaults.distributed_type + in ( + DistributedType.MULTI_GPU, + DistributedType.MULTI_NPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_SDAA, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_XPU, + DistributedType.MULTI_HPU, + ) + else False + ) + args.tpu = defaults.distributed_type == DistributedType.XLA + args.use_fsdp = defaults.distributed_type == DistributedType.FSDP + args.use_megatron_lm = defaults.distributed_type == DistributedType.MEGATRON_LM + args.tpu_use_cluster = defaults.tpu_use_cluster if args.tpu else False + args.use_parallelism_config = defaults.parallelism_config != {} + if args.gpu_ids is None: + if defaults.gpu_ids is not None: + args.gpu_ids = defaults.gpu_ids + else: + args.gpu_ids = "all" + + if args.multi_gpu and args.num_machines is None: + args.num_machines = defaults.num_machines + + if len(args.gpu_ids.split(",")) < 2 and (args.gpu_ids != "all") and args.multi_gpu and args.num_machines <= 1: + raise ValueError( + "Less than two GPU ids were configured and tried to run on on multiple GPUs. " + "Please ensure at least two are specified for `--gpu_ids`, or use `--gpu_ids='all'`." + ) + if defaults.compute_environment == ComputeEnvironment.LOCAL_MACHINE: + # Update args with the defaults + for name, attr in defaults.__dict__.items(): + if isinstance(attr, dict): + # Copy defaults.somedict.somearg to args.somearg and + # defaults.fsdp_config.x to args.fsdp_x + for key, value in attr.items(): + if name == "fsdp_config" and not key.startswith("fsdp"): + key = "fsdp_" + key + elif name == "fp8_config" and not key.startswith("fp8"): + key = "fp8_" + key + if hasattr(args, "nondefault") and key not in args.nondefault: + setattr(args, key, value) + elif ( + name not in ["compute_environment", "mixed_precision", "distributed_type"] + and getattr(args, name, None) is None + ): + # Those args are handled separately + setattr(args, name, attr) + if not args.debug: + args.debug = defaults.debug + + if not args.mixed_precision: + if defaults.mixed_precision is None: + args.mixed_precision = "no" + else: + args.mixed_precision = defaults.mixed_precision + mp_from_config_flag = True + else: + native_amp = is_bf16_available(True) + if ( + args.mixed_precision == "bf16" + and not native_amp + and not (args.tpu and is_torch_xla_available(check_is_tpu=True)) + ): + raise ValueError("bf16 mixed precision requires PyTorch >= 1.10 and a supported device.") + + # Silently set the default here + if args.dynamo_backend is None: + args.dynamo_backend = "no" + if args.num_processes == -1: + raise ValueError("You need to manually pass in `--num_processes` using this config yaml.") + else: + if args.num_processes is None: + if is_xpu_available(): + args.num_processes = torch.xpu.device_count() + elif is_mlu_available(): + args.num_processes = torch.mlu.device_count() + elif is_sdaa_available(): + args.num_processes = torch.sdaa.device_count() + elif is_musa_available(): + args.num_processes = torch.musa.device_count() + elif is_npu_available(): + args.num_processes = torch.npu.device_count() + elif is_hpu_available(): + args.num_processes = torch.hpu.device_count() + else: + args.num_processes = torch.cuda.device_count() + warned.append(f"\t`--num_processes` was set to a value of `{args.num_processes}`") + if args.debug is None: + args.debug = False + if ( + not args.multi_gpu + and args.num_processes > 1 + and ( + (is_xpu_available() and torch.xpu.device_count() > 1) + or (is_npu_available() and torch.npu.device_count() > 1) + or (is_hpu_available() and torch.hpu.device_count() > 1) + or (is_mlu_available() and torch.mlu.device_count() > 1) + or (is_sdaa_available() and torch.sdaa.device_count() > 1) + or (is_musa_available() and torch.musa.device_count() > 1) + or (torch.cuda.is_available() and torch.cuda.device_count() > 1) + ) + ): + warned.append( + "\t\tMore than one GPU was found, enabling multi-GPU training.\n" + "\t\tIf this was unintended please pass in `--num_processes=1`." + ) + args.multi_gpu = True + if args.num_machines is None: + warned.append("\t`--num_machines` was set to a value of `1`") + args.num_machines = 1 + if args.mixed_precision is None: + warned.append("\t`--mixed_precision` was set to a value of `'no'`") + args.mixed_precision = "no" + if not hasattr(args, "use_cpu"): + args.use_cpu = args.cpu + if args.dynamo_backend is None: + warned.append("\t`--dynamo_backend` was set to a value of `'no'`") + args.dynamo_backend = "no" + if args.debug: + logger.debug("Running script in debug mode, expect distributed operations to be slightly slower.") + + is_aws_env_disabled = defaults is None or ( + defaults is not None and defaults.compute_environment != ComputeEnvironment.AMAZON_SAGEMAKER + ) + if is_aws_env_disabled and args.num_cpu_threads_per_process is None: + args.num_cpu_threads_per_process = get_int_from_env(["OMP_NUM_THREADS"], 1) + if args.use_cpu and args.num_processes >= 1 and get_int_from_env(["OMP_NUM_THREADS"], 0) == 0: + local_size = get_int_from_env( + ["MPI_LOCALNRANKS", "OMPI_COMM_WORLD_LOCAL_SIZE", "MV2_COMM_WORLD_LOCAL_SIZE"], + max(int(args.num_processes / args.num_machines), 1), + ) + threads_per_process = int(psutil.cpu_count(logical=False) / local_size) + if threads_per_process > 1: + args.num_cpu_threads_per_process = threads_per_process + warned.append( + f"\t`--num_cpu_threads_per_process` was set to `{args.num_cpu_threads_per_process}` to improve out-of-box performance when training on CPUs" + ) + + if args.ipex is not None: + logger.warning( + "ipex flag is deprecated, will be removed in Accelerate v1.10. " + "From 2.7.0, PyTorch has all needed optimizations for Intel CPU and XPU." + ) + + if args.use_xpu is not None: + logger.warning( + "use_xpu is deprecated and ignored, will be removed in Accelerate v1.20. " + "XPU is a PyTorch native citizen now, we don't need extra argument to enable it any more." + ) + + if any(warned): + message = "The following values were not passed to `accelerate launch` and had defaults used instead:\n" + message += "\n".join(warned) + message += ( + "\nTo avoid this warning pass in values for each of the problematic parameters or run `accelerate config`." + ) + logger.warning(message) + return args, defaults, mp_from_config_flag + + +def launch_command(args): + args, defaults, mp_from_config_flag = _validate_launch_command(args) + # Use the proper launcher + if args.use_deepspeed and not args.cpu: + args.deepspeed_fields_from_accelerate_config = list(defaults.deepspeed_config.keys()) if defaults else [] + if mp_from_config_flag: + args.deepspeed_fields_from_accelerate_config.append("mixed_precision") + args.deepspeed_fields_from_accelerate_config = ",".join(args.deepspeed_fields_from_accelerate_config) + deepspeed_launcher(args) + elif args.use_fsdp and not args.cpu: + multi_gpu_launcher(args) + elif args.use_megatron_lm and not args.cpu: + multi_gpu_launcher(args) + elif args.multi_gpu and not args.cpu: + multi_gpu_launcher(args) + elif args.tpu and not args.cpu: + if args.tpu_use_cluster: + tpu_pod_launcher(args) + else: + tpu_launcher(args) + elif defaults is not None and defaults.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: + sagemaker_launcher(defaults, args) + else: + simple_launcher(args) + + +def main(): + parser = launch_command_parser() + args = parser.parse_args() + launch_command(args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/__init__.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c2c851cc0b192ab8207d3fa68d7409868c84354c --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/__init__.py @@ -0,0 +1,14 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from .selection_menu import BulletMenu diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/cursor.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/cursor.py new file mode 100644 index 0000000000000000000000000000000000000000..c1f0bb7b68025ae4fe0c2c76c095eb36b4e64f2c --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/cursor.py @@ -0,0 +1,65 @@ +# Copyright 2022 The HuggingFace Team and Brian Chao. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +A utility for showing and hiding the terminal cursor on Windows and Linux, based on https://github.com/bchao1/bullet +""" + +import os +import sys +from contextlib import contextmanager + + +# Windows only +if os.name == "nt": + import ctypes + import msvcrt # noqa + + class CursorInfo(ctypes.Structure): + # _fields is a specific attr expected by ctypes + _fields_ = [("size", ctypes.c_int), ("visible", ctypes.c_byte)] + + +def hide_cursor(): + if os.name == "nt": + ci = CursorInfo() + handle = ctypes.windll.kernel32.GetStdHandle(-11) + ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci)) + ci.visible = False + ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci)) + elif os.name == "posix": + sys.stdout.write("\033[?25l") + sys.stdout.flush() + + +def show_cursor(): + if os.name == "nt": + ci = CursorInfo() + handle = ctypes.windll.kernel32.GetStdHandle(-11) + ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci)) + ci.visible = True + ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci)) + elif os.name == "posix": + sys.stdout.write("\033[?25h") + sys.stdout.flush() + + +@contextmanager +def hide(): + "Context manager to hide the terminal cursor" + try: + hide_cursor() + yield + finally: + show_cursor() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/helpers.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..de46f37ddcf4591167e3e01791391e4b1729034f --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/helpers.py @@ -0,0 +1,59 @@ +# Copyright 2022 The HuggingFace Team and Brian Chao. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +A variety of helper functions and constants when dealing with terminal menu choices, based on +https://github.com/bchao1/bullet +""" + +import enum +import shutil +import sys + + +TERMINAL_WIDTH, _ = shutil.get_terminal_size() + +CURSOR_TO_CHAR = {"UP": "A", "DOWN": "B", "RIGHT": "C", "LEFT": "D"} + + +class Direction(enum.Enum): + UP = 0 + DOWN = 1 + + +def forceWrite(content, end=""): + sys.stdout.write(str(content) + end) + sys.stdout.flush() + + +def writeColor(content, color, end=""): + forceWrite(f"\u001b[{color}m{content}\u001b[0m", end) + + +def reset_cursor(): + forceWrite("\r") + + +def move_cursor(num_lines: int, direction: str): + forceWrite(f"\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}") + + +def clear_line(): + forceWrite(" " * TERMINAL_WIDTH) + reset_cursor() + + +def linebreak(): + reset_cursor() + forceWrite("-" * TERMINAL_WIDTH) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/input.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/input.py new file mode 100644 index 0000000000000000000000000000000000000000..f1270eaece9d4243e7282dcb31166feeeb9bdfc1 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/input.py @@ -0,0 +1,84 @@ +# Copyright 2022 The HuggingFace Team and Brian Chao. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +This file contains utilities for handling input from the user and registering specific keys to specific functions, +based on https://github.com/bchao1/bullet +""" + +from .keymap import KEYMAP, get_character + + +def mark(key: str): + """ + Mark the function with the key code so it can be handled in the register + """ + + def decorator(func): + handle = getattr(func, "handle_key", []) + handle += [key] + func.handle_key = handle + return func + + return decorator + + +def mark_multiple(*keys: list[str]): + """ + Mark the function with the key codes so it can be handled in the register + """ + + def decorator(func): + handle = getattr(func, "handle_key", []) + handle += keys + func.handle_key = handle + return func + + return decorator + + +class KeyHandler(type): + """ + Metaclass that adds the key handlers to the class + """ + + def __new__(cls, name, bases, attrs): + new_cls = super().__new__(cls, name, bases, attrs) + if not hasattr(new_cls, "key_handler"): + new_cls.key_handler = {} + new_cls.handle_input = KeyHandler.handle_input + + for value in attrs.values(): + handled_keys = getattr(value, "handle_key", []) + for key in handled_keys: + new_cls.key_handler[key] = value + return new_cls + + @staticmethod + def handle_input(cls): + "Finds and returns the selected character if it exists in the handler" + char = get_character() + if char != KEYMAP["undefined"]: + char = ord(char) + handler = cls.key_handler.get(char) + if handler: + cls.current_selection = char + return handler(cls) + else: + return None + + +def register(cls): + """Adds KeyHandler metaclass to the class""" + return KeyHandler(cls.__name__, cls.__bases__, cls.__dict__.copy()) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/keymap.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/keymap.py new file mode 100644 index 0000000000000000000000000000000000000000..787db12860fe21c6786dda69c34fcccab114f2f8 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/keymap.py @@ -0,0 +1,133 @@ +# Copyright 2022 The HuggingFace Team and Brian Chao. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Utilities relating to parsing raw characters from the keyboard, based on https://github.com/bchao1/bullet +""" + +import os +import string +import sys + + +ARROW_KEY_FLAG = 1 << 8 + +KEYMAP = { + "tab": ord("\t"), + "newline": ord("\r"), + "esc": 27, + "up": 65 + ARROW_KEY_FLAG, + "down": 66 + ARROW_KEY_FLAG, + "right": 67 + ARROW_KEY_FLAG, + "left": 68 + ARROW_KEY_FLAG, + "mod_int": 91, + "undefined": sys.maxsize, + "interrupt": 3, + "insert": 50, + "delete": 51, + "pg_up": 53, + "pg_down": 54, +} + +KEYMAP["arrow_begin"] = KEYMAP["up"] +KEYMAP["arrow_end"] = KEYMAP["left"] + +if sys.platform == "win32": + WIN_CH_BUFFER = [] + WIN_KEYMAP = { + b"\xe0H": KEYMAP["up"] - ARROW_KEY_FLAG, + b"\x00H": KEYMAP["up"] - ARROW_KEY_FLAG, + b"\xe0P": KEYMAP["down"] - ARROW_KEY_FLAG, + b"\x00P": KEYMAP["down"] - ARROW_KEY_FLAG, + b"\xe0M": KEYMAP["right"] - ARROW_KEY_FLAG, + b"\x00M": KEYMAP["right"] - ARROW_KEY_FLAG, + b"\xe0K": KEYMAP["left"] - ARROW_KEY_FLAG, + b"\x00K": KEYMAP["left"] - ARROW_KEY_FLAG, + } + +for i in range(10): + KEYMAP[str(i)] = ord(str(i)) + + +def get_raw_chars(): + "Gets raw characters from inputs" + if os.name == "nt": + import msvcrt + + encoding = "mbcs" + # Flush the keyboard buffer + while msvcrt.kbhit(): + msvcrt.getch() + if len(WIN_CH_BUFFER) == 0: + # Read the keystroke + ch = msvcrt.getch() + + # If it is a prefix char, get second part + if ch in (b"\x00", b"\xe0"): + ch2 = ch + msvcrt.getch() + # Translate actual Win chars to bullet char types + try: + chx = chr(WIN_KEYMAP[ch2]) + WIN_CH_BUFFER.append(chr(KEYMAP["mod_int"])) + WIN_CH_BUFFER.append(chx) + if ord(chx) in ( + KEYMAP["insert"] - 1 << 9, + KEYMAP["delete"] - 1 << 9, + KEYMAP["pg_up"] - 1 << 9, + KEYMAP["pg_down"] - 1 << 9, + ): + WIN_CH_BUFFER.append(chr(126)) + ch = chr(KEYMAP["esc"]) + except KeyError: + ch = ch2[1] + else: + ch = ch.decode(encoding) + else: + ch = WIN_CH_BUFFER.pop(0) + elif os.name == "posix": + import termios + import tty + + fd = sys.stdin.fileno() + old_settings = termios.tcgetattr(fd) + try: + tty.setraw(fd) + ch = sys.stdin.read(1) + finally: + termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) + return ch + + +def get_character(): + "Gets a character from the keyboard and returns the key code" + char = get_raw_chars() + if ord(char) in [KEYMAP["interrupt"], KEYMAP["newline"]]: + return char + + elif ord(char) == KEYMAP["esc"]: + combo = get_raw_chars() + if ord(combo) == KEYMAP["mod_int"]: + key = get_raw_chars() + if ord(key) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(key) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG: + return chr(ord(key) + ARROW_KEY_FLAG) + else: + return KEYMAP["undefined"] + else: + return get_raw_chars() + + else: + if char in string.printable: + return char + else: + return KEYMAP["undefined"] diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/selection_menu.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/selection_menu.py new file mode 100644 index 0000000000000000000000000000000000000000..ee9a771a54ef666ee46b67ae6c75fb957d49efdd --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/selection_menu.py @@ -0,0 +1,144 @@ +# Copyright 2022 The HuggingFace Team and Brian Chao. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Main driver for the selection menu, based on https://github.com/bchao1/bullet +""" + +import builtins +import sys + +from ...utils.imports import _is_package_available +from . import cursor, input +from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor +from .keymap import KEYMAP + + +in_colab = False +try: + in_colab = _is_package_available("google.colab") +except ModuleNotFoundError: + pass + + +@input.register +class BulletMenu: + """ + A CLI menu to select a choice from a list of choices using the keyboard. + """ + + def __init__(self, prompt: str = None, choices: list = []): + self.position = 0 + self.choices = choices + self.prompt = prompt + if sys.platform == "win32": + self.arrow_char = "*" + else: + self.arrow_char = "➔ " + + def write_choice(self, index, end: str = ""): + if sys.platform != "win32": + writeColor(self.choices[index], 32, end) + else: + forceWrite(self.choices[index], end) + + def print_choice(self, index: int): + "Prints the choice at the given index" + if index == self.position: + forceWrite(f" {self.arrow_char} ") + self.write_choice(index) + else: + forceWrite(f" {self.choices[index]}") + reset_cursor() + + def move_direction(self, direction: Direction, num_spaces: int = 1): + "Should not be directly called, used to move a direction of either up or down" + old_position = self.position + if direction == Direction.DOWN: + if self.position + 1 >= len(self.choices): + return + self.position += num_spaces + else: + if self.position - 1 < 0: + return + self.position -= num_spaces + clear_line() + self.print_choice(old_position) + move_cursor(num_spaces, direction.name) + self.print_choice(self.position) + + @input.mark(KEYMAP["up"]) + def move_up(self): + self.move_direction(Direction.UP) + + @input.mark(KEYMAP["down"]) + def move_down(self): + self.move_direction(Direction.DOWN) + + @input.mark(KEYMAP["newline"]) + def select(self): + move_cursor(len(self.choices) - self.position, "DOWN") + return self.position + + @input.mark(KEYMAP["interrupt"]) + def interrupt(self): + move_cursor(len(self.choices) - self.position, "DOWN") + raise KeyboardInterrupt + + @input.mark_multiple(*[KEYMAP[str(number)] for number in range(10)]) + def select_row(self): + index = int(chr(self.current_selection)) + movement = index - self.position + if index == self.position: + return + if index < len(self.choices): + if self.position > index: + self.move_direction(Direction.UP, -movement) + elif self.position < index: + self.move_direction(Direction.DOWN, movement) + else: + return + else: + return + + def run(self, default_choice: int = 0): + "Start the menu and return the selected choice" + if self.prompt: + linebreak() + forceWrite(self.prompt, "\n") + if in_colab: + forceWrite("Please input a choice index (starting from 0), and press enter", "\n") + else: + forceWrite("Please select a choice using the arrow or number keys, and selecting with enter", "\n") + self.position = default_choice + for i in range(len(self.choices)): + self.print_choice(i) + forceWrite("\n") + move_cursor(len(self.choices) - self.position, "UP") + with cursor.hide(): + while True: + if in_colab: + try: + choice = int(builtins.input()) + except ValueError: + choice = default_choice + else: + choice = self.handle_input() + if choice is not None: + reset_cursor() + for _ in range(len(self.choices) + 1): + move_cursor(1, "UP") + clear_line() + self.write_choice(choice, "\n") + return choice diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/merge.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/merge.py new file mode 100644 index 0000000000000000000000000000000000000000..475b53b5bbb71b959057126f8667d7f61eb9d0e1 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/merge.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python + +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from accelerate.commands.utils import CustomArgumentParser +from accelerate.utils import merge_fsdp_weights + + +description = """Utility to merge the weights from multiple FSDP checkpoints into a single combined checkpoint. Should be used if +`SHARDED_STATE_DICT` was used for the model. Weights will be saved to `{output_path}`. + +This is a CPU-bound process and requires enough RAM to load the entire model state dict.""" + + +def merge_command(args): + merge_fsdp_weights( + args.checkpoint_directory, args.output_path, not args.unsafe_serialization, args.remove_checkpoint_dir + ) + + +def merge_command_parser(subparsers=None): + if subparsers is not None: + parser = subparsers.add_parser("merge-weights", description=description) + else: + parser = CustomArgumentParser(description=description) + + parser.add_argument("checkpoint_directory", type=str, help="A directory containing sharded weights saved by FSDP.") + parser.add_argument( + "output_path", + type=str, + help="The path to save the merged weights. Defaults to the current directory. ", + ) + parser.add_argument( + "--unsafe_serialization", + action="store_true", + default=False, + help="Whether to save the merged weights as `.bin` rather than `.safetensors` (not recommended).", + ) + parser.add_argument( + "--remove_checkpoint_dir", + action="store_true", + help="Whether to remove the checkpoint directory after merging.", + default=False, + ) + + if subparsers is not None: + parser.set_defaults(func=merge_command) + return parser + + +def main(): + parser = merge_command_parser() + args = parser.parse_args() + merge_command(args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/test.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/test.py new file mode 100644 index 0000000000000000000000000000000000000000..a0d2f7bcf14727aa13e3438f4cd6e6f140f5bb2f --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/test.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python + +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse + +from accelerate.test_utils import execute_subprocess_async, path_in_accelerate_package + + +def test_command_parser(subparsers=None): + if subparsers is not None: + parser = subparsers.add_parser("test") + else: + parser = argparse.ArgumentParser("Accelerate test command") + + parser.add_argument( + "--config_file", + default=None, + help=( + "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " + "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " + "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " + "with 'huggingface'." + ), + ) + + if subparsers is not None: + parser.set_defaults(func=test_command) + return parser + + +def test_command(args): + script_name = path_in_accelerate_package("test_utils", "scripts", "test_script.py") + + if args.config_file is None: + test_args = [script_name] + else: + test_args = f"--config_file={args.config_file} {script_name}".split() + + cmd = ["accelerate-launch"] + test_args + result = execute_subprocess_async(cmd) + if result.returncode == 0: + print("Test is a success! You are ready for your distributed training!") + + +def main(): + parser = test_command_parser() + args = parser.parse_args() + test_command(args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/to_fsdp2.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/to_fsdp2.py new file mode 100644 index 0000000000000000000000000000000000000000..443407cd983dcb31711b75c2a6337f9a7af24584 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/to_fsdp2.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python + +# Copyright 2025 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import enum +import logging +from pathlib import Path + +import yaml + +from accelerate.commands.utils import CustomArgumentParser + + +class ConversionStatus(enum.Enum): + NOT_YET_IMPLEMENTED = 0 + REMOVED = -1 + + +ARGUMENT_KEY_MAPPING = { + # New keys in FSDP2 + "fsdp_version": "fsdp_version", + "fsdp_reshard_after_forward": "fsdp_reshard_after_forward", + # https://github.com/pytorch/torchtitan/blob/main/docs/fsdp.md + # https://huggingface.co/docs/accelerate/en/usage_guides/fsdp + "fsdp_auto_wrap_policy": "fsdp_auto_wrap_policy", + "fsdp_backward_prefetch": ConversionStatus.REMOVED, + "fsdp_forward_prefetch": ConversionStatus.NOT_YET_IMPLEMENTED, + "fsdp_cpu_ram_efficient_loading": "fsdp_cpu_ram_efficient_loading", + "fsdp_offload_params": "fsdp_offload_params", + "fsdp_sharding_strategy": "fsdp_reshard_after_forward", + "fsdp_state_dict_type": "fsdp_state_dict_type", + "fsdp_sync_module_states": ConversionStatus.REMOVED, + "fsdp_transformer_layer_cls_to_wrap": "fsdp_transformer_layer_cls_to_wrap", + "fsdp_min_num_params": "fsdp_min_num_params", + "fsdp_use_orig_params": ConversionStatus.REMOVED, + "fsdp_activation_checkpointing": "fsdp_activation_checkpointing", +} + +ARGUMENT_VALUE_MAPPING = { + "fsdp_sharding_strategy": { + "FULL_SHARD": True, + "SHARD_GRAD_OP": False, + "HYBRID_SHARD": True, + "HYBRID_SHARD_ZERO2": False, + "NO_SHARD": False, + }, + "fsdp_reshard_after_forward": { # Needed to convert newly created configs using FSDP1 to FSDP2 + "FULL_SHARD": True, + "SHARD_GRAD_OP": False, + "HYBRID_SHARD": True, + "HYBRID_SHARD_ZERO2": False, + "NO_SHARD": False, + }, +} + +logger = logging.getLogger(__name__) + + +def _validate_to_fsdp2_args(args): + if not Path(args.config_file).exists(): + raise FileNotFoundError(f"Config file {args.config_file} not found") + + if not args.overwrite and args.output_file is None: + raise ValueError("If --overwrite is not set, --output_file must be provided") + + if not args.overwrite and Path(args.output_file).exists(): + raise FileExistsError(f"Output file {args.output_file} already exists and --overwrite is not set") + + +def convert_config_to_fsdp2(config: dict) -> dict: + fsdp_config = config.get("fsdp_config", {}) + + if not fsdp_config: + logger.info("No FSDP config found in the config file, skipping conversion...") + return config + + new_fsdp_config = {} + + if fsdp_config.get("fsdp_version", 1) == 2: + logger.warning("Config already specfies FSDP2, skipping conversion...") + logger.warning( + "If the config doesn't use new argument names, change `fsdp_version` to `1` and rerun the command." + ) + return config + + for key, value in fsdp_config.items(): + conversion_status = ARGUMENT_KEY_MAPPING.get(key, None) + if isinstance(conversion_status, ConversionStatus) or conversion_status is None: + conversion_status = key + new_fsdp_config[conversion_status] = value + continue + + if conversion_status == ConversionStatus.REMOVED: + logger.warning(f"Argument {key} has been removed in FSDP2, skipping this key...") + continue + + if conversion_status == ConversionStatus.NOT_YET_IMPLEMENTED: + logger.warning(f"Argument {key} is not yet implemented in FSDP2, skipping this key...") + continue + + if conversion_status is None: + logger.warning(f"Argument {key} is not being converted, skipping this key...") + new_fsdp_config[key] = value + else: + if key in ARGUMENT_VALUE_MAPPING: + value = ARGUMENT_VALUE_MAPPING[key].get(value, value) + new_fsdp_config[ARGUMENT_KEY_MAPPING[key]] = value + + new_fsdp_config["fsdp_version"] = 2 + config["fsdp_config"] = new_fsdp_config + return config + + +def to_fsdp2_command_parser(subparsers=None): + description = "Convert an Accelerate config from FSDP1 to FSDP2" + + if subparsers is not None: + parser = subparsers.add_parser("to-fsdp2", description=description) + else: + parser = CustomArgumentParser(description=description) + + parser.add_argument("--config_file", type=str, help="The config file to convert to FSDP2", required=True) + parser.add_argument( + "--overwrite", + action="store_true", + help="Overwrite the config file if it exists", + default=False, + ) + parser.add_argument( + "--output_file", + type=str, + help="The path to the output file to write the converted config to. If not provided, the input file will be overwritten (if --overwrite is set)", + default=None, + ) + if subparsers is not None: + parser.set_defaults(func=to_fsdp2_command) + + return parser + + +def load_config(config_file: str) -> dict: + with open(config_file) as f: + config = yaml.safe_load(f) + if not config: + raise ValueError("Config file is empty") + + return config + + +def to_fsdp2_command(args): + _validate_to_fsdp2_args(args) + config = load_config(args.config_file) + + if args.overwrite and args.output_file is None: + args.output_file = args.config_file + + new_config = convert_config_to_fsdp2(config) + + with open(args.output_file, "w") as f: + yaml.dump(new_config, f) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/tpu.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/tpu.py new file mode 100644 index 0000000000000000000000000000000000000000..fc0f07bf8697bfdb6484d3bf817f2e18b1313b00 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/tpu.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python + +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import os +import subprocess + +from packaging.version import Version, parse + +from accelerate.commands.config.config_args import default_config_file, load_config_from_file + + +_description = "Run commands across TPU VMs for initial setup before running `accelerate launch`." + + +def tpu_command_parser(subparsers=None): + if subparsers is not None: + parser = subparsers.add_parser("tpu-config", description=_description) + else: + parser = argparse.ArgumentParser("Accelerate tpu-config command", description=_description) + # Core arguments + config_args = parser.add_argument_group( + "Config Arguments", "Arguments that can be configured through `accelerate config`." + ) + config_args.add_argument( + "--config_file", + type=str, + default=None, + help="Path to the config file to use for accelerate.", + ) + config_args.add_argument( + "--tpu_name", + default=None, + help="The name of the TPU to use. If not specified, will use the TPU specified in the config file.", + ) + config_args.add_argument( + "--tpu_zone", + default=None, + help="The zone of the TPU to use. If not specified, will use the zone specified in the config file.", + ) + pod_args = parser.add_argument_group("TPU Arguments", "Arguments for options ran inside the TPU.") + pod_args.add_argument( + "--use_alpha", + action="store_true", + help="Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.", + ) + pod_args.add_argument( + "--command_file", + default=None, + help="The path to the file containing the commands to run on the pod on startup.", + ) + pod_args.add_argument( + "--command", + action="append", + nargs="+", + help="A command to run on the pod. Can be passed multiple times.", + ) + pod_args.add_argument( + "--install_accelerate", + action="store_true", + help="Whether to install accelerate on the pod. Defaults to False.", + ) + pod_args.add_argument( + "--accelerate_version", + default="latest", + help="The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify 'dev' to install from GitHub.", + ) + pod_args.add_argument( + "--debug", action="store_true", help="If set, will print the command that would be run instead of running it." + ) + + if subparsers is not None: + parser.set_defaults(func=tpu_command_launcher) + return parser + + +def tpu_command_launcher(args): + defaults = None + + # Get the default from the config file if it exists. + if args.config_file is not None or os.path.isfile(default_config_file): + defaults = load_config_from_file(args.config_file) + if not args.command_file and defaults.command_file is not None and not args.command: + args.command_file = defaults.command_file + if not args.command and defaults.commands is not None: + args.command = defaults.commands + if not args.tpu_name: + args.tpu_name = defaults.tpu_name + if not args.tpu_zone: + args.tpu_zone = defaults.tpu_zone + if args.accelerate_version == "dev": + args.accelerate_version = "git+https://github.com/huggingface/accelerate.git" + elif args.accelerate_version == "latest": + args.accelerate_version = "accelerate -U" + elif isinstance(parse(args.accelerate_version), Version): + args.accelerate_version = f"accelerate=={args.accelerate_version}" + + if not args.command_file and not args.command: + raise ValueError("You must specify either a command file or a command to run on the pod.") + + if args.command_file: + with open(args.command_file) as f: + args.command = [f.read().splitlines()] + + # To turn list of lists into list of strings + if isinstance(args.command[0], list): + args.command = [line for cmd in args.command for line in cmd] + # Default to the shared folder and install accelerate + new_cmd = ["cd /usr/share"] + if args.install_accelerate: + new_cmd += [f"pip install {args.accelerate_version}"] + new_cmd += args.command + args.command = "; ".join(new_cmd) + + # Then send it to gcloud + # Eventually try to use google-api-core to do this instead of subprocess + cmd = ["gcloud"] + if args.use_alpha: + cmd += ["alpha"] + cmd += [ + "compute", + "tpus", + "tpu-vm", + "ssh", + args.tpu_name, + "--zone", + args.tpu_zone, + "--command", + args.command, + "--worker", + "all", + ] + if args.debug: + print(f"Running {' '.join(cmd)}") + return + subprocess.run(cmd) + print("Successfully setup pod.") + + +def main(): + parser = tpu_command_parser() + args = parser.parse_args() + + tpu_command_launcher(args) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/utils.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..326f37d7f93de2417e4171e5ffe91193fb97225c --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/utils.py @@ -0,0 +1,123 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse + + +class _StoreAction(argparse.Action): + """ + Custom action that allows for `-` or `_` to be passed in for an argument. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + new_option_strings = [] + for option_string in self.option_strings: + new_option_strings.append(option_string) + if "_" in option_string[2:]: + # Add `-` version to the option string + new_option_strings.append(option_string.replace("_", "-")) + self.option_strings = new_option_strings + + def __call__(self, parser, namespace, values, option_string=None): + setattr(namespace, self.dest, values) + if not hasattr(namespace, "nondefault"): + namespace.nondefault = set() + namespace.nondefault.add(self.dest) + + +class _StoreConstAction(_StoreAction): + """ + Same as `argparse._StoreConstAction` but uses the custom `_StoreAction`. + """ + + def __init__(self, option_strings, dest, const, default=None, required=False, help=None): + super().__init__( + option_strings=option_strings, + dest=dest, + nargs=0, + const=const, + default=default, + required=required, + help=help, + ) + + def __call__(self, parser, namespace, values, option_string=None): + super().__call__(parser, namespace, self.const, option_string) + + +class _StoreTrueAction(_StoreConstAction): + """ + Same as `argparse._StoreTrueAction` but uses the custom `_StoreConstAction`. + """ + + def __init__( + self, + option_strings, + dest, + default=None, + required=False, + help=None, + ): + super().__init__( + option_strings=option_strings, dest=dest, const=True, default=default, required=required, help=help + ) + + +class CustomArgumentGroup(argparse._ArgumentGroup): + """ + Custom argument group that allows for the use of `-` or `_` in arguments passed and overrides the help for each + when applicable. + """ + + def _add_action(self, action): + args = vars(action) + if isinstance(action, argparse._StoreTrueAction): + action = _StoreTrueAction( + args["option_strings"], args["dest"], args["default"], args["required"], args["help"] + ) + elif isinstance(action, argparse._StoreConstAction): + action = _StoreConstAction( + args["option_strings"], + args["dest"], + args["const"], + args["default"], + args["required"], + args["help"], + ) + elif isinstance(action, argparse._StoreAction): + action = _StoreAction(**args) + action = super()._add_action(action) + return action + + +class CustomArgumentParser(argparse.ArgumentParser): + """ + Custom argument parser that allows for the use of `-` or `_` in arguments passed and overrides the help for each + when applicable. + """ + + def add_argument(self, *args, **kwargs): + if "action" in kwargs: + # Translate action -> class + if kwargs["action"] == "store_true": + kwargs["action"] = _StoreTrueAction + else: + kwargs["action"] = _StoreAction + super().add_argument(*args, **kwargs) + + def add_argument_group(self, *args, **kwargs): + group = CustomArgumentGroup(self, *args, **kwargs) + self._action_groups.append(group) + return group diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/data_loader.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/data_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..3bb538908ddd10406396c8352dfffb051bca81ac --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/data_loader.py @@ -0,0 +1,1451 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import importlib +import math +from contextlib import suppress +from typing import Callable, Optional, Union + +import torch +from packaging import version +from torch.utils.data import BatchSampler, DataLoader, IterableDataset, RandomSampler + +from .logging import get_logger +from .state import DistributedType, GradientState, PartialState, is_torch_xla_available +from .utils import ( + RNGType, + broadcast, + broadcast_object_list, + compare_versions, + concatenate, + find_batch_size, + get_data_structure, + initialize_tensors, + is_datasets_available, + is_torch_version, + is_torchdata_stateful_dataloader_available, + send_to_device, + slice_tensors, + synchronize_rng_states, +) + + +logger = get_logger(__name__) + +# kwargs of the DataLoader in min version 2.0 +_PYTORCH_DATALOADER_KWARGS = { + "batch_size": 1, + "shuffle": False, + "sampler": None, + "batch_sampler": None, + "num_workers": 0, + "collate_fn": None, + "pin_memory": False, + "drop_last": False, + "timeout": 0, + "worker_init_fn": None, + "multiprocessing_context": None, + "generator": None, + "prefetch_factor": 2, + "persistent_workers": False, + "pin_memory_device": "", +} + +# kwargs added after by version +_PYTORCH_DATALOADER_ADDITIONAL_KWARGS = {"2.6.0": {"in_order": True}} + +for v, additional_kwargs in _PYTORCH_DATALOADER_ADDITIONAL_KWARGS.items(): + if is_torch_version(">=", v): + _PYTORCH_DATALOADER_KWARGS.update(additional_kwargs) + + +class SeedableRandomSampler(RandomSampler): + """ + Same as a random sampler, except that in `__iter__` a seed can be used. + + Needed specifically in distributed cases, when the random generator for each GPU needs to start from the same seed + and be fully reproducable on multiple iterations. + + If a custom `generator` is passed, it will rely on its initial seed as well as the current iteration it is on + (stored in `self.epoch`). + """ + + def __init__(self, *args, **kwargs): + data_seed = kwargs.pop("data_seed", None) + super().__init__(*args, **kwargs) + + self.initial_seed = data_seed if data_seed is not None else torch.random.initial_seed() + self.epoch = 0 + + def __iter__(self): + if self.generator is None: + self.generator = torch.Generator( + device=torch.get_default_device() if hasattr(torch, "get_default_device") else "cpu" + ) + self.generator.manual_seed(self.initial_seed) + + # Allow `self.epoch` to modify the seed of the generator + seed = self.epoch + self.initial_seed + # print("Setting seed at epoch", self.epoch, seed) + self.generator.manual_seed(seed) + yield from super().__iter__() + self.set_epoch(self.epoch + 1) + + def set_epoch(self, epoch: int): + "Sets the current iteration of the sampler." + self.epoch = epoch + + +class BatchSamplerShard(BatchSampler): + """ + Wraps a PyTorch `BatchSampler` to generate batches for one of the processes only. Instances of this class will + always yield a number of batches that is a round multiple of `num_processes` and that all have the same size. + Depending on the value of the `drop_last` attribute of the batch sampler passed, it will either stop the iteration + at the first batch that would be too small / not present on all processes or loop with indices from the beginning. + + Args: + batch_sampler (`torch.utils.data.sampler.BatchSampler`): + The batch sampler to split in several shards. + num_processes (`int`, *optional*, defaults to 1): + The number of processes running concurrently. + process_index (`int`, *optional*, defaults to 0): + The index of the current process. + split_batches (`bool`, *optional*, defaults to `False`): + Whether the shards should be created by splitting a batch to give a piece of it on each process, or by + yielding different full batches on each process. + + On two processes with a sampler of `[[0, 1, 2, 3], [4, 5, 6, 7]]`, this will result in: + + - the sampler on process 0 to yield `[0, 1, 2, 3]` and the sampler on process 1 to yield `[4, 5, 6, 7]` if + this argument is set to `False`. + - the sampler on process 0 to yield `[0, 1]` then `[4, 5]` and the sampler on process 1 to yield `[2, 3]` + then `[6, 7]` if this argument is set to `True`. + even_batches (`bool`, *optional*, defaults to `True`): + Whether or not to loop back at the beginning of the sampler when the number of samples is not a round + multiple of (original batch size / number of processes). + + + + `BatchSampler`s with varying batch sizes are not enabled by default. To enable this behaviour, set `even_batches` + equal to `False` + + """ + + def __init__( + self, + batch_sampler: BatchSampler, + num_processes: int = 1, + process_index: int = 0, + split_batches: bool = False, + even_batches: bool = True, + ): + if split_batches and batch_sampler.batch_size % num_processes != 0: + raise ValueError( + f"To use `BatchSamplerShard` in `split_batches` mode, the batch size ({batch_sampler.batch_size}) " + f"needs to be a round multiple of the number of processes ({num_processes})." + ) + self.batch_sampler = batch_sampler + self.num_processes = num_processes + self.process_index = process_index + self.split_batches = split_batches + self.even_batches = even_batches + self.batch_size = getattr(batch_sampler, "batch_size", None) + self.drop_last = getattr(batch_sampler, "drop_last", False) + if self.batch_size is None and self.even_batches: + raise ValueError( + "You need to use `even_batches=False` when the batch sampler has no batch size. If you " + "are not calling this method directly, set `accelerator.even_batches=False` instead." + ) + + @property + def total_length(self): + return len(self.batch_sampler) + + def __len__(self): + if self.split_batches: + # Split batches does not change the length of the batch sampler + return len(self.batch_sampler) + if len(self.batch_sampler) % self.num_processes == 0: + # If the length is a round multiple of the number of processes, it's easy. + return len(self.batch_sampler) // self.num_processes + length = len(self.batch_sampler) // self.num_processes + if self.drop_last: + # Same if we drop the remainder. + return length + elif self.even_batches: + # When we even batches we always get +1 + return length + 1 + else: + # Otherwise it depends on the process index. + return length + 1 if self.process_index < len(self.batch_sampler) % self.num_processes else length + + def __iter__(self): + return self._iter_with_split() if self.split_batches else self._iter_with_no_split() + + def _iter_with_split(self): + initial_data = [] + batch_length = self.batch_sampler.batch_size // self.num_processes + for idx, batch in enumerate(self.batch_sampler): + if idx == 0: + initial_data = batch + if len(batch) == self.batch_size: + # If the batch is full, we yield the part of it this process is responsible of. + yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)] + + # If drop_last is True of the last batch was full, iteration is over, otherwise... + if not self.drop_last and len(initial_data) > 0 and len(batch) < self.batch_size: + if not self.even_batches: + if len(batch) > batch_length * self.process_index: + yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)] + else: + # For degenerate cases where the dataset has less than num_process * batch_size samples + while len(initial_data) < self.batch_size: + initial_data += initial_data + batch = batch + initial_data + yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)] + + def _iter_with_no_split(self): + initial_data = [] + batch_to_yield = [] + for idx, batch in enumerate(self.batch_sampler): + # We gather the initial indices in case we need to circle back at the end. + if not self.drop_last and idx < self.num_processes: + initial_data += batch + # We identify the batch to yield but wait until we ar sure every process gets a full batch before actually + # yielding it. + if idx % self.num_processes == self.process_index: + batch_to_yield = batch + if idx % self.num_processes == self.num_processes - 1 and ( + self.batch_size is None or len(batch) == self.batch_size + ): + yield batch_to_yield + batch_to_yield = [] + + # If drop_last is True, iteration is over, otherwise... + if not self.drop_last and len(initial_data) > 0: + if not self.even_batches: + if len(batch_to_yield) > 0: + yield batch_to_yield + else: + # ... we yield the complete batch we had saved before if it has the proper length + if len(batch_to_yield) == self.batch_size: + yield batch_to_yield + + # For degenerate cases where the dataset has less than num_process * batch_size samples + while len(initial_data) < self.num_processes * self.batch_size: + initial_data += initial_data + + # If the last batch seen was of the proper size, it has been yielded by its process so we move to the next + if len(batch) == self.batch_size: + batch = [] + idx += 1 + + # Make sure we yield a multiple of self.num_processes batches + cycle_index = 0 + while idx % self.num_processes != 0 or len(batch) > 0: + end_index = cycle_index + self.batch_size - len(batch) + batch += initial_data[cycle_index:end_index] + if idx % self.num_processes == self.process_index: + yield batch + cycle_index = end_index + batch = [] + idx += 1 + + +class IterableDatasetShard(IterableDataset): + """ + Wraps a PyTorch `IterableDataset` to generate samples for one of the processes only. Instances of this class will + always yield a number of samples that is a round multiple of the actual batch size (depending of the value of + `split_batches`, this is either `batch_size` or `batch_size x num_processes`). Depending on the value of the + `drop_last` attribute of the batch sampler passed, it will either stop the iteration at the first batch that would + be too small or loop with indices from the beginning. + + Args: + dataset (`torch.utils.data.dataset.IterableDataset`): + The batch sampler to split in several shards. + batch_size (`int`, *optional*, defaults to 1): + The size of the batches per shard (if `split_batches=False`) or the size of the batches (if + `split_batches=True`). + drop_last (`bool`, *optional*, defaults to `False`): + Whether or not to drop the last incomplete batch or complete the last batches by using the samples from the + beginning. + num_processes (`int`, *optional*, defaults to 1): + The number of processes running concurrently. + process_index (`int`, *optional*, defaults to 0): + The index of the current process. + split_batches (`bool`, *optional*, defaults to `False`): + Whether the shards should be created by splitting a batch to give a piece of it on each process, or by + yielding different full batches on each process. + + On two processes with an iterable dataset yielding of `[0, 1, 2, 3, 4, 5, 6, 7]`, this will result in: + + - the shard on process 0 to yield `[0, 1, 2, 3]` and the shard on process 1 to yield `[4, 5, 6, 7]` if this + argument is set to `False`. + - the shard on process 0 to yield `[0, 1, 4, 5]` and the sampler on process 1 to yield `[2, 3, 6, 7]` if + this argument is set to `True`. + """ + + def __init__( + self, + dataset: IterableDataset, + batch_size: int = 1, + drop_last: bool = False, + num_processes: int = 1, + process_index: int = 0, + split_batches: bool = False, + ): + if split_batches and batch_size > 1 and batch_size % num_processes != 0: + raise ValueError( + f"To use `IterableDatasetShard` in `split_batches` mode, the batch size ({batch_size}) " + f"needs to be a round multiple of the number of processes ({num_processes})." + ) + self.dataset = dataset + self.batch_size = batch_size + self.drop_last = drop_last + self.num_processes = num_processes + self.process_index = process_index + self.split_batches = split_batches + + def set_epoch(self, epoch): + self.epoch = epoch + if hasattr(self.dataset, "set_epoch"): + self.dataset.set_epoch(epoch) + + def __len__(self): + # We will just raise the downstream error if the underlying dataset is not sized + if self.drop_last: + return (len(self.dataset) // (self.batch_size * self.num_processes)) * self.batch_size + else: + return math.ceil(len(self.dataset) / (self.batch_size * self.num_processes)) * self.batch_size + + def __iter__(self): + if ( + not hasattr(self.dataset, "set_epoch") + and hasattr(self.dataset, "generator") + and isinstance(self.dataset.generator, torch.Generator) + ): + self.dataset.generator.manual_seed(self.epoch) + real_batch_size = self.batch_size if self.split_batches else (self.batch_size * self.num_processes) + process_batch_size = (self.batch_size // self.num_processes) if self.split_batches else self.batch_size + process_slice = range(self.process_index * process_batch_size, (self.process_index + 1) * process_batch_size) + + first_batch = None + current_batch = [] + for element in self.dataset: + current_batch.append(element) + # Wait to have a full batch before yielding elements. + if len(current_batch) == real_batch_size: + for i in process_slice: + yield current_batch[i] + if first_batch is None: + first_batch = current_batch.copy() + current_batch = [] + + # Finished if drop_last is True, otherwise complete the last batch with elements from the beginning. + if not self.drop_last and len(current_batch) > 0: + if first_batch is None: + first_batch = current_batch.copy() + while len(current_batch) < real_batch_size: + current_batch += first_batch + for i in process_slice: + yield current_batch[i] + + +class DataLoaderStateMixin: + """ + Mixin class that adds a state to a `DataLoader` to keep track of the status inside the dataloader such as at the + end of the iteration, the number of items in the dataset in the last batch relative to the batch size, and other + useful information that might be needed. + + **Available attributes:** + + - **end_of_dataloader** (`bool`) -- Whether at the last iteration or batch + - **remainder** (`int`) -- The number of items that are remaining in the last batch, relative to the total + batch size + + + + Inheriters of this class should ensure that the class creates a `GradientState()` instance, stored in + `self.gradient_state`. + + + + """ + + def __init_subclass__(cls, **kwargs): + cls.end_of_dataloader = False + cls.remainder = -1 + + def reset(self): + self.end_of_dataloader = False + self.remainder = -1 + + def begin(self): + "Prepares the gradient state for the current dataloader" + self.reset() + with suppress(Exception): + if not self._drop_last: + length = getattr(self.dataset, "total_dataset_length", len(self.dataset)) + self.remainder = length % self.total_batch_size + self.gradient_state._add_dataloader(self) + + def end(self): + "Cleans up the gradient state after exiting the dataloader" + self.gradient_state._remove_dataloader(self) + + +class DataLoaderAdapter: + """ + A class which wraps around a PyTorch `DataLoader` (or variants of it) to be used with the `Accelerator`. For + compatability reasons, this class inherits from the class it wraps around, so it can be used as a drop-in. + """ + + def __init__(self, dataset, use_stateful_dataloader=False, batch_sampler=None, **kwargs): + self.use_stateful_dataloader = use_stateful_dataloader + if is_torchdata_stateful_dataloader_available(): + from torchdata.stateful_dataloader import StatefulDataLoader + + if use_stateful_dataloader and not is_torchdata_stateful_dataloader_available(): + raise ImportError( + "StatefulDataLoader is not available. Please install torchdata version 0.8.0 or higher to use it." + ) + if use_stateful_dataloader: + torchdata_version = version.parse(importlib.metadata.version("torchdata")) + if ( + "in_order" in kwargs + and compare_versions(torchdata_version, "<", "0.11") + and is_torch_version(">=", "2.6.0") + ): + kwargs.pop("in_order") + self.base_dataloader = StatefulDataLoader(dataset, batch_sampler=batch_sampler, **kwargs) + else: + self.base_dataloader = DataLoader(dataset, batch_sampler=batch_sampler, **kwargs) + + if hasattr(self.base_dataloader, "state_dict"): + self.dl_state_dict = self.base_dataloader.state_dict() + + def __getattr__(self, name): + # Avoid infinite recursion if we try to access a nonexistent base_dataloader attribute. + if name == "base_dataloader": + raise AttributeError() + # Delegate attribute access to the internal dataloader + return getattr(self.base_dataloader, name) + + def state_dict(self): + return self.dl_state_dict + + def load_state_dict(self, state_dict): + self.base_dataloader.load_state_dict(state_dict) + + @property + def __class__(self): + """ + In order to maintain backwards compatability with other code, we need to ensure `isinstance(obj, DataLoader)` + returs true. This is because some downstream code assumes that the `DataLoader` is the base class of the + object. + """ + return self.base_dataloader.__class__ + + def __len__(self): + return len(self.base_dataloader) + + def adjust_state_dict_for_prefetch(self): + """ + Adjusts the state dict for prefetching. Natively, this will adjust all of the iters yielded keys in + `self.dl_state_dict` by a factor of `num_processes - 1`, however if a custom correction is needed, this can be + overridden. + + This should modify `self.dl_state_dict` directly + """ + # The state dict will be off by a factor of `n-1` batch too many during DDP, + # so we need to adjust it here + if PartialState().distributed_type != DistributedType.NO: + factor = PartialState().num_processes - 1 + if self.dl_state_dict["_sampler_iter_yielded"] > 0: + self.dl_state_dict["_sampler_iter_yielded"] -= factor + if self.dl_state_dict["_num_yielded"] > 0: + self.dl_state_dict["_num_yielded"] -= factor + if self.dl_state_dict["_index_sampler_state"] is not None: + if ( + "samples_yielded" in self.dl_state_dict["_index_sampler_state"] + and self.dl_state_dict["_index_sampler_state"]["samples_yielded"] > 0 + ): + self.dl_state_dict["_index_sampler_state"]["samples_yielded"] -= self.batch_size * factor + + def _update_state_dict(self): + # The state_dict of the underlying base_dataloader may be ahead of what is currently being yielded. + # E.g. the implementation of DataLoaderShard involves having an underlying iterator 1 element ahead of + # what it wants to yield. + # + # _update_state_dict is called to snapshot the state_dict that would properly recover the DataLoaderAdapter. + if hasattr(self.base_dataloader, "state_dict"): + self.dl_state_dict = self.base_dataloader.state_dict() + # Potentially modify the state_dict to adjust for prefetching + self.adjust_state_dict_for_prefetch() + # Then tag if we are at the end of the dataloader + self.dl_state_dict["_iterator_finished"] = self.end_of_dataloader + + +class DataLoaderShard(DataLoaderAdapter, DataLoaderStateMixin): + """ + Subclass of `DataLoaderAdapter` that will deal with device placement and current distributed setup. + + Args: + dataset (`torch.utils.data.dataset.Dataset`): + The dataset to use to build this dataloader. + device (`torch.device`, *optional*): + If passed, the device to put all batches on. + rng_types (list of `str` or [`~utils.RNGType`]): + The list of random number generators to synchronize at the beginning of each iteration. Should be one or + several of: + + - `"torch"`: the base torch random number generator + - `"cuda"`: the CUDA random number generator (GPU only) + - `"xla"`: the XLA random number generator (TPU only) + - `"generator"`: an optional `torch.Generator` + synchronized_generator (`torch.Generator`, *optional*): + A random number generator to keep synchronized across processes. + skip_batches (`int`, *optional*, defaults to 0): + The number of batches to skip at the beginning. + use_stateful_dataloader (`bool`, *optional*, defaults to `False`): + Whether to have this class adapt `StatefulDataLoader` from `torchdata` instead of the regular `DataLoader`. + **kwargs (additional keyword arguments, *optional*): + All other keyword arguments to pass to the regular `DataLoader` initialization. + + **Available attributes:** + + - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes. + Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total + number of processes + + - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes. + """ + + def __init__( + self, + dataset, + device=None, + rng_types=None, + synchronized_generator=None, + skip_batches=0, + use_stateful_dataloader=False, + _drop_last: bool = False, + _non_blocking: bool = False, + torch_device_mesh=None, + **kwargs, + ): + super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs) + self.device = device + self.rng_types = rng_types + self.synchronized_generator = synchronized_generator + self.skip_batches = skip_batches + self.gradient_state = GradientState() + self._drop_last = _drop_last + self._non_blocking = _non_blocking + self.iteration = 0 + + def __iter__(self): + if self.rng_types is not None: + synchronize_rng_states(self.rng_types, self.synchronized_generator) + self.begin() + + self.set_epoch(self.iteration) + dataloader_iter = self.base_dataloader.__iter__() + # We iterate one batch ahead to check when we are at the end + try: + current_batch = next(dataloader_iter) + except StopIteration: + self.end() + return + + batch_index = 0 + while True: + try: + # But we still move it to the device so it is done before `StopIteration` is reached + if self.device is not None: + current_batch = send_to_device(current_batch, self.device, non_blocking=self._non_blocking) + self._update_state_dict() + next_batch = next(dataloader_iter) + if batch_index >= self.skip_batches: + yield current_batch + batch_index += 1 + current_batch = next_batch + except StopIteration: + self.end_of_dataloader = True + self._update_state_dict() + if batch_index >= self.skip_batches: + yield current_batch + break + + self.iteration += 1 + self.end() + + def __reduce__(self): + """ + Define the `__reduce__` method to ensure a `DataLoaderShard` can be pickled and unpickled. This needs to be + explicitly defined since default pickling behavior is broken by `DataLoaderAdapter` messing with its + `__class__` member. + """ + args = super().__reduce__() + return (DataLoaderShard, *args[1:]) + + def set_epoch(self, epoch: int): + # In case it is manually passed in, the user can set it to what they like + if self.iteration != epoch: + self.iteration = epoch + if hasattr(self.batch_sampler, "set_epoch"): + self.batch_sampler.set_epoch(epoch) + if hasattr(self.batch_sampler, "sampler") and hasattr(self.batch_sampler.sampler, "set_epoch"): + self.batch_sampler.sampler.set_epoch(epoch) + if ( + hasattr(self.batch_sampler, "batch_sampler") + and hasattr(self.batch_sampler.batch_sampler, "sampler") + and hasattr(self.batch_sampler.batch_sampler.sampler, "set_epoch") + ): + self.batch_sampler.batch_sampler.sampler.set_epoch(epoch) + # We support if a custom `Dataset` implementation has `set_epoch` + # or in general HF datasets `Datasets` + elif hasattr(self.dataset, "set_epoch"): + self.dataset.set_epoch(epoch) + + @property + def total_batch_size(self): + batch_sampler = self.sampler if isinstance(self.sampler, BatchSampler) else self.batch_sampler + return ( + batch_sampler.batch_size + if getattr(batch_sampler, "split_batches", False) + else (batch_sampler.batch_size * getattr(batch_sampler, "num_processes", 1)) + ) + + @property + def total_dataset_length(self): + if hasattr(self.dataset, "total_length"): + return self.dataset.total_length + else: + return len(self.dataset) + + def get_sampler(self): + return get_sampler(self) + + def set_sampler(self, sampler): + sampler_is_batch_sampler = isinstance(self.sampler, BatchSampler) + if sampler_is_batch_sampler: + self.sampler.sampler = sampler + else: + self.batch_sampler.sampler = sampler + if hasattr(self.batch_sampler, "batch_sampler"): + self.batch_sampler.batch_sampler.sampler = sampler + + +if is_torch_xla_available(): + import torch_xla.distributed.parallel_loader as xpl + + class MpDeviceLoaderWrapper(xpl.MpDeviceLoader): + """ + Wrapper for the xpl.MpDeviceLoader class that knows the total batch size. + + XLA preloading threads will all call DataLoaderShard's __iter__(). Remove rng_types from DataLoaderShard to + prevent it from using the XLA device in the preloading threads, and synchronize the RNG once from the main + thread only. + + **Available attributes:** + + - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes. + Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total + number of processes + + - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes. + """ + + def __init__(self, dataloader: DataLoaderShard, device: torch.device): + super().__init__(dataloader, device) + self._rng_types = self._loader.rng_types + self._loader.rng_types = None + self.device = device + + def __iter__(self): + if self._rng_types is not None: + synchronize_rng_states(self._rng_types, self._loader.synchronized_generator) + + return super().__iter__() + + def set_epoch(self, epoch: int): + if hasattr(self.dataloader, "set_epoch"): + self.dataloader.set_epoch(epoch) + + @property + def total_batch_size(self): + return self._loader.total_batch_size + + @property + def total_dataset_length(self): + return self._loader.total_dataset_length + + @property + def batch_sampler(self): + return self._loader.batch_sampler + + @property + def dataloader(self): + return self._loader + + +class DataLoaderDispatcher(DataLoaderAdapter, DataLoaderStateMixin): + """ + Subclass of `DataLoaderAdapter` that will iterate and preprocess on process 0 only, then dispatch on each process + their part of the batch. + + Args: + split_batches (`bool`, *optional*, defaults to `False`): + Whether the resulting `DataLoader` should split the batches of the original data loader across devices or + yield full batches (in which case it will yield batches starting at the `process_index`-th and advancing of + `num_processes` batches at each iteration). Another way to see this is that the observed batch size will be + the same as the initial `dataloader` if this option is set to `True`, the batch size of the initial + `dataloader` multiplied by `num_processes` otherwise. Setting this option to `True` requires that the batch + size of the `dataloader` is a round multiple of `batch_size`. + skip_batches (`int`, *optional*, defaults to 0): + The number of batches to skip at the beginning of an iteration. + use_stateful_dataloader (`bool`, *optional*, defaults to `False`): + Whether to have this class adapt `StatefulDataLoader` from `torchdata` instead of the regular `DataLoader`. + + **Available attributes:** + + - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes. + Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total + number of processes + + - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes. + """ + + def __init__( + self, + dataset, + split_batches: bool = False, + skip_batches=0, + use_stateful_dataloader=False, + _drop_last: bool = False, + _non_blocking: bool = False, + slice_fn=None, + torch_device_mesh=None, + **kwargs, + ): + shuffle = False + from torch.utils.data.datapipes.iter.combinatorics import ShufflerIterDataPipe + + # We need to save the shuffling state of the DataPipe + if isinstance(dataset, ShufflerIterDataPipe): + shuffle = dataset._shuffle_enabled + super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs) + self.split_batches = split_batches + if shuffle: + torch.utils.data.graph_settings.apply_shuffle_settings(dataset, shuffle=shuffle) + + self.gradient_state = GradientState() + self.state = PartialState() + self._drop_last = _drop_last + self._non_blocking = _non_blocking + self.skip_batches = skip_batches + self.torch_device_mesh = torch_device_mesh + + self.slice_fn = slice_tensors if slice_fn is None else slice_fn + self.iteration = 0 + + # if a device mesh is provided extract each dimension (dp, fsdp, tp) + # device mesh may hold any number of dimensions, however, + # below code is for targetted support for dp, fsdp and tp + + # device mesh will be used only if there is tp involved + # or any multi-dimensional parallelism involving tp + # (dp, tp) (fsdp, tp) (dp, fsdp, tp) + # otherwise the default behavour not using device mesh should be sufficient + # since multi dimensional parallelism devoid of tp would anyway need + # different batches for each process irrespective of dp or fsdp + self.submesh_tp = None + self.submesh_dp = None + self.submesh_fsdp = None + if self.torch_device_mesh and "tp" in self.torch_device_mesh.mesh_dim_names: + self.submesh_tp = self.torch_device_mesh["tp"] + if "dp" in self.torch_device_mesh.mesh_dim_names: + self.submesh_dp = self.torch_device_mesh["dp"] + if "fsdp" in self.torch_device_mesh.mesh_dim_names: + self.submesh_fsdp = self.torch_device_mesh["fsdp"] + if self.submesh_tp and (self.submesh_dp or self.submesh_fsdp): + raise ValueError("TP + (DP/FSDP) is not yet supported in dispatch mode") + + def _fetch_batches(self, iterator): + batches, batch = None, None + # On process 0, we gather the batch to dispatch. + if self.state.process_index == 0: + # Procedure to support TP only is simpler + # since we want to dispatch the same batch of samples across all ranks + # this removes complexity of handling multiple tp rank groups when TP + DP + # combination is involved. + + try: + # for TP case avoid using split_batches + # since it would mean that the dataloader should be spilling out + # duplicates of batches. + if self.split_batches: + # One batch of the main iterator is dispatched and split. + if self.submesh_tp: + logger.warning( + "Use of split_batches for TP would need the dataloader to produce duplicate batches," + "otherwise, use dispatch_batches=True instead." + ) + self._update_state_dict() + batch = next(iterator) + else: + # num_processes batches of the main iterator are concatenated then dispatched and split. + # We add the batches one by one so we have the remainder available when drop_last=False. + batches = [] + if self.submesh_tp: + # when tp, extract single batch and then replicate + self._update_state_dict() + batch = next(iterator) + batches = [batch] * self.state.num_processes + else: + for _ in range(self.state.num_processes): + self._update_state_dict() + batches.append(next(iterator)) + try: + batch = concatenate(batches, dim=0) + except RuntimeError as e: + raise RuntimeError( + "You can't use batches of different size with `dispatch_batches=True` or when using an `IterableDataset`." + "either pass `dispatch_batches=False` and have each process fetch its own batch " + " or pass `split_batches=True`. By doing so, the main process will fetch a full batch and " + "slice it into `num_processes` batches for each process." + ) from e + # In both cases, we need to get the structure of the batch that we will broadcast on other + # processes to initialize the tensors with the right shape. + # data_structure, stop_iteration + batch_info = [get_data_structure(batch), False] + except StopIteration: + batch_info = [None, True] + else: + batch_info = [None, self._stop_iteration] + # This is inplace, so after this instruction, every process has the same `batch_info` as process 0. + broadcast_object_list(batch_info) + self._stop_iteration = batch_info[1] + if self._stop_iteration: + # If drop_last is False and split_batches is False, we may have a remainder to take care of. + if not self.split_batches and not self._drop_last: + if self.state.process_index == 0 and len(batches) > 0: + batch = concatenate(batches, dim=0) + batch_info = [get_data_structure(batch), False] + else: + batch_info = [None, True] + broadcast_object_list(batch_info) + return batch, batch_info + + def __iter__(self): + self.begin() + self.set_epoch(self.iteration) + main_iterator = None + if is_torch_version(">=", "2.0.1"): + # NOTE PyTorch DataLoader adds forward compatibilities for DataPipes, which broadcasts + # shared seed to all dist processes. Thus, we need to create iterator for all dist processes. + # But, we only iterate through the DataLoader on process 0. + main_iterator = self.base_dataloader.__iter__() + elif self.state.process_index == 0: + main_iterator = self.base_dataloader.__iter__() + stop_iteration = False + self._stop_iteration = False + first_batch = None + next_batch, next_batch_info = self._fetch_batches(main_iterator) + batch_index = 0 + while not stop_iteration: + batch, batch_info = next_batch, next_batch_info + + if self.state.process_index != 0: + # Initialize tensors on other processes than process 0. + batch = initialize_tensors(batch_info[0]) + batch = send_to_device(batch, self.state.device, non_blocking=self._non_blocking) + # Broadcast the batch before splitting it. + batch = broadcast(batch, from_process=0) + + if not self._drop_last and first_batch is None: + # We keep at least num processes elements of the first batch to be able to complete the last batch + first_batch = self.slice_fn( + batch, + slice(0, self.state.num_processes), + process_index=self.state.process_index, + num_processes=self.state.num_processes, + ) + + if batch is None: + raise ValueError( + f"Batch does not contain any data (`{batch}`). At the end of all iterable data available before expected stop iteration." + ) + + observed_batch_size = find_batch_size(batch) + batch_size = observed_batch_size // self.state.num_processes + + stop_iteration = self._stop_iteration + if not stop_iteration: + # We may still be at the end of the dataloader without knowing it yet: if there is nothing left in + # the dataloader since the number of batches is a round multiple of the number of processes. + next_batch, next_batch_info = self._fetch_batches(main_iterator) + # next_batch_info[0] is None when there are no more batches, otherwise we still need to process them. + if self._stop_iteration and next_batch_info[0] is None: + stop_iteration = True + + if not self._drop_last and stop_iteration and observed_batch_size % self.state.num_processes != 0: + # If the last batch is not complete, let's add the first batch to it. + batch = concatenate([batch, first_batch], dim=0) + # Batch size computation above is wrong, it's off by 1 so we fix it. + batch_size += 1 + + data_slice = slice(self.state.process_index * batch_size, (self.state.process_index + 1) * batch_size) + batch = self.slice_fn( + batch, + data_slice, + process_index=self.state.process_index, + num_processes=self.state.num_processes, + ) + + if stop_iteration: + self.end_of_dataloader = True + self._update_state_dict() + self.remainder = observed_batch_size + if batch_index >= self.skip_batches: + yield batch + batch_index += 1 + self.iteration += 1 + self.end() + + def set_epoch(self, epoch: int): + # In case it is manually passed in, the user can set it to what they like + if self.iteration != epoch: + self.iteration = epoch + if hasattr(self.batch_sampler, "sampler") and hasattr(self.batch_sampler.sampler, "set_epoch"): + self.batch_sampler.sampler.set_epoch(epoch) + elif hasattr(self.dataset, "set_epoch"): + self.dataset.set_epoch(epoch) + + def __len__(self): + whole_length = len(self.base_dataloader) + if self.split_batches: + return whole_length + elif self._drop_last: + return whole_length // self.state.num_processes + else: + return math.ceil(whole_length / self.state.num_processes) + + def __reduce__(self): + """ + Define the `__reduce__` method to ensure a `DataLoaderDispatcher` can be pickled and unpickled. This needs to + be explicitly defined since default pickling behavior is broken by `DataLoaderAdapter` messing with its + `__class__` member. + """ + args = super().__reduce__() + return (DataLoaderDispatcher, *args[1:]) + + @property + def total_batch_size(self): + return ( + self.dataset.batch_size if self.split_batches else (self.dataset.batch_size * self.dataset.num_processes) + ) + + @property + def total_dataset_length(self): + return len(self.dataset) + + def get_sampler(self): + return get_sampler(self) + + def set_sampler(self, sampler): + sampler_is_batch_sampler = isinstance(self.sampler, BatchSampler) + if sampler_is_batch_sampler: + self.sampler.sampler = sampler + else: + self.batch_sampler.sampler = sampler + if hasattr(self.batch_sampler, "batch_sampler"): + self.batch_sampler.batch_sampler.sampler = sampler + + +def get_sampler(dataloader): + """ + Get the sampler associated to the dataloader + + Args: + dataloader (`torch.utils.data.dataloader.DataLoader`): + The data loader to split across several devices. + Returns: + `torch.utils.data.Sampler`: The sampler associated to the dataloader + """ + sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler) + if sampler_is_batch_sampler: + sampler = getattr(dataloader.sampler, "sampler", None) + else: + sampler = getattr(dataloader.batch_sampler, "sampler", None) + return sampler + + +def prepare_data_loader( + dataloader: DataLoader, + device: Optional[torch.device] = None, + num_processes: Optional[int] = None, + process_index: Optional[int] = None, + split_batches: bool = False, + put_on_device: bool = False, + rng_types: Optional[list[Union[str, RNGType]]] = None, + dispatch_batches: Optional[bool] = None, + even_batches: bool = True, + slice_fn_for_dispatch: Optional[Callable] = None, + use_seedable_sampler: bool = False, + data_seed: Optional[int] = None, + non_blocking: bool = False, + use_stateful_dataloader: bool = False, + torch_device_mesh=None, +) -> DataLoader: + """ + Wraps a PyTorch `DataLoader` to generate batches for one of the processes only. + + Depending on the value of the `drop_last` attribute of the `dataloader` passed, it will either stop the iteration + at the first batch that would be too small / not present on all processes or loop with indices from the beginning. + + Args: + dataloader (`torch.utils.data.dataloader.DataLoader`): + The data loader to split across several devices. + device (`torch.device`): + The target device for the returned `DataLoader`. + num_processes (`int`, *optional*): + The number of processes running concurrently. Will default to the value given by [`~state.PartialState`]. + process_index (`int`, *optional*): + The index of the current process. Will default to the value given by [`~state.PartialState`]. + split_batches (`bool`, *optional*, defaults to `False`): + Whether the resulting `DataLoader` should split the batches of the original data loader across devices or + yield full batches (in which case it will yield batches starting at the `process_index`-th and advancing of + `num_processes` batches at each iteration). + + Another way to see this is that the observed batch size will be the same as the initial `dataloader` if + this option is set to `True`, the batch size of the initial `dataloader` multiplied by `num_processes` + otherwise. + + Setting this option to `True` requires that the batch size of the `dataloader` is a round multiple of + `batch_size`. + put_on_device (`bool`, *optional*, defaults to `False`): + Whether or not to put the batches on `device` (only works if the batches are nested list, tuples or + dictionaries of tensors). + rng_types (list of `str` or [`~utils.RNGType`]): + The list of random number generators to synchronize at the beginning of each iteration. Should be one or + several of: + + - `"torch"`: the base torch random number generator + - `"cuda"`: the CUDA random number generator (GPU only) + - `"xla"`: the XLA random number generator (TPU only) + - `"generator"`: the `torch.Generator` of the sampler (or batch sampler if there is no sampler in your + dataloader) or of the iterable dataset (if it exists) if the underlying dataset is of that type. + + dispatch_batches (`bool`, *optional*): + If set to `True`, the dataloader prepared is only iterated through on the main process and then the batches + are split and broadcast to each process. Will default to `True` when the underlying dataset is an + `IterableDataset`, `False` otherwise. + even_batches (`bool`, *optional*, defaults to `True`): + If set to `True`, in cases where the total batch size across all processes does not exactly divide the + dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among + all workers. + slice_fn_for_dispatch (`Callable`, *optional*`): + If passed, this function will be used to slice tensors across `num_processes`. Will default to + [`~utils.slice_tensors`]. This argument is used only when `dispatch_batches` is set to `True` and will be + ignored otherwise. + use_seedable_sampler (`bool`, *optional*, defaults to `False`): + Whether to use the [`~data_loader.SeedableRandomSampler`] instead of a `RandomSampler` for better + reproducability. Comes at a cost of potentially different performances due to different shuffling + algorithms but ensures results will be the *exact* same. Should be paired with `set_seed()` at every + `self.set_epoch` + data_seed (`int`, *optional*, defaults to `None`): + The seed to use for the underlying generator when using `use_seedable_sampler`. If `None`, the generator + will use the current default seed from torch. + non_blocking (`bool`, *optional*, defaults to `False`): + If set to `True`, dataloader will utilize non-blocking host-to-device transfers. If the dataloader has + `pin_memory` set to `True`, this will help to increase overlap between data transfer and computations. + use_stateful_dataloader (`bool`, *optional*, defaults to `False`): + "If set to true, the dataloader prepared by the Accelerator will be backed by " + "[torchdata.StatefulDataLoader](https://github.com/pytorch/data/tree/main/torchdata/stateful_dataloader). + This requires `torchdata` version 0.8.0 or higher that supports StatefulDataLoader to be installed." + torch_device_mesh (`torch.distributed.DeviceMesh`, *optional*, defaults to `None`): + PyTorch device mesh. + + + Returns: + `torch.utils.data.dataloader.DataLoader`: A new data loader that will yield the portion of the batches + + + + `BatchSampler`s with varying batch sizes are not enabled by default. To enable this behaviour, set `even_batches` + equal to `False` + + + """ + if dispatch_batches is None: + if not put_on_device: + dispatch_batches = False + else: + dispatch_batches = isinstance(dataloader.dataset, IterableDataset) + + if dispatch_batches and not put_on_device: + raise ValueError("Using `dispatch_batches=True` requires `put_on_device=True`.") + # Grab defaults from PartialState + state = PartialState() + if num_processes is None: + num_processes = state.num_processes + + if process_index is None: + process_index = state.process_index + + if torch_device_mesh: + if state.distributed_type == DistributedType.DEEPSPEED: + # In DeepSpeed, the optimizer sharing level in DP is determined by the config file. + # Only considers "dp" and "tp". + # Given a device mesh (dp, tp) = (2, 3): + # - From the data parallel perspective, ranks should be structured as: 0 0 0 1 1 1 + # - Processes with the same DP rank will receive the same batch. + submesh_tp_size = 1 + if "tp" in torch_device_mesh.mesh_dim_names: + submesh_tp_size = torch_device_mesh["tp"].size() + process_index = process_index // submesh_tp_size + num_processes = num_processes // submesh_tp_size + else: + # when device mesh is used, specifically with TP + # then there is need to update process_index and num_processes + # to bring in the effect of generating same batch across TP ranks + # and different batch across FSDP and DP ranks. + # Example: + # if device mesh is (dp,fsdp,tp) = (2, 2, 3) + # ranks would range from 0...11 + # from data angle ranks should look like 0 0 0 1 1 1 2 2 2 3 3 3 + # processes with same ranks/ids would receive the same batch + # for CP the same as TP applies + submesh_fsdp_size = 1 + submesh_dp_size = 1 + submesh_tp_size = 1 + submesh_cp_size = 1 + if "tp" in torch_device_mesh.mesh_dim_names: + submesh_tp_size = torch_device_mesh["tp"].size() + if "cp" in torch_device_mesh.mesh_dim_names: + submesh_cp_size = torch_device_mesh["cp"].size() + if "dp_replicate" in torch_device_mesh.mesh_dim_names: + submesh_dp_size = torch_device_mesh["dp_replicate"].size() + if "dp_shard" in torch_device_mesh.mesh_dim_names: + submesh_fsdp_size = torch_device_mesh["dp_shard"].size() + process_index = process_index // (submesh_tp_size * submesh_cp_size) + num_processes = submesh_fsdp_size * submesh_dp_size + + # Sanity check + if split_batches: + if dataloader.batch_size is not None: + batch_size_for_check = dataloader.batch_size + else: + # For custom batch_sampler + if hasattr(dataloader.batch_sampler, "batch_size"): + batch_size_for_check = dataloader.batch_sampler.batch_size + else: + raise ValueError( + "In order to use `split_batches==True` you must have a `batch_size` attribute either in the passed " + "`dataloader` or `dataloader.batch_sampler` objects, and it has to return a natural number. " + "Your `dataloader.batch_size` is None and `dataloader.batch_sampler` " + f"(`{type(dataloader.batch_sampler)}`) does not have the `batch_size` attribute set." + ) + + if batch_size_for_check > 1 and batch_size_for_check % num_processes != 0: + raise ValueError( + f"To use a `DataLoader` in `split_batches` mode, the batch size ({dataloader.batch_size}) " + f"needs to be a round multiple of the number of processes ({num_processes})." + ) + + new_dataset = dataloader.dataset + # Iterable dataset doesn't like batch_sampler, but data_loader creates a default one for it + new_batch_sampler = dataloader.batch_sampler if not isinstance(new_dataset, IterableDataset) else None + sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler) + synchronized_generator = None + + sampler = get_sampler(dataloader) + if isinstance(sampler, RandomSampler) and use_seedable_sampler: + # When iterating through the dataloader during distributed processes + # we want to ensure that on each process we are iterating through the same + # samples in the same order if a seed is set. This requires a tweak + # to the `torch.utils.data.RandomSampler` class (if used). + sampler = SeedableRandomSampler( + data_source=sampler.data_source, + replacement=sampler.replacement, + num_samples=sampler._num_samples, + generator=getattr( + sampler, + "generator", + torch.Generator(device=torch.get_default_device() if hasattr(torch, "get_default_device") else "cpu"), + ), + data_seed=data_seed, + ) + + if isinstance(dataloader.sampler, RandomSampler) and state.distributed_type == DistributedType.XLA: + # isinstance(dataloader.sampler, RandomSampler) indicates the original dataloader has `shuffle` enabled. + generator = torch.Generator( + device=torch.get_default_device() if hasattr(torch, "get_default_device") else "cpu" + ) + seed = int(torch.empty((), dtype=torch.int64).random_().item()) + generator.manual_seed(seed) + dataloader.generator = generator + dataloader.sampler.generator = generator + # No change if no multiprocess + if (num_processes != 1 or state.distributed_type == DistributedType.MEGATRON_LM) and not dispatch_batches: + if is_datasets_available(): + from datasets import IterableDataset as DatasetsIterableDataset + if ( + is_datasets_available() + and isinstance(new_dataset, DatasetsIterableDataset) + and not split_batches + and new_dataset.n_shards > num_processes + ): + new_dataset = new_dataset.shard(num_shards=num_processes, index=process_index) + elif isinstance(new_dataset, IterableDataset): + if getattr(dataloader.dataset, "generator", None) is not None: + synchronized_generator = dataloader.dataset.generator + new_dataset = IterableDatasetShard( + new_dataset, + batch_size=dataloader.batch_size, + drop_last=dataloader.drop_last, + num_processes=num_processes, + process_index=process_index, + split_batches=split_batches, + ) + else: + if not use_seedable_sampler and hasattr(sampler, "generator"): + if sampler.generator is None: + sampler.generator = torch.Generator( + device=torch.get_default_device() if hasattr(torch, "get_default_device") else "cpu" + ) + seed = int(torch.empty((), dtype=torch.int64).random_().item()) + sampler.generator.manual_seed(seed) + synchronized_generator = sampler.generator + batch_sampler = dataloader.sampler if sampler_is_batch_sampler else dataloader.batch_sampler + new_batch_sampler = BatchSamplerShard( + batch_sampler, + num_processes=num_processes, + process_index=process_index, + split_batches=split_batches, + even_batches=even_batches, + ) + + # We ignore all of those since they are all dealt with by our new_batch_sampler + ignore_kwargs = [ + "batch_size", + "shuffle", + "sampler", + "batch_sampler", + "drop_last", + ] + + if rng_types is not None and synchronized_generator is None and "generator" in rng_types: + rng_types.remove("generator") + + kwargs = { + k: getattr(dataloader, k, _PYTORCH_DATALOADER_KWARGS[k]) + for k in _PYTORCH_DATALOADER_KWARGS + if k not in ignore_kwargs + } + + # Need to provide batch_size as batch_sampler is None for Iterable dataset + if new_batch_sampler is None: + kwargs["drop_last"] = dataloader.drop_last + kwargs["batch_size"] = ( + dataloader.batch_size // num_processes if split_batches and not dispatch_batches else dataloader.batch_size + ) + if dispatch_batches: + kwargs.pop("generator") + dataloader = DataLoaderDispatcher( + new_dataset, + split_batches=split_batches, + batch_sampler=new_batch_sampler, + _drop_last=dataloader.drop_last, + _non_blocking=non_blocking, + slice_fn=slice_fn_for_dispatch, + use_stateful_dataloader=use_stateful_dataloader, + torch_device_mesh=torch_device_mesh, + **kwargs, + ) + elif sampler_is_batch_sampler: + dataloader = DataLoaderShard( + new_dataset, + device=device if put_on_device and state.distributed_type != DistributedType.XLA else None, + sampler=new_batch_sampler, + batch_size=dataloader.batch_size, + rng_types=rng_types, + _drop_last=dataloader.drop_last, + _non_blocking=non_blocking, + synchronized_generator=synchronized_generator, + use_stateful_dataloader=use_stateful_dataloader, + **kwargs, + ) + else: + dataloader = DataLoaderShard( + new_dataset, + device=device if put_on_device and state.distributed_type != DistributedType.XLA else None, + batch_sampler=new_batch_sampler, + rng_types=rng_types, + synchronized_generator=synchronized_generator, + _drop_last=dataloader.drop_last, + _non_blocking=non_blocking, + use_stateful_dataloader=use_stateful_dataloader, + **kwargs, + ) + + if isinstance(sampler, SeedableRandomSampler) and use_seedable_sampler: + dataloader.set_sampler(sampler) + if state.distributed_type == DistributedType.XLA: + return MpDeviceLoaderWrapper(dataloader, device) + return dataloader + + +class SkipBatchSampler(BatchSampler): + """ + A `torch.utils.data.BatchSampler` that skips the first `n` batches of another `torch.utils.data.BatchSampler`. + Should not be used if the original dataloader is a `StatefulDataLoader`. + """ + + def __init__(self, batch_sampler, skip_batches=0): + self.batch_sampler = batch_sampler + self.skip_batches = skip_batches + + def __iter__(self): + for index, samples in enumerate(self.batch_sampler): + if index >= self.skip_batches: + yield samples + + @property + def total_length(self): + return len(self.batch_sampler) + + def __len__(self): + return len(self.batch_sampler) - self.skip_batches + + +class SkipDataLoader(DataLoaderAdapter, DataLoaderStateMixin): + """ + Subclass of a PyTorch `DataLoader` that will skip the first batches. Generally it's preferable to use + `skip_first_batches`/`torchdata.StatefulDataLoader` instead of this class. + + Args: + dataset (`torch.utils.data.dataset.Dataset`): + The dataset to use to build this dataloader. + skip_batches (`int`, *optional*, defaults to 0): + The number of batches to skip at the beginning. + kwargs: + All other keyword arguments to pass to the regular `DataLoader` initialization. + """ + + def __init__(self, dataset, skip_batches=0, use_stateful_dataloader=False, **kwargs): + super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs) + self.skip_batches = skip_batches + self.gradient_state = GradientState() + + def __iter__(self): + self.begin() + for index, batch in enumerate(self.base_dataloader.__iter__()): + if index >= self.skip_batches: + self._update_state_dict() + yield batch + self.end() + + def __len__(self): + return len(self.base_dataloader) - self.skip_batches + + def __reduce__(self): + """ + Define the `__reduce__` method to ensure a `SkipDataLoader` can be pickled and unpickled. This needs to be + explicitly defined since default pickling behavior is broken by `DataLoaderAdapter` messing with its + `__class__` member. + """ + args = super().__reduce__() + return (SkipDataLoader, *args[1:]) + + +def skip_first_batches(dataloader, num_batches=0): + """ + Creates a `torch.utils.data.DataLoader` that will efficiently skip the first `num_batches`. Should not be used if + the original dataloader is a `StatefulDataLoader`. + """ + state = PartialState() + if state.distributed_type == DistributedType.XLA: + device = dataloader.device + dataloader = dataloader.dataloader + + dataset = dataloader.dataset + sampler_is_batch_sampler = False + if isinstance(dataset, IterableDataset): + new_batch_sampler = None + else: + sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler) + batch_sampler = dataloader.sampler if sampler_is_batch_sampler else dataloader.batch_sampler + new_batch_sampler = SkipBatchSampler(batch_sampler, skip_batches=num_batches) + + # We ignore all of those since they are all dealt with by our new_batch_sampler + ignore_kwargs = [ + "batch_size", + "shuffle", + "sampler", + "batch_sampler", + "drop_last", + ] + + kwargs = { + k: getattr(dataloader, k, _PYTORCH_DATALOADER_KWARGS[k]) + for k in _PYTORCH_DATALOADER_KWARGS + if k not in ignore_kwargs + } + + # Need to provide batch_size as batch_sampler is None for Iterable dataset + if new_batch_sampler is None: + kwargs["drop_last"] = dataloader.drop_last + kwargs["batch_size"] = dataloader.batch_size + + if isinstance(dataloader, DataLoaderDispatcher): + if new_batch_sampler is None: + # Need to manually skip batches in the dataloader + kwargs["skip_batches"] = num_batches + dataloader = DataLoaderDispatcher( + dataset, + split_batches=dataloader.split_batches, + batch_sampler=new_batch_sampler, + _drop_last=dataloader._drop_last, + **kwargs, + ) + elif isinstance(dataloader, DataLoaderShard): + if new_batch_sampler is None: + # Need to manually skip batches in the dataloader + kwargs["skip_batches"] = num_batches + elif sampler_is_batch_sampler: + kwargs["sampler"] = new_batch_sampler + kwargs["batch_size"] = dataloader.batch_size + else: + kwargs["batch_sampler"] = new_batch_sampler + dataloader = DataLoaderShard( + dataset, + device=dataloader.device, + rng_types=dataloader.rng_types, + synchronized_generator=dataloader.synchronized_generator, + **kwargs, + ) + else: + if new_batch_sampler is None: + # Need to manually skip batches in the dataloader + dataloader = SkipDataLoader(dataset, skip_batches=num_batches, **kwargs) + else: + dataloader = DataLoader(dataset, batch_sampler=new_batch_sampler, **kwargs) + + if state.distributed_type == DistributedType.XLA: + dataloader = MpDeviceLoaderWrapper(dataloader, device) + + return dataloader diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/hooks.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..55b6f2efb8b7f24ec38a4da37f61992fd20519de --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/hooks.py @@ -0,0 +1,765 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import functools +from collections.abc import Mapping +from typing import Optional, Union + +import torch +import torch.nn as nn + +from .state import PartialState +from .utils import ( + PrefixedDataset, + find_device, + named_module_tensors, + send_to_device, + set_module_tensor_to_device, +) +from .utils.imports import ( + is_mlu_available, + is_musa_available, + is_npu_available, +) +from .utils.memory import clear_device_cache +from .utils.modeling import get_non_persistent_buffers +from .utils.other import recursive_getattr + + +_accelerate_added_attributes = ["to", "cuda", "npu", "xpu", "mlu", "sdaa", "musa"] + + +class ModelHook: + """ + A hook that contains callbacks to be executed just before and after the forward method of a model. The difference + with PyTorch existing hooks is that they get passed along the kwargs. + + Class attribute: + - **no_grad** (`bool`, *optional*, defaults to `False`) -- Whether or not to execute the actual forward pass under + the `torch.no_grad()` context manager. + """ + + no_grad = False + + def init_hook(self, module): + """ + To be executed when the hook is attached to the module. + + Args: + module (`torch.nn.Module`): The module attached to this hook. + """ + return module + + def pre_forward(self, module, *args, **kwargs): + """ + To be executed just before the forward method of the model. + + Args: + module (`torch.nn.Module`): The module whose forward pass will be executed just after this event. + args (`Tuple[Any]`): The positional arguments passed to the module. + kwargs (`Dict[Str, Any]`): The keyword arguments passed to the module. + + Returns: + `Tuple[Tuple[Any], Dict[Str, Any]]`: A tuple with the treated `args` and `kwargs`. + """ + return args, kwargs + + def post_forward(self, module, output): + """ + To be executed just after the forward method of the model. + + Args: + module (`torch.nn.Module`): The module whose forward pass been executed just before this event. + output (`Any`): The output of the module. + + Returns: + `Any`: The processed `output`. + """ + return output + + def detach_hook(self, module): + """ + To be executed when the hook is detached from a module. + + Args: + module (`torch.nn.Module`): The module detached from this hook. + """ + return module + + +class SequentialHook(ModelHook): + """ + A hook that can contain several hooks and iterates through them at each event. + """ + + def __init__(self, *hooks): + self.hooks = hooks + + def init_hook(self, module): + for hook in self.hooks: + module = hook.init_hook(module) + return module + + def pre_forward(self, module, *args, **kwargs): + for hook in self.hooks: + args, kwargs = hook.pre_forward(module, *args, **kwargs) + return args, kwargs + + def post_forward(self, module, output): + for hook in self.hooks: + output = hook.post_forward(module, output) + return output + + def detach_hook(self, module): + for hook in self.hooks: + module = hook.detach_hook(module) + return module + + +def add_hook_to_module(module: nn.Module, hook: ModelHook, append: bool = False): + """ + Adds a hook to a given module. This will rewrite the `forward` method of the module to include the hook, to remove + this behavior and restore the original `forward` method, use `remove_hook_from_module`. + + + + If the module already contains a hook, this will replace it with the new hook passed by default. To chain two hooks + together, pass `append=True`, so it chains the current and new hook into an instance of the `SequentialHook` class. + + + + Args: + module (`torch.nn.Module`): + The module to attach a hook to. + hook (`ModelHook`): + The hook to attach. + append (`bool`, *optional*, defaults to `False`): + Whether the hook should be chained with an existing one (if module already contains a hook) or not. + + Returns: + `torch.nn.Module`: The same module, with the hook attached (the module is modified in place, so the result can + be discarded). + """ + if append and (getattr(module, "_hf_hook", None) is not None): + old_hook = module._hf_hook + remove_hook_from_module(module) + hook = SequentialHook(old_hook, hook) + + if hasattr(module, "_hf_hook") and hasattr(module, "_old_forward"): + # If we already put some hook on this module, we replace it with the new one. + old_forward = module._old_forward + else: + old_forward = module.forward + module._old_forward = old_forward + + module = hook.init_hook(module) + module._hf_hook = hook + + def new_forward(module, *args, **kwargs): + args, kwargs = module._hf_hook.pre_forward(module, *args, **kwargs) + if module._hf_hook.no_grad: + with torch.no_grad(): + output = module._old_forward(*args, **kwargs) + else: + output = module._old_forward(*args, **kwargs) + return module._hf_hook.post_forward(module, output) + + # Overriding a GraphModuleImpl forward freezes the forward call and later modifications on the graph will fail. + # Reference: https://pytorch.slack.com/archives/C3PDTEV8E/p1705929610405409 + if "GraphModuleImpl" in str(type(module)): + module.__class__.forward = functools.update_wrapper(functools.partial(new_forward, module), old_forward) + else: + module.forward = functools.update_wrapper(functools.partial(new_forward, module), old_forward) + + return module + + +def remove_hook_from_module(module: nn.Module, recurse=False): + """ + Removes any hook attached to a module via `add_hook_to_module`. + + Args: + module (`torch.nn.Module`): The module to attach a hook to. + recurse (`bool`, **optional**): Whether to remove the hooks recursively + + Returns: + `torch.nn.Module`: The same module, with the hook detached (the module is modified in place, so the result can + be discarded). + """ + + if hasattr(module, "_hf_hook"): + module._hf_hook.detach_hook(module) + delattr(module, "_hf_hook") + + if hasattr(module, "_old_forward"): + # Overriding a GraphModuleImpl forward freezes the forward call and later modifications on the graph will fail. + # Reference: https://pytorch.slack.com/archives/C3PDTEV8E/p1705929610405409 + if "GraphModuleImpl" in str(type(module)): + module.__class__.forward = module._old_forward + else: + module.forward = module._old_forward + delattr(module, "_old_forward") + + # Remove accelerate added warning hooks from dispatch_model + for attr in _accelerate_added_attributes: + module.__dict__.pop(attr, None) + + if recurse: + for child in module.children(): + remove_hook_from_module(child, recurse) + + return module + + +class AlignDevicesHook(ModelHook): + """ + A generic `ModelHook` that ensures inputs and model weights are on the same device for the forward pass of the + associated module, potentially offloading the weights after the forward pass. + + Args: + execution_device (`torch.device`, *optional*): + The device on which inputs and model weights should be placed before the forward pass. + offload (`bool`, *optional*, defaults to `False`): + Whether or not the weights should be offloaded after the forward pass. + io_same_device (`bool`, *optional*, defaults to `False`): + Whether or not the output should be placed on the same device as the input was. + weights_map (`Mapping[str, torch.Tensor]`, *optional*): + When the model weights are offloaded, a (potentially lazy) map from param names to the tensor values. + offload_buffers (`bool`, *optional*, defaults to `False`): + Whether or not to include the associated module's buffers when offloading. + place_submodules (`bool`, *optional*, defaults to `False`): + Whether to place the submodules on `execution_device` during the `init_hook` event. + """ + + def __init__( + self, + execution_device: Optional[Union[int, str, torch.device]] = None, + offload: bool = False, + io_same_device: bool = False, + weights_map: Optional[Mapping] = None, + offload_buffers: bool = False, + place_submodules: bool = False, + skip_keys: Optional[Union[str, list[str]]] = None, + tied_params_map: Optional[dict[int, dict[torch.device, torch.Tensor]]] = None, + ): + self.execution_device = execution_device + self.offload = offload + self.io_same_device = io_same_device + self.weights_map = weights_map + self.offload_buffers = offload_buffers + self.place_submodules = place_submodules + self.skip_keys = skip_keys + + # Will contain the input device when `io_same_device=True`. + self.input_device = None + self.param_original_devices = {} + self.buffer_original_devices = {} + self.tied_params_names = set() + + # The hook pre_forward/post_forward need to have knowledge of this dictionary, as with offloading we want to avoid duplicating memory + # for tied weights already loaded on the target execution device. + self.tied_params_map = tied_params_map + + def __repr__(self): + return ( + f"AlignDevicesHook(execution_device={self.execution_device}, offload={self.offload}, " + f"io_same_device={self.io_same_device}, offload_buffers={self.offload_buffers}, " + f"place_submodules={self.place_submodules}, skip_keys={repr(self.skip_keys)})" + ) + + def init_hook(self, module): + # In case the AlignDevicesHook is on meta device, ignore tied weights as data_ptr() is then always zero. + if self.execution_device == "meta" or self.execution_device == torch.device("meta"): + self.tied_params_map = None + + if not self.offload and self.execution_device is not None: + for name, _ in named_module_tensors(module, recurse=self.place_submodules): + set_module_tensor_to_device(module, name, self.execution_device, tied_params_map=self.tied_params_map) + elif self.offload: + self.original_devices = { + name: param.device for name, param in named_module_tensors(module, recurse=self.place_submodules) + } + if self.weights_map is None: + self.weights_map = { + name: param.to("cpu") + for name, param in named_module_tensors( + module, include_buffers=self.offload_buffers, recurse=self.place_submodules + ) + } + for name, _ in named_module_tensors( + module, include_buffers=self.offload_buffers, recurse=self.place_submodules, remove_non_persistent=True + ): + # When using disk offloading, we can not rely on `weights_map[name].data_ptr()` as the reference pointer, + # as we have no guarantee that safetensors' `file.get_tensor()` will always give the same pointer. + # As we have no reliable way to track the shared data pointer of tied weights in this case, we use tied_params_names: List[str] + # to add on the fly pointers to `tied_params_map` in the pre_forward call. + if ( + self.tied_params_map is not None + and recursive_getattr(module, name).data_ptr() in self.tied_params_map + ): + self.tied_params_names.add(name) + + set_module_tensor_to_device(module, name, "meta") + + if not self.offload_buffers and self.execution_device is not None: + for name, _ in module.named_buffers(recurse=self.place_submodules): + set_module_tensor_to_device( + module, name, self.execution_device, tied_params_map=self.tied_params_map + ) + elif self.offload_buffers and self.execution_device is not None: + for name in get_non_persistent_buffers(module, recurse=self.place_submodules): + set_module_tensor_to_device( + module, name, self.execution_device, tied_params_map=self.tied_params_map + ) + + return module + + def pre_forward(self, module, *args, **kwargs): + if self.io_same_device: + self.input_device = find_device([args, kwargs]) + if self.offload: + self.tied_pointers_to_remove = set() + + for name, _ in named_module_tensors( + module, + include_buffers=self.offload_buffers, + recurse=self.place_submodules, + remove_non_persistent=True, + ): + fp16_statistics = None + value = self.weights_map[name] + if "weight" in name and name.replace("weight", "SCB") in self.weights_map.keys(): + if value.dtype == torch.int8: + fp16_statistics = self.weights_map[name.replace("weight", "SCB")] + + # In case we are using offloading with tied weights, we need to keep track of the offloaded weights + # that are loaded on device at this point, as we will need to remove them as well from the dictionary + # self.tied_params_map in order to allow to free memory. + if name in self.tied_params_names and value.data_ptr() not in self.tied_params_map: + self.tied_params_map[value.data_ptr()] = {} + + if ( + value is not None + and self.tied_params_map is not None + and value.data_ptr() in self.tied_params_map + and self.execution_device not in self.tied_params_map[value.data_ptr()] + ): + self.tied_pointers_to_remove.add((value.data_ptr(), self.execution_device)) + + set_module_tensor_to_device( + module, + name, + self.execution_device, + value=value, + fp16_statistics=fp16_statistics, + tied_params_map=self.tied_params_map, + ) + + return send_to_device(args, self.execution_device), send_to_device( + kwargs, self.execution_device, skip_keys=self.skip_keys + ) + + def post_forward(self, module, output): + if self.offload: + for name, _ in named_module_tensors( + module, + include_buffers=self.offload_buffers, + recurse=self.place_submodules, + remove_non_persistent=True, + ): + set_module_tensor_to_device(module, name, "meta") + if type(module).__name__ == "Linear8bitLt": + module.state.SCB = None + module.state.CxB = None + + # We may have loaded tied weights into self.tied_params_map (avoiding to load them several times in e.g. submodules): remove them from + # this dictionary to allow the garbage collector to do its job. + for value_pointer, device in self.tied_pointers_to_remove: + if isinstance(device, int): + if is_npu_available(): + device = f"npu:{device}" + elif is_mlu_available(): + device = f"mlu:{device}" + elif is_musa_available(): + device = f"musa:{device}" + if device in self.tied_params_map[value_pointer]: + del self.tied_params_map[value_pointer][device] + self.tied_pointers_to_remove = set() + if self.io_same_device and self.input_device is not None: + output = send_to_device(output, self.input_device, skip_keys=self.skip_keys) + + return output + + def detach_hook(self, module): + if self.offload: + for name, device in self.original_devices.items(): + if device != torch.device("meta"): + set_module_tensor_to_device(module, name, device, value=self.weights_map.get(name, None)) + return module + + +def attach_execution_device_hook( + module: torch.nn.Module, + execution_device: Union[int, str, torch.device], + skip_keys: Optional[Union[str, list[str]]] = None, + preload_module_classes: Optional[list[str]] = None, + tied_params_map: Optional[dict[int, dict[torch.device, torch.Tensor]]] = None, +): + """ + Recursively attaches `AlignDevicesHook` to all submodules of a given model to make sure they have the right + execution device + + Args: + module (`torch.nn.Module`): + The module where we want to attach the hooks. + execution_device (`int`, `str` or `torch.device`): + The device on which inputs and model weights should be placed before the forward pass. + skip_keys (`str` or `List[str]`, *optional*): + A list of keys to ignore when moving inputs or outputs between devices. + preload_module_classes (`List[str]`, *optional*): + A list of classes whose instances should load all their weights (even in the submodules) at the beginning + of the forward. This should only be used for classes that have submodules which are registered but not + called directly during the forward, for instance if a `dense` linear layer is registered, but at forward, + `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly. + tied_params_map (Optional[Dict[int, Dict[torch.device, torch.Tensor]]], *optional*, defaults to `None`): + A map of data pointers to dictionaries of devices to already dispatched tied weights. For a given execution + device, this parameter is useful to reuse the first available pointer of a shared weight for all others, + instead of duplicating memory. + """ + if not hasattr(module, "_hf_hook") and len(module.state_dict()) > 0: + add_hook_to_module( + module, + AlignDevicesHook(execution_device, skip_keys=skip_keys, tied_params_map=tied_params_map), + ) + + # Break the recursion if we get to a preload module. + if preload_module_classes is not None and module.__class__.__name__ in preload_module_classes: + return + + for child in module.children(): + attach_execution_device_hook( + child, + execution_device, + skip_keys=skip_keys, + preload_module_classes=preload_module_classes, + tied_params_map=tied_params_map, + ) + + +def attach_align_device_hook( + module: torch.nn.Module, + execution_device: Optional[torch.device] = None, + offload: bool = False, + weights_map: Optional[Mapping] = None, + offload_buffers: bool = False, + module_name: str = "", + skip_keys: Optional[Union[str, list[str]]] = None, + preload_module_classes: Optional[list[str]] = None, + tied_params_map: Optional[dict[int, dict[torch.device, torch.Tensor]]] = None, +): + """ + Recursively attaches `AlignDevicesHook` to all submodules of a given model that have direct parameters and/or + buffers. + + Args: + module (`torch.nn.Module`): + The module where we want to attach the hooks. + execution_device (`torch.device`, *optional*): + The device on which inputs and model weights should be placed before the forward pass. + offload (`bool`, *optional*, defaults to `False`): + Whether or not the weights should be offloaded after the forward pass. + weights_map (`Mapping[str, torch.Tensor]`, *optional*): + When the model weights are offloaded, a (potentially lazy) map from param names to the tensor values. + offload_buffers (`bool`, *optional*, defaults to `False`): + Whether or not to include the associated module's buffers when offloading. + module_name (`str`, *optional*, defaults to `""`): + The name of the module. + skip_keys (`str` or `List[str]`, *optional*): + A list of keys to ignore when moving inputs or outputs between devices. + preload_module_classes (`List[str]`, *optional*): + A list of classes whose instances should load all their weights (even in the submodules) at the beginning + of the forward. This should only be used for classes that have submodules which are registered but not + called directly during the forward, for instance if a `dense` linear layer is registered, but at forward, + `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly. + tied_params_map (Optional[Dict[int, Dict[torch.device, torch.Tensor]]], *optional*, defaults to `None`): + A map of data pointers to dictionaries of devices to already dispatched tied weights. For a given execution + device, this parameter is useful to reuse the first available pointer of a shared weight for all others, + instead of duplicating memory. + """ + # Attach the hook on this module if it has any direct tensor. + directs = named_module_tensors(module) + full_offload = ( + offload and preload_module_classes is not None and module.__class__.__name__ in preload_module_classes + ) + + if len(list(directs)) > 0 or full_offload: + if weights_map is not None: + prefix = f"{module_name}." if len(module_name) > 0 else "" + prefixed_weights_map = PrefixedDataset(weights_map, prefix) + else: + prefixed_weights_map = None + hook = AlignDevicesHook( + execution_device=execution_device, + offload=offload, + weights_map=prefixed_weights_map, + offload_buffers=offload_buffers, + place_submodules=full_offload, + skip_keys=skip_keys, + tied_params_map=tied_params_map, + ) + add_hook_to_module(module, hook, append=True) + + # We stop the recursion in case we hit the full offload. + if full_offload: + return + + # Recurse on all children of the module. + for child_name, child in module.named_children(): + child_name = f"{module_name}.{child_name}" if len(module_name) > 0 else child_name + attach_align_device_hook( + child, + execution_device=execution_device, + offload=offload, + weights_map=weights_map, + offload_buffers=offload_buffers, + module_name=child_name, + preload_module_classes=preload_module_classes, + skip_keys=skip_keys, + tied_params_map=tied_params_map, + ) + + +def remove_hook_from_submodules(module: nn.Module): + """ + Recursively removes all hooks attached on the submodules of a given model. + + Args: + module (`torch.nn.Module`): The module on which to remove all hooks. + """ + remove_hook_from_module(module) + for child in module.children(): + remove_hook_from_submodules(child) + + +def attach_align_device_hook_on_blocks( + module: nn.Module, + execution_device: Optional[Union[torch.device, dict[str, torch.device]]] = None, + offload: Union[bool, dict[str, bool]] = False, + weights_map: Mapping = None, + offload_buffers: bool = False, + module_name: str = "", + skip_keys: Optional[Union[str, list[str]]] = None, + preload_module_classes: Optional[list[str]] = None, + tied_params_map: Optional[dict[int, dict[torch.device, torch.Tensor]]] = None, +): + """ + Attaches `AlignDevicesHook` to all blocks of a given model as needed. + + Args: + module (`torch.nn.Module`): + The module where we want to attach the hooks. + execution_device (`torch.device` or `Dict[str, torch.device]`, *optional*): + The device on which inputs and model weights should be placed before the forward pass. It can be one device + for the whole module, or a dictionary mapping module name to device. + offload (`bool`, *optional*, defaults to `False`): + Whether or not the weights should be offloaded after the forward pass. It can be one boolean for the whole + module, or a dictionary mapping module name to boolean. + weights_map (`Mapping[str, torch.Tensor]`, *optional*): + When the model weights are offloaded, a (potentially lazy) map from param names to the tensor values. + offload_buffers (`bool`, *optional*, defaults to `False`): + Whether or not to include the associated module's buffers when offloading. + module_name (`str`, *optional*, defaults to `""`): + The name of the module. + skip_keys (`str` or `List[str]`, *optional*): + A list of keys to ignore when moving inputs or outputs between devices. + preload_module_classes (`List[str]`, *optional*): + A list of classes whose instances should load all their weights (even in the submodules) at the beginning + of the forward. This should only be used for classes that have submodules which are registered but not + called directly during the forward, for instance if a `dense` linear layer is registered, but at forward, + `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly. + tied_params_map (Optional[Dict[int, Dict[torch.device, torch.Tensor]]], *optional*, defaults to `None`): + A map of data pointers to dictionaries of devices to already dispatched tied weights. For a given execution + device, this parameter is useful to reuse the first available pointer of a shared weight for all others, + instead of duplicating memory. + """ + # If one device and one offload, we've got one hook. + if not isinstance(execution_device, Mapping) and not isinstance(offload, dict): + if not offload: + hook = AlignDevicesHook( + execution_device=execution_device, + io_same_device=True, + skip_keys=skip_keys, + place_submodules=True, + tied_params_map=tied_params_map, + ) + add_hook_to_module(module, hook) + else: + attach_align_device_hook( + module, + execution_device=execution_device, + offload=True, + weights_map=weights_map, + offload_buffers=offload_buffers, + module_name=module_name, + skip_keys=skip_keys, + tied_params_map=tied_params_map, + ) + return + + if not isinstance(execution_device, Mapping): + execution_device = {key: execution_device for key in offload.keys()} + if not isinstance(offload, Mapping): + offload = {key: offload for key in execution_device.keys()} + + if module_name in execution_device and module_name in offload and not offload[module_name]: + hook = AlignDevicesHook( + execution_device=execution_device[module_name], + offload_buffers=offload_buffers, + io_same_device=(module_name == ""), + place_submodules=True, + skip_keys=skip_keys, + tied_params_map=tied_params_map, + ) + add_hook_to_module(module, hook) + attach_execution_device_hook( + module, execution_device[module_name], skip_keys=skip_keys, tied_params_map=tied_params_map + ) + elif module_name in execution_device and module_name in offload: + attach_align_device_hook( + module, + execution_device=execution_device[module_name], + offload=True, + weights_map=weights_map, + offload_buffers=offload_buffers, + module_name=module_name, + skip_keys=skip_keys, + preload_module_classes=preload_module_classes, + tied_params_map=tied_params_map, + ) + if not hasattr(module, "_hf_hook"): + hook = AlignDevicesHook( + execution_device=execution_device[module_name], + io_same_device=(module_name == ""), + skip_keys=skip_keys, + tied_params_map=tied_params_map, + ) + add_hook_to_module(module, hook) + attach_execution_device_hook( + module, + execution_device[module_name], + preload_module_classes=preload_module_classes, + skip_keys=skip_keys, + tied_params_map=tied_params_map, + ) + elif module_name == "": + hook = AlignDevicesHook( + execution_device=execution_device.get(""), + io_same_device=True, + skip_keys=skip_keys, + tied_params_map=tied_params_map, + ) + add_hook_to_module(module, hook) + + for child_name, child in module.named_children(): + child_name = f"{module_name}.{child_name}" if len(module_name) > 0 else child_name + attach_align_device_hook_on_blocks( + child, + execution_device=execution_device, + offload=offload, + weights_map=weights_map, + offload_buffers=offload_buffers, + module_name=child_name, + preload_module_classes=preload_module_classes, + skip_keys=skip_keys, + tied_params_map=tied_params_map, + ) + + +class CpuOffload(ModelHook): + """ + Offloads a model on the CPU until its forward pass is called. The model will not be offloaded back to the CPU after + the forward, the user needs to call the `init_hook` method again for this. + + Args: + execution_device(`str`, `int` or `torch.device`, *optional*): + The device on which the model should be executed. Will default to the MPS device if it's available, then + GPU 0 if there is a GPU, and finally to the CPU. + prev_module_hook (`UserCpuOffloadHook`, *optional*): + The hook sent back by [`cpu_offload_with_hook`] for a previous model in the pipeline you are running. If + passed, its offload method will be called just before the forward of the model to which this hook is + attached. + """ + + def __init__( + self, + execution_device: Optional[Union[str, int, torch.device]] = None, + prev_module_hook: Optional["UserCpuOffloadHook"] = None, + ): + self.prev_module_hook = prev_module_hook + + self.execution_device = execution_device if execution_device is not None else PartialState().default_device + + def init_hook(self, module): + return module.to("cpu") + + def pre_forward(self, module, *args, **kwargs): + if self.prev_module_hook is not None: + self.prev_module_hook.offload() + clear_device_cache() + module.to(self.execution_device) + return send_to_device(args, self.execution_device), send_to_device(kwargs, self.execution_device) + + +class UserCpuOffloadHook: + """ + A simple hook grouping a model and a `ModelHook`, which provides easy APIs for to call the init method of the hook + or remove it entirely. + """ + + def __init__(self, model, hook): + self.model = model + self.hook = hook + + def offload(self): + self.hook.init_hook(self.model) + + def remove(self): + remove_hook_from_module(self.model) + + +class LayerwiseCastingHook(ModelHook): + r""" + A hook that casts the weights of a module to a high precision dtype for computation, and to a low precision dtype + for storage. This process may lead to quality loss in the output, but can significantly reduce the memory + footprint. + """ + + _is_stateful = False + + def __init__(self, storage_dtype: torch.dtype, compute_dtype: torch.dtype, non_blocking: bool) -> None: + self.storage_dtype = storage_dtype + self.compute_dtype = compute_dtype + self.non_blocking = non_blocking + + def init_hook(self, module: torch.nn.Module): + module.to(dtype=self.storage_dtype, non_blocking=self.non_blocking) + return module + + def pre_forward(self, module: torch.nn.Module, *args, **kwargs): + module.to(dtype=self.compute_dtype, non_blocking=self.non_blocking) + return args, kwargs + + def post_forward(self, module: torch.nn.Module, output): + module.to(dtype=self.storage_dtype, non_blocking=self.non_blocking) + return output diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/inference.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..d1659718b0b3020955f04060aa6f0cc7ef66d7ff --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/inference.py @@ -0,0 +1,184 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import math +from types import MethodType +from typing import Any, Optional, Union + +from .state import PartialState +from .utils import ( + calculate_maximum_sizes, + convert_bytes, + copy_tensor_to_devices, + ignorant_find_batch_size, + infer_auto_device_map, + is_pippy_available, + pad_input_tensors, + send_to_device, +) + + +def generate_device_map(model, num_processes: int = 1, no_split_module_classes=None, max_memory: dict = None): + """ + Calculates the device map for `model` with an offset for PiPPy + """ + if num_processes == 1: + return infer_auto_device_map(model, no_split_module_classes=no_split_module_classes, clean_result=False) + if max_memory is None: + model_size, shared = calculate_maximum_sizes(model) + + # Split into `n` chunks for each GPU + memory = (model_size + shared[0]) / num_processes + memory = convert_bytes(memory) + value, ending = memory.split(" ") + + # Add a chunk to deal with potential extra shared memory instances + memory = math.ceil(float(value)) * 1.1 + memory = f"{memory} {ending}" + max_memory = {i: memory for i in range(num_processes)} + device_map = infer_auto_device_map( + model, + max_memory=max_memory, + no_split_module_classes=no_split_module_classes, + clean_result=False, + ) + return device_map + + +def find_pippy_batch_size(args, kwargs): + found_batch_size = None + if args is not None: + for arg in args: + found_batch_size = ignorant_find_batch_size(arg) + if found_batch_size is not None: + break + if kwargs is not None and found_batch_size is None: + for kwarg in kwargs.values(): + found_batch_size = ignorant_find_batch_size(kwarg) + if found_batch_size is not None: + break + return found_batch_size + + +def build_pipeline(model, split_points, args, kwargs, num_chunks): + """ + Attaches the split points to the model based on `self.device_map` and generates a `PipelineStage`. Requires passing + in needed `args` and `kwargs` as the model needs on the CPU. + + Users can pass in custom `num_chunks` as an optional hyper-parameter. By default will use + `AcceleratorState.num_processes` + """ + # Note: We import here to reduce import time from general modules, and isolate outside dependencies + from torch.distributed.pipelining import ScheduleGPipe, SplitPoint, pipeline + + # We need to annotate the split points in the model for PiPPy + state = PartialState() + split_spec = {split_point: SplitPoint.BEGINNING for split_point in split_points} + pipe = pipeline( + model, + mb_args=args, + mb_kwargs=kwargs, + split_spec=split_spec, + ) + stage = pipe.build_stage(state.local_process_index, device=state.device) + schedule = ScheduleGPipe(stage, num_chunks) + + return schedule + + +def pippy_forward(forward, num_chunks, gather_output, *args, **kwargs): + state = PartialState() + output = None + + if state.num_processes == 1: + output = forward(*args, **kwargs) + elif state.is_local_main_process: + found_batch_size = find_pippy_batch_size(args, kwargs) + if found_batch_size is None: + raise ValueError("Could not find batch size from args or kwargs") + else: + if found_batch_size != num_chunks: + args = pad_input_tensors(args, found_batch_size, num_chunks) + kwargs = pad_input_tensors(kwargs, found_batch_size, num_chunks) + forward(*args, **kwargs) + elif state.is_last_process: + output = forward() + else: + forward() + if gather_output: + # Each node will get a copy of the full output which is only on the last GPU + output = copy_tensor_to_devices(output) + return output + + +def prepare_pippy( + model, + split_points: Optional[Union[str, list[str]]] = "auto", + no_split_module_classes: Optional[list[str]] = None, + example_args: Optional[tuple[Any]] = (), + example_kwargs: Optional[dict[str, Any]] = None, + num_chunks: Optional[int] = None, + gather_output: Optional[bool] = False, +): + """ + Wraps `model` for pipeline parallel inference. + + Args: + model (`torch.nn.Module`): + A model we want to split for pipeline-parallel inference + split_points (`str` or `List[str]`, defaults to 'auto'): + How to generate the split points and chunk the model across each GPU. 'auto' will find the best balanced + split given any model. Should be a list of layer names in the model to split by otherwise. + no_split_module_classes (`List[str]`): + A list of class names for layers we don't want to be split. + example_args (tuple of model inputs): + The expected inputs for the model that uses order-based inputs for a *single process*. Recommended to use + this method if possible. + example_kwargs (dict of model inputs) + The expected inputs for the model that uses dictionary-based inputs for a *single process*. This is a + *highly* limiting structure that requires the same keys be present at *all* inference calls. Not + recommended unless the prior condition is true for all cases. + num_chunks (`int`, defaults to the number of available GPUs): + The number of different stages the Pipeline will have. By default it will assign one chunk per GPU, but + this can be tuned and played with. In general one should have num_chunks >= num_gpus. + gather_output (`bool`, defaults to `False`): + If `True`, the output from the last GPU (which holds the true outputs) is sent across to all GPUs. + """ + if not is_pippy_available(): + raise ImportError("Using `torch.distributed.pipelining` requires PyTorch 2.4.0 or later.") + state = PartialState() + example_args = send_to_device(example_args, "cpu") + example_kwargs = send_to_device(example_kwargs, "cpu") + if num_chunks is None: + num_chunks = state.num_processes + if split_points == "auto": + device_map = generate_device_map(model, num_chunks, no_split_module_classes=no_split_module_classes) + split_points = [] + for i in range(1, num_chunks): + split_points.append(next(k for k, v in device_map.items() if v == i)) + model.hf_split_points = split_points + stage = build_pipeline(model, split_points, example_args, example_kwargs, num_chunks) + model._original_forward = model.forward + model._original_call = model.__call__ + model.pippy_stage = stage + model.hf_split_points = split_points + + def forward(*args, **kwargs): + return pippy_forward(stage.step, num_chunks, gather_output, *args, **kwargs) + + # To act like a decorator so that it can be popped when doing `extract_model_from_parallel` + # Note: creates an infinite recursion loop with `generate` + model_forward = MethodType(forward, model) + forward.__wrapped__ = model_forward + model.forward = forward + return model diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/launchers.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/launchers.py new file mode 100644 index 0000000000000000000000000000000000000000..532c0ad4450bb22870efa5a3d46cedbfbca5a28b --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/launchers.py @@ -0,0 +1,306 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import sys +import tempfile + +import torch + +from .state import AcceleratorState, PartialState +from .utils import ( + PrecisionType, + PrepareForLaunch, + are_libraries_initialized, + check_cuda_p2p_ib_support, + get_gpu_info, + is_mps_available, + is_torch_version, + patch_environment, +) +from .utils.constants import ELASTIC_LOG_LINE_PREFIX_TEMPLATE_PYTORCH_VERSION + + +def test_launch(): + "Verify a `PartialState` can be initialized." + _ = PartialState() + + +def notebook_launcher( + function, + args=(), + num_processes=None, + mixed_precision="no", + use_port="29500", + master_addr="127.0.0.1", + node_rank=0, + num_nodes=1, + rdzv_backend="static", + rdzv_endpoint="", + rdzv_conf=None, + rdzv_id="none", + max_restarts=0, + monitor_interval=0.1, + log_line_prefix_template=None, +): + """ + Launches a training function, using several processes or multiple nodes if it's possible in the current environment + (TPU with multiple cores for instance). + + + + To use this function absolutely zero calls to a device must be made in the notebook session before calling. If any + have been made, you will need to restart the notebook and make sure no cells use any device capability. + + Setting `ACCELERATE_DEBUG_MODE="1"` in your environment will run a test before truly launching to ensure that none + of those calls have been made. + + + + Args: + function (`Callable`): + The training function to execute. If it accepts arguments, the first argument should be the index of the + process run. + args (`Tuple`): + Tuple of arguments to pass to the function (it will receive `*args`). + num_processes (`int`, *optional*): + The number of processes to use for training. Will default to 8 in Colab/Kaggle if a TPU is available, to + the number of devices available otherwise. + mixed_precision (`str`, *optional*, defaults to `"no"`): + If `fp16` or `bf16`, will use mixed precision training on multi-device. + use_port (`str`, *optional*, defaults to `"29500"`): + The port to use to communicate between processes when launching a multi-device training. + master_addr (`str`, *optional*, defaults to `"127.0.0.1"`): + The address to use for communication between processes. + node_rank (`int`, *optional*, defaults to 0): + The rank of the current node. + num_nodes (`int`, *optional*, defaults to 1): + The number of nodes to use for training. + rdzv_backend (`str`, *optional*, defaults to `"static"`): + The rendezvous method to use, such as 'static' (the default) or 'c10d' + rdzv_endpoint (`str`, *optional*, defaults to `""`): + The endpoint of the rdzv sync. storage. + rdzv_conf (`Dict`, *optional*, defaults to `None`): + Additional rendezvous configuration. + rdzv_id (`str`, *optional*, defaults to `"none"`): + The unique run id of the job. + max_restarts (`int`, *optional*, defaults to 0): + The maximum amount of restarts that elastic agent will conduct on workers before failure. + monitor_interval (`float`, *optional*, defaults to 0.1): + The interval in seconds that is used by the elastic_agent as a period of monitoring workers. + log_line_prefix_template (`str`, *optional*, defaults to `None`): + The prefix template for elastic launch logging. Available from PyTorch 2.2.0. + + Example: + + ```python + # Assume this is defined in a Jupyter Notebook on an instance with two devices + from accelerate import notebook_launcher + + + def train(*args): + # Your training function here + ... + + + notebook_launcher(train, args=(arg1, arg2), num_processes=2, mixed_precision="fp16") + ``` + """ + # Are we in a google colab or a Kaggle Kernel? + in_colab = False + in_kaggle = False + if any(key.startswith("KAGGLE") for key in os.environ.keys()): + in_kaggle = True + elif "IPython" in sys.modules: + in_colab = "google.colab" in str(sys.modules["IPython"].get_ipython()) + + try: + mixed_precision = PrecisionType(mixed_precision.lower()) + except ValueError: + raise ValueError( + f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}." + ) + + if (in_colab or in_kaggle) and ( + (os.environ.get("TPU_NAME", None) is not None) or (os.environ.get("PJRT_DEVICE", "") == "TPU") + ): + # TPU launch + import torch_xla.distributed.xla_multiprocessing as xmp + + if len(AcceleratorState._shared_state) > 0: + raise ValueError( + "To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside " + "your training function. Restart your notebook and make sure no cells initializes an " + "`Accelerator`." + ) + + launcher = PrepareForLaunch(function, distributed_type="XLA") + print("Launching a training on TPU cores.") + xmp.spawn(launcher, args=args, start_method="fork") + elif in_colab and get_gpu_info()[1] < 2: + # No need for a distributed launch otherwise as it's either CPU or one GPU. + if torch.cuda.is_available(): + print("Launching training on one GPU.") + else: + print("Launching training on one CPU.") + function(*args) + else: + if num_processes is None: + raise ValueError( + "You have to specify the number of devices you would like to use, add `num_processes=...` to your call." + ) + if node_rank >= num_nodes: + raise ValueError("The node_rank must be less than the number of nodes.") + if num_processes > 1: + # Multi-device launch + from torch.distributed.launcher.api import LaunchConfig, elastic_launch + from torch.multiprocessing import start_processes + from torch.multiprocessing.spawn import ProcessRaisedException + + if len(AcceleratorState._shared_state) > 0: + raise ValueError( + "To launch a multi-device training from your notebook, the `Accelerator` should only be initialized " + "inside your training function. Restart your notebook and make sure no cells initializes an " + "`Accelerator`." + ) + # Check for specific libraries known to initialize device that users constantly use + problematic_imports = are_libraries_initialized("bitsandbytes") + if len(problematic_imports) > 0: + err = ( + "Could not start distributed process. Libraries known to initialize device upon import have been " + "imported already. Please keep these imports inside your training function to try and help with this:" + ) + for lib_name in problematic_imports: + err += f"\n\t* `{lib_name}`" + raise RuntimeError(err) + + patched_env = dict( + nproc=num_processes, + node_rank=node_rank, + world_size=num_nodes * num_processes, + master_addr=master_addr, + master_port=use_port, + mixed_precision=mixed_precision, + ) + + # Check for CUDA P2P and IB issues + if not check_cuda_p2p_ib_support(): + patched_env["nccl_p2p_disable"] = "1" + patched_env["nccl_ib_disable"] = "1" + + # torch.distributed will expect a few environment variable to be here. We set the ones common to each + # process here (the other ones will be set be the launcher). + with patch_environment(**patched_env): + # First dummy launch + device_type = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda" + distributed_type = "MULTI_XPU" if device_type == "xpu" else "MULTI_GPU" + if os.environ.get("ACCELERATE_DEBUG_MODE", "false").lower() == "true": + launcher = PrepareForLaunch(test_launch, distributed_type=distributed_type) + try: + start_processes(launcher, args=(), nprocs=num_processes, start_method="fork") + except ProcessRaisedException as e: + err = "An issue was found when verifying a stable environment for the notebook launcher." + if f"Cannot re-initialize {device_type.upper()} in forked subprocess" in e.args[0]: + raise RuntimeError( + f"{err}" + "This likely stems from an outside import causing issues once the `notebook_launcher()` is called. " + "Please review your imports and test them when running the `notebook_launcher()` to identify " + f"which one is problematic and causing {device_type.upper()} to be initialized." + ) from e + else: + raise RuntimeError(f"{err} The following error was raised: {e}") from e + # Now the actual launch + launcher = PrepareForLaunch(function, distributed_type=distributed_type) + print(f"Launching training on {num_processes} {device_type.upper()}s.") + try: + if rdzv_conf is None: + rdzv_conf = {} + if rdzv_backend == "static": + rdzv_conf["rank"] = node_rank + if not rdzv_endpoint: + rdzv_endpoint = f"{master_addr}:{use_port}" + launch_config_kwargs = dict( + min_nodes=num_nodes, + max_nodes=num_nodes, + nproc_per_node=num_processes, + run_id=rdzv_id, + rdzv_endpoint=rdzv_endpoint, + rdzv_backend=rdzv_backend, + rdzv_configs=rdzv_conf, + max_restarts=max_restarts, + monitor_interval=monitor_interval, + start_method="fork", + ) + if is_torch_version(">=", ELASTIC_LOG_LINE_PREFIX_TEMPLATE_PYTORCH_VERSION): + launch_config_kwargs["log_line_prefix_template"] = log_line_prefix_template + elastic_launch(config=LaunchConfig(**launch_config_kwargs), entrypoint=function)(*args) + except ProcessRaisedException as e: + if f"Cannot re-initialize {device_type.upper()} in forked subprocess" in e.args[0]: + raise RuntimeError( + f"{device_type.upper()} has been initialized before the `notebook_launcher` could create a forked subprocess. " + "This likely stems from an outside import causing issues once the `notebook_launcher()` is called. " + "Please review your imports and test them when running the `notebook_launcher()` to identify " + f"which one is problematic and causing {device_type.upper()} to be initialized." + ) from e + else: + raise RuntimeError(f"An issue was found when launching the training: {e}") from e + + else: + # No need for a distributed launch otherwise as it's either CPU, GPU, XPU or MPS. + if is_mps_available(): + os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" + print("Launching training on MPS.") + elif torch.cuda.is_available(): + print("Launching training on one GPU.") + elif torch.xpu.is_available(): + print("Launching training on one XPU.") + else: + print("Launching training on CPU.") + function(*args) + + +def debug_launcher(function, args=(), num_processes=2): + """ + Launches a training function using several processes on CPU for debugging purposes. + + + + This function is provided for internal testing and debugging, but it's not intended for real trainings. It will + only use the CPU. + + + + Args: + function (`Callable`): + The training function to execute. + args (`Tuple`): + Tuple of arguments to pass to the function (it will receive `*args`). + num_processes (`int`, *optional*, defaults to 2): + The number of processes to use for training. + """ + from torch.multiprocessing import start_processes + + with tempfile.NamedTemporaryFile() as tmp_file: + # torch.distributed will expect a few environment variable to be here. We set the ones common to each + # process here (the other ones will be set be the launcher). + with patch_environment( + world_size=num_processes, + master_addr="127.0.0.1", + master_port="29500", + accelerate_mixed_precision="no", + accelerate_debug_rdv_file=tmp_file.name, + accelerate_use_cpu="yes", + ): + launcher = PrepareForLaunch(function, debug=True) + start_processes(launcher, args=args, nprocs=num_processes, start_method="fork") diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/local_sgd.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/local_sgd.py new file mode 100644 index 0000000000000000000000000000000000000000..40b198d46aa24610d8eaf46424474d7c1c9881a1 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/local_sgd.py @@ -0,0 +1,106 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import torch + +from accelerate import Accelerator, DistributedType + + +class LocalSGD: + """ + A helper class to support local SGD on top of Accelerator. It simply runs a given number of updates independently + on each device, and averages model weights every K synchronization step. + + It should be used only in the multi-GPU (or multi-CPU) setup without extensions such as DeepSpeed. In particular, + this is a simple implementation that cannot support scenarios such as model parallelism. + + + Although we are not aware of the true origins of this simple approach, the idea of local SGD is quite old and goes + back to at least: + + Zhang, J., De Sa, C., Mitliagkas, I., & Ré, C. (2016). [Parallel SGD: When does averaging help?. arXiv preprint + arXiv:1606.07365.](https://arxiv.org/abs/1606.07365) + + We credit the term Local SGD to the following paper (but there might be earlier references we are not aware of). + + Stich, Sebastian Urban. ["Local SGD Converges Fast and Communicates Little." ICLR 2019-International Conference on + Learning Representations. No. CONF. 2019.](https://arxiv.org/abs/1805.09767) + + """ + + def __enter__(self): + if self.enabled: + self.model_sync_obj = self.model.no_sync() + self.model_sync_obj.__enter__() + + return self + + def __exit__(self, type, value, tb): + if self.enabled: + # Average all models on exit + self._sync_and_avg_model_params() + self.model_sync_obj.__exit__(type, value, tb) + + def __init__(self, accelerator: Accelerator, model: torch.nn.Module, local_sgd_steps: int, enabled: bool = True): + """ + Constructor. + + Args: + model (`torch.nn.Module): + The model whose parameters we need to average. + accelerator (`Accelerator`): + Accelerator object. + local_sgd_steps (`int`): + A number of local SGD steps (before model parameters are synchronized). + enabled (`bool): + Local SGD is disabled if this parameter set to `False`. + """ + if accelerator.distributed_type not in [ + DistributedType.NO, + DistributedType.MULTI_CPU, + DistributedType.MULTI_GPU, + DistributedType.MULTI_XPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_HPU, + DistributedType.MULTI_SDAA, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_NPU, + ]: + raise NotImplementedError("LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)") + self.enabled = enabled and accelerator.distributed_type != DistributedType.NO + self.num_steps = 0 + if self.enabled: + self.accelerator = accelerator + self.model = model + self.local_sgd_steps = local_sgd_steps + + def step(self): + """ + This function makes a "step" and synchronizes model parameters if necessary. + """ + self.num_steps += 1 + if not self.enabled: + return + + if self.num_steps % self.local_sgd_steps == 0: + self._sync_and_avg_model_params() + + def _sync_and_avg_model_params(self): + """ + Synchronize + Average model parameters across all GPUs + """ + + self.accelerator.wait_for_everyone() + with self.accelerator.autocast(): + for param in self.model.parameters(): + param.data = self.accelerator.reduce(param.data, reduction="mean") diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/logging.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..1615bc313b74d4f01166384435b6c499ff616f49 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/logging.py @@ -0,0 +1,125 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import functools +import logging +import os + +from .state import PartialState + + +class MultiProcessAdapter(logging.LoggerAdapter): + """ + An adapter to assist with logging in multiprocess. + + `log` takes in an additional `main_process_only` kwarg, which dictates whether it should be called on all processes + or only the main executed one. Default is `main_process_only=True`. + + Does not require an `Accelerator` object to be created first. + """ + + @staticmethod + def _should_log(main_process_only): + "Check if log should be performed" + state = PartialState() + return not main_process_only or (main_process_only and state.is_main_process) + + def log(self, level, msg, *args, **kwargs): + """ + Delegates logger call after checking if we should log. + + Accepts a new kwarg of `main_process_only`, which will dictate whether it will be logged across all processes + or only the main executed one. Default is `True` if not passed + + Also accepts "in_order", which if `True` makes the processes log one by one, in order. This is much easier to + read, but comes at the cost of sometimes needing to wait for the other processes. Default is `False` to not + break with the previous behavior. + + `in_order` is ignored if `main_process_only` is passed. + """ + if PartialState._shared_state == {}: + raise RuntimeError( + "You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility." + ) + main_process_only = kwargs.pop("main_process_only", True) + in_order = kwargs.pop("in_order", False) + # set `stacklevel` to exclude ourself in `Logger.findCaller()` while respecting user's choice + kwargs.setdefault("stacklevel", 2) + + if self.isEnabledFor(level): + if self._should_log(main_process_only): + msg, kwargs = self.process(msg, kwargs) + self.logger.log(level, msg, *args, **kwargs) + + elif in_order: + state = PartialState() + for i in range(state.num_processes): + if i == state.process_index: + msg, kwargs = self.process(msg, kwargs) + self.logger.log(level, msg, *args, **kwargs) + state.wait_for_everyone() + + @functools.lru_cache(None) + def warning_once(self, *args, **kwargs): + """ + This method is identical to `logger.warning()`, but will emit the warning with the same message only once + + Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the + cache. The assumption here is that all warning messages are unique across the code. If they aren't then need to + switch to another type of cache that includes the caller frame information in the hashing function. + """ + self.warning(*args, **kwargs) + + +def get_logger(name: str, log_level: str = None): + """ + Returns a `logging.Logger` for `name` that can handle multiprocessing. + + If a log should be called on all processes, pass `main_process_only=False` If a log should be called on all + processes and in order, also pass `in_order=True` + + Args: + name (`str`): + The name for the logger, such as `__file__` + log_level (`str`, *optional*): + The log level to use. If not passed, will default to the `LOG_LEVEL` environment variable, or `INFO` if not + + Example: + + ```python + >>> from accelerate.logging import get_logger + >>> from accelerate import Accelerator + + >>> logger = get_logger(__name__) + + >>> accelerator = Accelerator() + >>> logger.info("My log", main_process_only=False) + >>> logger.debug("My log", main_process_only=True) + + >>> logger = get_logger(__name__, log_level="DEBUG") + >>> logger.info("My log") + >>> logger.debug("My second log") + + >>> array = ["a", "b", "c", "d"] + >>> letter_at_rank = array[accelerator.process_index] + >>> logger.info(letter_at_rank, in_order=True) + ``` + """ + if log_level is None: + log_level = os.environ.get("ACCELERATE_LOG_LEVEL", None) + logger = logging.getLogger(name) + if log_level is not None: + logger.setLevel(log_level.upper()) + logger.root.setLevel(log_level.upper()) + return MultiProcessAdapter(logger, {}) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/memory_utils.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/memory_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fa2e2c8b9d7d0064c3e5e282737a7ad6919bde29 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/memory_utils.py @@ -0,0 +1,22 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings + + +warnings.warn( + "memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: " + "`from accelerate import find_executable_batch_size` to avoid this warning.", + FutureWarning, +) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/optimizer.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..c1f8faa15436fb5d1d02ae4d691a4fcac44cd236 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/optimizer.py @@ -0,0 +1,213 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect + +import torch + +from .state import AcceleratorState, GradientState +from .utils import DistributedType, honor_type, is_lomo_available, is_torch_xla_available + + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + import torch_xla.runtime as xr + + +def move_to_device(state, device): + if isinstance(state, (list, tuple)): + return honor_type(state, (move_to_device(t, device) for t in state)) + elif isinstance(state, dict): + return type(state)({k: move_to_device(v, device) for k, v in state.items()}) + elif isinstance(state, torch.Tensor): + return state.to(device) + return state + + +class AcceleratedOptimizer(torch.optim.Optimizer): + """ + Internal wrapper around a torch optimizer. + + Conditionally will perform `step` and `zero_grad` if gradients should be synchronized when performing gradient + accumulation. + + Args: + optimizer (`torch.optim.optimizer.Optimizer`): + The optimizer to wrap. + device_placement (`bool`, *optional*, defaults to `True`): + Whether or not the optimizer should handle device placement. If so, it will place the state dictionary of + `optimizer` on the right device. + scaler (`torch.amp.GradScaler` or `torch.cuda.amp.GradScaler`, *optional*): + The scaler to use in the step function if training with mixed precision. + """ + + def __init__(self, optimizer, device_placement=True, scaler=None): + self.optimizer = optimizer + self.scaler = scaler + self.accelerator_state = AcceleratorState() + self.gradient_state = GradientState() + self.device_placement = device_placement + self._is_overflow = False + + if self.scaler is not None: + self._accelerate_step_called = False + self._optimizer_original_step_method = self.optimizer.step + self._optimizer_patched_step_method = patch_optimizer_step(self, self.optimizer.step) + + # Handle device placement + if device_placement: + state_dict = self.optimizer.state_dict() + if self.accelerator_state.distributed_type == DistributedType.XLA: + xm.send_cpu_data_to_device(state_dict, self.accelerator_state.device) + else: + state_dict = move_to_device(state_dict, self.accelerator_state.device) + self.optimizer.load_state_dict(state_dict) + + @property + def state(self): + return self.optimizer.state + + @state.setter + def state(self, state): + self.optimizer.state = state + + @property + def param_groups(self): + return self.optimizer.param_groups + + @param_groups.setter + def param_groups(self, param_groups): + self.optimizer.param_groups = param_groups + + @property + def defaults(self): + return self.optimizer.defaults + + @defaults.setter + def defaults(self, defaults): + self.optimizer.defaults = defaults + + def add_param_group(self, param_group): + self.optimizer.add_param_group(param_group) + + def load_state_dict(self, state_dict): + if self.accelerator_state.distributed_type == DistributedType.XLA and self.device_placement: + xm.send_cpu_data_to_device(state_dict, self.accelerator_state.device) + self.optimizer.load_state_dict(state_dict) + + def state_dict(self): + return self.optimizer.state_dict() + + def zero_grad(self, set_to_none=None): + if self.gradient_state.sync_gradients: + accept_arg = "set_to_none" in inspect.signature(self.optimizer.zero_grad).parameters + if accept_arg: + if set_to_none is None: + set_to_none = True + self.optimizer.zero_grad(set_to_none=set_to_none) + else: + if set_to_none is not None: + raise ValueError("`set_to_none` for Optimizer.zero_grad` is not supported by this optimizer.") + self.optimizer.zero_grad() + + def train(self): + """ + Sets the optimizer to "train" mode. Useful for optimizers like `schedule_free` + """ + if hasattr(self.optimizer, "train") and callable(self.optimizer.train): + self.optimizer.train() + elif ( + hasattr(self.optimizer, "optimizer") + and hasattr(self.optimizer.optimizer, "train") + and callable(self.optimizer.optimizer.train) + ): + # the deepspeed optimizer further wraps the optimizer + self.optimizer.optimizer.train() + + def eval(self): + """ + Sets the optimizer to "eval" mode. Useful for optimizers like `schedule_free` + """ + if hasattr(self.optimizer, "eval") and callable(self.optimizer.eval): + self.optimizer.eval() + + def step(self, closure=None): + if is_lomo_available(): + from lomo_optim import AdaLomo, Lomo + + if ( + not self.gradient_state.is_xla_gradients_synced + and self.accelerator_state.distributed_type == DistributedType.XLA + ): + gradients = xm._fetch_gradients(self.optimizer) + xm.all_reduce("sum", gradients, scale=1.0 / xr.world_size()) + self.gradient_state.is_xla_gradients_synced = True + + if is_lomo_available(): + # `step` should be a no-op for LOMO optimizers. + if isinstance(self.optimizer, (Lomo, AdaLomo)): + return + + if self.gradient_state.sync_gradients: + if self.scaler is not None: + self.optimizer.step = self._optimizer_patched_step_method + + self.scaler.step(self.optimizer, closure) + self.scaler.update() + + if not self._accelerate_step_called: + # If the optimizer step was skipped, gradient overflow was detected. + self._is_overflow = True + else: + self._is_overflow = False + # Reset the step method to the original one + self.optimizer.step = self._optimizer_original_step_method + # Reset the indicator + self._accelerate_step_called = False + else: + self.optimizer.step(closure) + if self.accelerator_state.distributed_type == DistributedType.XLA: + self.gradient_state.is_xla_gradients_synced = False + + def _switch_parameters(self, parameters_map): + for param_group in self.optimizer.param_groups: + param_group["params"] = [parameters_map.get(p, p) for p in param_group["params"]] + + @property + def step_was_skipped(self): + """Whether or not the optimizer step was skipped.""" + return self._is_overflow + + def __getstate__(self): + _ignored_keys = [ + "_accelerate_step_called", + "_optimizer_original_step_method", + "_optimizer_patched_step_method", + ] + return {k: v for k, v in self.__dict__.items() if k not in _ignored_keys} + + def __setstate__(self, state): + self.__dict__.update(state) + if self.scaler is not None: + self._accelerate_step_called = False + self._optimizer_original_step_method = self.optimizer.step + self._optimizer_patched_step_method = patch_optimizer_step(self, self.optimizer.step) + + +def patch_optimizer_step(accelerated_optimizer: AcceleratedOptimizer, method): + def patched_step(*args, **kwargs): + accelerated_optimizer._accelerate_step_called = True + return method(*args, **kwargs) + + return patched_step diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/parallelism_config.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/parallelism_config.py new file mode 100644 index 0000000000000000000000000000000000000000..8755c242e003b172af3f3a8743c058ce19e7af49 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/parallelism_config.py @@ -0,0 +1,289 @@ +# Copyright 2025 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import warnings +from dataclasses import dataclass +from typing import TYPE_CHECKING, Union + +from torch.distributed.device_mesh import init_device_mesh + +from accelerate.utils.dataclasses import TorchContextParallelConfig, TorchTensorParallelConfig + + +if TYPE_CHECKING: + from accelerate import Accelerator + + +@dataclass +class ParallelismConfig: + """ + A dataclass to configure parallelisms applied to the model. Inspired by torchtitan's `ParallelDims` + https://github.com/pytorch/torchtitan/blob/main/torchtitan/distributed/parallel_dims.py + + Args: + dp_replicate_size (`int`, defaults to `1`): + The size of the data parallel group. If `dp_replicate_size` is set to 1, the data parallel replication + group will not be used. + dp_shard_size (`int`, defaults to `1`): + The size of the model shard group. If `dp_replicate_size > 1` and `tp_size > 1`, `dp_shard_size` must also + be greater than 1, as composing DDP + TP is currently not supported. + tp_size (`int`, defaults to `1`): + The size of the tensor parallel group. If `tp_size` is set to `1`, the tensor parallel group will not be + used. + cp_size (`int`, defaults to `1`): + The size of the context parallel group. Currently not supported, but reserved for future use and enabled + for downstream libraries. + tp_handler (`~utils.TorchTensorParallelConfig`, defaults to `None`): + The handler for the tensor parallel group. + + You may obtain different distributed data parallel paradigms by configuring `dp_replicate_size` and `dp_shard_size` + together: + - `dp_replicate_size == 1` and `dp_shard_size > 1`, we obtain Fully Sharded Data Parallel (FSDP). + - `dp_replicate_size > 1` and `dp_shard_size > 1`, we obtain Hybrid Sharded Data Parallel (HSDP). + - `dp_replicate_size > 1` and `dp_shard_size == 1` is an invalid configuration, to use pure DP, use + `DistributedDataParallelKwargs` instead. + + """ + + dp_replicate_size: int = None + dp_shard_size: int = None + tp_size: int = None + cp_size: int = None + + # we use Union because we might support other x parallel plugins (i.e. deepspeed, etc) + tp_handler: Union[None, TorchTensorParallelConfig] = None + cp_handler: Union[None, TorchContextParallelConfig] = None + + def __repr__(self): + return ( + "ParallelismConfig(\n " + f"\tdp_replicate_size={self.dp_replicate_size},\n" + f"\tdp_shard_size={self.dp_shard_size},\n" + f"\ttp_size={self.tp_size},\n" + f"\tcp_size={self.cp_size},\n" + f"\ttotal_size={self.total_size}\n" + f"\ttp_handler={self.tp_handler},\n" + f"\tcp_handler={self.cp_handler})\n" + ) + + @property + def dp_dim_names(self): + """Names of enabled dimensions across which data parallelism is applied.""" + dims = [] + if self.dp_replicate_enabled: + dims += ["dp_replicate"] + if self.dp_shard_enabled: + dims += ["dp_shard"] + return dims + + @property + def non_dp_dim_names(self): + """Names of enabled dimensions which will receive the same batch (non-data parallel dimensions).""" + dims = [] + if self.tp_enabled: + dims += ["tp"] + if self.cp_enabled: + dims += ["cp"] + return dims + + @property + def dp_shard_cp_dim_names(self): + """Names of enabled dimensions which will be flattened into a joint mesh across which is model sharded in FSDP.""" + dims = [] + if self.dp_shard_enabled: + dims += ["dp_shard"] + if self.cp_enabled: + dims += ["cp"] + return dims + + @property + def dp_cp_dim_names(self): + """Names of enabled dimensions across which loss should be averaged""" + dims = [] + if self.dp_replicate_enabled: + dims += ["dp_replicate"] + if self.dp_shard_enabled: + dims += ["dp_shard"] + if self.cp_enabled: + dims += ["cp"] + return dims + + @property + def fsdp_dim_names(self): + """Names of enabled dimensions across which FSDP is applied, including data parallel replication.""" + dims = [] + if self.dp_replicate_enabled: + dims += ["dp_replicate"] + dims += ["dp_shard_cp"] + return dims + + @property + def total_size(self): + """The total size of the parallelism configuration, which is the product of all sizes.""" + return self.dp_replicate_size * self.dp_shard_size * self.tp_size * self.cp_size + + @property + def non_data_parallel_size(self): + """The size of the non-data parallel dimensions, which is the product of tensor and context parallel sizes.""" + return self.tp_size * self.cp_size + + @property + def data_parallel_size(self): + """The size of the data parallel dimensions, which is the product of data parallel replication and""" + return self.dp_replicate_size * self.dp_shard_size + + @property + def dp_replicate_enabled(self): + """True if data parallel replication is enabled, i.e. `dp_replicate_size > 1`.""" + return self.dp_replicate_size > 1 + + @property + def dp_shard_enabled(self): + """True if data parallel sharding is enabled, i.e. `dp_shard_size > 1`.""" + return self.dp_shard_size > 1 + + @property + def tp_enabled(self): + """True if tensor parallelism is enabled, i.e. `tp_size > 1`.""" + return self.tp_size > 1 + + @property + def cp_enabled(self): + """True if context parallelism is enabled, i.e. `cp_size > 1`.""" + return self.cp_size > 1 + + @property + def active_mesh_dims(self): + """Names of all active mesh dimensions.""" + return self.dp_dim_names + self.non_dp_dim_names + + def build_device_mesh(self, device_type: str): + """Builds a device mesh for the given device type based on the parallelism configuration. + This method will also create required joint meshes (e.g. `dp_shard_cp`, `dp_cp`, `dp`). + + Args: + device_type (`str`): The type of device for which to build the mesh, e + """ + mesh = self._get_mesh() + if len(mesh) == 0: + return + mesh_dim_names, mesh_shape = mesh + device_mesh = init_device_mesh( + device_type, + mesh_shape, + mesh_dim_names=mesh_dim_names, + ) + if self.dp_dim_names: + device_mesh[self.dp_dim_names]._flatten("dp") + if self.dp_shard_cp_dim_names: + device_mesh[self.dp_shard_cp_dim_names]._flatten("dp_shard_cp") + if self.dp_cp_dim_names: + device_mesh[self.dp_cp_dim_names]._flatten("dp_cp") + + return device_mesh + + def _get_mesh(self) -> tuple[tuple[int, ...], tuple[str, ...]]: + """Generate mesh shape and dimension names for torch.distributed.init_device_mesh().""" + + # Build mesh dimensions dictionary + mesh_dims = {parallelism: self._sizes[parallelism] for parallelism in self.active_mesh_dims} + + # Apply canonical ordering + mesh_order = ["dp_replicate", "dp_shard", "cp", "tp"] + sorted_items = sorted( + mesh_dims.items(), + key=lambda x: (mesh_order.index(x[0])), + ) + return tuple(zip(*sorted_items)) + + def __post_init__(self): + # Basic size validation + if self.dp_replicate_size is None: + self.dp_replicate_size = int(os.environ.get("PARALLELISM_CONFIG_DP_REPLICATE_SIZE", "1")) + if self.dp_shard_size is None: + self.dp_shard_size = int(os.environ.get("PARALLELISM_CONFIG_DP_SHARD_SIZE", "1")) + if self.tp_size is None: + self.tp_size = int(os.environ.get("PARALLELISM_CONFIG_TP_SIZE", "1")) + if self.cp_size is None: + self.cp_size = int(os.environ.get("PARALLELISM_CONFIG_CP_SIZE", "1")) + + if self.tp_size > 1: + if self.tp_handler is None: + self.tp_handler = TorchTensorParallelConfig() + + if self.cp_size > 1: + if self.cp_handler is None: + self.cp_handler = TorchContextParallelConfig() + + if self.dp_replicate_size < 1: + raise ValueError(f"dp_replicate_size must be at least 1, but got {self.dp_replicate_size}") + if self.dp_shard_size < 1: + raise ValueError(f"dp_shard_size must be at least 1, but got {self.dp_shard_size}") + if self.tp_size < 1: + raise ValueError(f"tp_size must be at least 1, but got {self.tp_size}") + if self.cp_size < 1: + raise ValueError(f"cp_size must be at least 1, but got {self.cp_size}") + + if (self.tp_size > 1 or self.cp_size > 1) and self.dp_replicate_size > 1 and self.dp_shard_size == 1: + raise ValueError( + "Tensor/Context parallelism (tp/cp_size > 1) cannot be used with pure data parallelism (dp_replicate_size > 1 and dp_shard_size == 1). " + "Please set dp_shard_size > 1 and dp_replicate_size == 1 to compose FSDP + TP/CP for 2D parallel, " + "or set dp_replicate_size == 1 and dp_shard_size > 1 to compose HSDP + TP/CP for 3D parallel." + ) + self._sizes = { + "dp_replicate": self.dp_replicate_size, + "dp_shard": self.dp_shard_size, + "tp": self.tp_size, + "cp": self.cp_size, + } + + def _set_size(self, parallelism: str, size: int): + assert parallelism in self._sizes.keys(), f"Parallelism must be one of {self._sizes.keys()}" + self._sizes[parallelism] = size + setattr(self, f"{parallelism}_size", size) + + def _validate_accelerator(self, accelerator: "Accelerator"): + _warnings = set() + if not accelerator.multi_device and self.total_size == 1: + # No distributed setup, valid parallelism config + return + + # We need this to ensure DDP works + if self.total_size == 1: + self._set_size("dp_replicate", accelerator.num_processes) + + if self.total_size != accelerator.num_processes: + raise ValueError( + f"ParallelismConfig total_size ({self.total_size}) does not match " + f"num_processes ({accelerator.num_processes}). Please adjust dp_replicate_size/ " + f"dp_shard_size/tp_size/cp_size." + ) + + if self.total_size > 1 and not (accelerator.is_fsdp2 or accelerator.multi_device): + raise ValueError( + f"ParallelismConfig is only compatible DistributedType.FSDP (version 2) or DistributedType.Multi{{Device}}, but got {accelerator.distributed_type}." + ) + + for parallelism, size in self._sizes.items(): + if size == 1 and getattr(self, f"{parallelism}_handler", None) is not None: + _warnings.add( + f"ParallelismConfig.{parallelism}_handler is set, but {parallelism}_size is set to 1. This handler will be ignored." + ) + + if _warnings and accelerator.is_main_process: + warnings.warn( + "ParallelismConfig has the following warnings:\n" + "\n".join(_warnings), + UserWarning, + ) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/scheduler.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..1fa8a13f238afd7b908ee8e8cb8e0620f48d4ff8 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/scheduler.py @@ -0,0 +1,98 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation + +import warnings + +from .state import AcceleratorState, GradientState + + +warnings.filterwarnings("ignore", category=UserWarning, module="torch.optim.lr_scheduler") + + +class AcceleratedScheduler: + """ + A wrapper around a learning rate scheduler that will only step when the optimizer(s) have a training step. Useful + to avoid making a scheduler step too fast when gradients went overflow and there was no training step (in mixed + precision training) + + When performing gradient accumulation scheduler lengths should not be changed accordingly, Accelerate will always + step the scheduler to account for it. + + Args: + scheduler (`torch.optim.lr_scheduler._LRScheduler`): + The scheduler to wrap. + optimizers (one or a list of `torch.optim.Optimizer`): + The optimizers used. + step_with_optimizer (`bool`, *optional*, defaults to `True`): + Whether or not the scheduler should be stepped at each optimizer step. + split_batches (`bool`, *optional*, defaults to `False`): + Whether or not the dataloaders split one batch across the different processes (so batch size is the same + regardless of the number of processes) or create batches on each process (so batch size is the original + batch size multiplied by the number of processes). + """ + + def __init__(self, scheduler, optimizers, step_with_optimizer: bool = True, split_batches: bool = False): + self.scheduler = scheduler + self.optimizers = optimizers if isinstance(optimizers, (list, tuple)) else [optimizers] + self.split_batches = split_batches + self.step_with_optimizer = step_with_optimizer + self.gradient_state = GradientState() + + def step(self, *args, **kwargs): + if not self.step_with_optimizer: + # No link between scheduler and optimizer -> just step + self.scheduler.step(*args, **kwargs) + return + + # Otherwise, first make sure the optimizer was stepped. + if not self.gradient_state.sync_gradients: + if self.gradient_state.adjust_scheduler: + self.scheduler._step_count += 1 + return + + for opt in self.optimizers: + if opt.step_was_skipped: + return + if self.split_batches: + # Split batches -> the training dataloader batch size is not changed so one step per training step + self.scheduler.step(*args, **kwargs) + else: + # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do + # num_processes steps per training step + num_processes = AcceleratorState().num_processes + for _ in range(num_processes): + # Special case when using OneCycle and `drop_last` was not used + if hasattr(self.scheduler, "total_steps"): + if self.scheduler._step_count <= self.scheduler.total_steps: + self.scheduler.step(*args, **kwargs) + else: + self.scheduler.step(*args, **kwargs) + + # Passthroughs + def get_last_lr(self): + return self.scheduler.get_last_lr() + + def state_dict(self): + return self.scheduler.state_dict() + + def load_state_dict(self, state_dict): + self.scheduler.load_state_dict(state_dict) + + def get_lr(self): + return self.scheduler.get_lr() + + def print_lr(self, *args, **kwargs): + return self.scheduler.print_lr(*args, **kwargs) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/state.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/state.py new file mode 100644 index 0000000000000000000000000000000000000000..c6df0353bd357c7a435ba5aec44cf33d32586abf --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/state.py @@ -0,0 +1,1369 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import logging +import os +import threading +import warnings +import weakref +from contextlib import contextmanager +from functools import partial +from typing import Any, Callable + +import torch + +from .utils import ( + DistributedType, + DynamoBackend, + GradientAccumulationPlugin, + check_cuda_fp8_capability, + check_cuda_p2p_ib_support, + deepspeed_required, + get_cpu_distributed_information, + get_int_from_env, + is_ccl_available, + is_datasets_available, + is_deepspeed_available, + is_fp8_available, + is_habana_gaudi1, + is_hpu_available, + is_ipex_available, + is_mlu_available, + is_mps_available, + is_musa_available, + is_npu_available, + is_sdaa_available, + is_torch_xla_available, + is_xccl_available, + is_xpu_available, + parse_choice_from_env, + parse_flag_from_env, + set_numa_affinity, +) +from .utils.dataclasses import SageMakerDistributedType + + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + import torch_xla.runtime as xr + +if is_mlu_available(check_device=False): + import torch_mlu # noqa: F401 + +if is_sdaa_available(check_device=False): + import torch_sdaa # noqa: F401 + +if is_musa_available(check_device=False): + import torch_musa # noqa: F401 + +if is_npu_available(check_device=False): + import torch_npu # noqa: F401 + + +logger = logging.getLogger(__name__) + + +def is_initialized() -> bool: + """ + Checks if the `AcceleratorState` has been initialized from `Accelerator`. Same as `AcceleratorState.initialized`, + but works as a module method. + """ + return AcceleratorState._shared_state != {} + + +# Lambda function that does nothing +def do_nothing(*args, **kwargs): + return None + + +class ThreadLocalSharedDict(threading.local): + """ + Descriptor that holds a dict shared between instances of a class in the same thread. + + Note: Descriptors have slightly different semantics than just a dict field on its own. + `PartialState(...)._shared_state` and `PartialState._shared_state` (instance vs class) give the same value: the + underlying _storage dict. Likewise, `PartialState(...)._shared_state = {...}` overrides the _storage dict inside + the descriptor as you would expect. However, `PartialState._shared_state = {}` actually replaces the descriptor + object with a dict instead Thus, you should modify the _storage dict in-place (e.g. `_shared_state.clear()`). + + See Python documentation for an explanation of descriptors: https://docs.python.org/3/howto/descriptor.html + + This is required for using PyTorch/XLA with PJRT in multithreaded mode (required for TPU v2 and v3). + + See https://github.com/pytorch/xla/blob/r2.0/docs/pjrt.md#multithreading-on-tpu-v2v3 + """ + + def __init__(self, thread_local: bool = False): + self._storage = {} + + def __get__(self, obj, objtype=None): + return self._storage + + def __set__(self, obj, value): + self._storage = value + + +# Prefer global shared dictionary, except when using TPU. +SharedDict = dict if not is_torch_xla_available() else ThreadLocalSharedDict + + +# Inspired by Alex Martelli's 'Borg'. +class PartialState: + """ + Singleton class that has information about the current training environment and functions to help with process + control. Designed to be used when only process control and device execution states are needed. Does *not* need to + be initialized from `Accelerator`. + + Args: + cpu (`bool`, *optional*): + Whether or not to force the script to execute on CPU. Will ignore any accelerators available if set to + `True` and force the execution on the CPU. + kwargs (additional keyword arguments, *optional*): + Additional keyword arguments to pass to the relevant `init_process_group` function. Valid `kwargs` can be + found in [`utils.InitProcessGroupKwargs`]. See the example section for detailed usage. + + **Available attributes:** + + - **device** (`torch.device`) -- The device to use. + - **distributed_type** ([`~accelerate.state.DistributedType`]) -- The type of distributed environment currently + in use. + - **local_process_index** (`int`) -- The index of the current process on the current server. + - **mixed_precision** (`str`) -- Whether or not the current script will use mixed precision, and if so the type + of mixed precision being performed. (Choose from 'no','fp16','bf16 or 'fp8'). + - **num_processes** (`int`) -- The number of processes currently launched in parallel. + - **process_index** (`int`) -- The index of the current process. + - **is_last_process** (`bool`) -- Whether or not the current process is the last one. + - **is_main_process** (`bool`) -- Whether or not the current process is the main one. + - **is_local_main_process** (`bool`) -- Whether or not the current process is the main one on the local node. + - **debug** (`bool`) -- Whether or not the current script is being run in debug mode. + + Example: + ```python + from accelerate.utils import InitProcessGroupKwargs + + # To include `InitProcessGroupKwargs`, init then call `.to_kwargs()` + kwargs = InitProcessGroupKwargs(...).to_kwargs() + state = PartialState(**kwargs) + ``` + """ + + _shared_state = SharedDict() + _known_attrs = [ + "_cpu", + "_mixed_precision", + "_shared_state", + "backend", + "debug", + "device", + "distributed_type", + "fork_launched", + "local_process_index", + "num_processes", + "process_index", + ] + + def __init__(self, cpu: bool = False, **kwargs): + self.__dict__ = self._shared_state + if not self.initialized: + self._cpu = cpu + self.backend = None + self.parallelism_config = kwargs.pop("parallelism_config", None) + self.device_mesh = kwargs.pop("device_mesh", None) + env_device = os.environ.get("ACCELERATE_TORCH_DEVICE", None) + self.device = torch.device(env_device) if env_device is not None else None + self.debug = parse_flag_from_env("ACCELERATE_DEBUG_MODE") + use_sagemaker_dp = kwargs.pop("_use_sagemaker_dp", None) + dist_information = None + if use_sagemaker_dp is None: + use_sagemaker_dp = ( + os.environ.get("ACCELERATE_USE_SAGEMAKER", "false").lower() == "true" + and os.environ.get("ACCELERATE_SAGEMAKER_DISTRIBUTED_TYPE") != SageMakerDistributedType.NO + ) + + # Sets up self.backend + imports + original_backend = kwargs.pop("backend", None) + backend, distributed_type = self._prepare_backend(cpu, use_sagemaker_dp, original_backend) + if original_backend is not None and backend != original_backend: + raise ValueError(f"Your assigned backend {original_backend} is not avaliable, please use {backend}") + self.backend = backend + self.distributed_type = distributed_type + use_deepspeed = False + if not cpu and self.backend != "xla": + if int(os.environ.get("LOCAL_RANK", -1)) != -1: + # Deal with spawning deepspeed + if os.environ.get("ACCELERATE_USE_DEEPSPEED", "false").lower() == "true": + if not is_deepspeed_available(): + raise ImportError( + "DeepSpeed is not available => install it using `pip3 install deepspeed` or build it from source" + ) + from deepspeed import comm as dist + + if not dist.is_initialized(): + if self.backend == "tccl": + local_rank = os.environ.get("LOCAL_RANK", -1) + torch.sdaa.set_device(f"sdaa:{local_rank}") + dist.init_distributed(dist_backend=self.backend, auto_mpi_discovery=False, **kwargs) + # We need to flag to `use_deepspeed` to be True to override `distributed_type` later + use_deepspeed = True + # Deal with all other backends but XPU and CPU, that gets handled special later + elif ( + self.distributed_type not in (DistributedType.MULTI_XPU, DistributedType.MULTI_CPU) + and not torch.distributed.is_initialized() + ): + if self.backend == "tccl": + local_rank = os.environ.get("LOCAL_RANK", -1) + torch.sdaa.set_device(f"sdaa:{local_rank}") + if ( + self.backend == "nccl" + and os.environ.get("ACCELERATE_USE_FSDP", "false").lower() == "true" + and ( + os.environ.get("FSDP_OFFLOAD_PARAMS", "false").lower() == "true" + or os.environ.get("FSDP_STATE_DICT_TYPE", "SHARDED_STATE_DICT") == "FULL_STATE_DICT" + ) + ): + self.backend = "cuda:nccl,cpu:gloo" + torch.distributed.init_process_group(backend=self.backend, **kwargs) + + # XPU and CPU require special env configs to be set + if self.distributed_type in (DistributedType.MULTI_XPU, DistributedType.MULTI_CPU): + dist_information = get_cpu_distributed_information() + os.environ["RANK"] = str(dist_information.rank) + os.environ["WORLD_SIZE"] = str(dist_information.world_size) + os.environ["LOCAL_RANK"] = str(dist_information.local_rank) + os.environ["LOCAL_WORLD_SIZE"] = str(dist_information.local_world_size) + if not os.environ.get("MASTER_PORT", None): + os.environ["MASTER_PORT"] = "29500" + if ( + not os.environ.get("MASTER_ADDR", None) + and dist_information.local_world_size != dist_information.world_size + and self.backend != "mpi" + ): + raise ValueError( + "Tried to launch on distributed with multinode, but `MASTER_ADDR` env was not set, " + "please try exporting rank 0's hostname as `MASTER_ADDR`" + ) + kwargs["rank"] = dist_information.rank + kwargs["world_size"] = dist_information.world_size + + if ( + self.distributed_type == DistributedType.MULTI_CPU + and get_int_from_env(["OMP_NUM_THREADS"], 0) == 0 + ): + import psutil + + num_cpu_threads_per_process = int( + psutil.cpu_count(logical=False) / dist_information.local_world_size + ) + if num_cpu_threads_per_process == 0: + num_cpu_threads_per_process = 1 + torch.set_num_threads(num_cpu_threads_per_process) + warnings.warn( + f"OMP_NUM_THREADS/MKL_NUM_THREADS unset, we set it at {num_cpu_threads_per_process} to improve oob" + " performance." + ) + + if not torch.distributed.is_initialized(): + torch.distributed.init_process_group(backend=self.backend, **kwargs) + + # No backend == no distributed training + if self.backend is None: + self.distributed_type = DistributedType.NO + self.num_processes = 1 + self.process_index = 0 + self.local_process_index = 0 + elif self.backend == "xla": + # XLA needs device setting first for `set_replication` + self.set_device() + xm.set_replication(self.device, xm.get_xla_supported_devices()) + self.num_processes = xr.world_size() + self.process_index = xr.global_ordinal() + if is_torch_xla_available(check_is_tpu=True): + self.local_process_index = xm.get_local_ordinal() + else: + self.local_process_index = int(os.environ.get("LOCAL_RANK", -1)) + else: + self.num_processes = torch.distributed.get_world_size() + self.process_index = torch.distributed.get_rank() + self.local_process_index = ( + int(os.environ.get("LOCAL_RANK", -1)) if dist_information is None else dist_information.local_rank + ) + self.set_device() + # Now we can change to deepseed + if use_deepspeed: + self.distributed_type = DistributedType.DEEPSPEED + + # Set CPU affinity if enabled + if parse_flag_from_env("ACCELERATE_CPU_AFFINITY", False): + set_numa_affinity(self.local_process_index) + + # Check for old RTX 4000's that can't use P2P or IB and are on old drivers + if self.device.type == "cuda" and not check_cuda_p2p_ib_support(): + if "NCCL_P2P_DISABLE" not in os.environ or "NCCL_IB_DISABLE" not in os.environ: + raise NotImplementedError( + "Using RTX 4000 series doesn't support faster communication broadband via P2P or IB. " + 'Please set `NCCL_P2P_DISABLE="1"` and `NCCL_IB_DISABLE="1" or use `accelerate launch` which ' + "will do this automatically." + ) + + # Important: This should be the *only* code outside of `self.initialized!` + self.fork_launched = parse_flag_from_env("FORK_LAUNCHED", 0) + + def __repr__(self) -> str: + return ( + f"Distributed environment: {self.distributed_type}{(' Backend: ' + self.backend) if self.backend else ''}\n" + f"Num processes: {self.num_processes}\n" + f"Process index: {self.process_index}\n" + f"Local process index: {self.local_process_index}\n" + f"Device: {self.device}\n" + ) + + @staticmethod + def _reset_state(): + "Resets `_shared_state`, is used internally and should not be called" + PartialState._shared_state.clear() + + @property + def initialized(self) -> bool: + "Returns whether the `PartialState` has been initialized" + return self._shared_state != {} + + @property + def use_distributed(self): + """ + Whether the Accelerator is configured for distributed training + """ + return self.distributed_type != DistributedType.NO and self.num_processes > 1 + + @property + def is_last_process(self) -> bool: + "Returns whether the current process is the last one" + return self.process_index == self.num_processes - 1 + + @property + def is_main_process(self) -> bool: + "Returns whether the current process is the main process" + return ( + self.process_index == 0 if self.distributed_type != DistributedType.MEGATRON_LM else self.is_last_process + ) + + @property + def is_local_main_process(self) -> bool: + "Returns whether the current process is the main process on the local node" + return ( + self.local_process_index == 0 + if self.distributed_type != DistributedType.MEGATRON_LM + else self.is_last_process + ) + + def wait_for_everyone(self): + """ + Will stop the execution of the current process until every other process has reached that point (so this does + nothing when the script is only run in one process). Useful to do before saving a model. + + Example: + + ```python + >>> # Assuming two GPU processes + >>> import time + >>> from accelerate.state import PartialState + + >>> state = PartialState() + >>> if state.is_main_process: + ... time.sleep(2) + >>> else: + ... print("I'm waiting for the main process to finish its sleep...") + >>> state.wait_for_everyone() + >>> # Should print on every process at the same time + >>> print("Everyone is here") + ``` + """ + if self.distributed_type in ( + DistributedType.MULTI_GPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_SDAA, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_NPU, + DistributedType.MULTI_XPU, + DistributedType.MULTI_CPU, + DistributedType.MULTI_HPU, + DistributedType.DEEPSPEED, + DistributedType.FSDP, + ): + torch.distributed.barrier() + elif self.distributed_type == DistributedType.XLA: + xm.rendezvous("accelerate.utils.wait_for_everyone") + + def _goes_first(self, is_main: bool): + if not is_main: + self.wait_for_everyone() + + yield + + if is_main: + self.wait_for_everyone() + + @contextmanager + def split_between_processes(self, inputs: list | tuple | dict | torch.Tensor, apply_padding: bool = False): + """ + Splits `input` between `self.num_processes` quickly and can be then used on that process. Useful when doing + distributed inference, such as with different prompts. + + Note that when using a `dict`, all keys need to have the same number of elements. + + Args: + inputs (`list`, `tuple`, `torch.Tensor`, `dict` of `list`/`tuple`/`torch.Tensor`, or `datasets.Dataset`): + The input to split between processes. + apply_padding (`bool`, `optional`, defaults to `False`): + Whether to apply padding by repeating the last element of the input so that all processes have the same + number of elements. Useful when trying to perform actions such as `gather()` on the outputs or passing + in less inputs than there are processes. If so, just remember to drop the padded elements afterwards. + + + Example: + + ```python + # Assume there are two processes + from accelerate import PartialState + + state = PartialState() + with state.split_between_processes(["A", "B", "C"]) as inputs: + print(inputs) + # Process 0 + ["A", "B"] + # Process 1 + ["C"] + + with state.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs: + print(inputs) + # Process 0 + ["A", "B"] + # Process 1 + ["C", "C"] + ``` + """ + if self.num_processes == 1: + yield inputs + return + length = len(inputs) + # Nested dictionary of any types + if isinstance(inputs, dict): + length = len(inputs[list(inputs.keys())[0]]) + if not all(len(v) == length for v in inputs.values()): + raise ValueError("All values in the dictionary must have the same length") + num_samples_per_process, num_extras = divmod(length, self.num_processes) + start_index = self.process_index * num_samples_per_process + min(self.process_index, num_extras) + end_index = start_index + num_samples_per_process + (1 if self.process_index < num_extras else 0) + + def _split_values(inputs, start_index, end_index): + if isinstance(inputs, (list, tuple, torch.Tensor)): + if start_index >= len(inputs): + result = inputs[-1:] + else: + result = inputs[start_index:end_index] + if apply_padding: + if isinstance(result, torch.Tensor): + from accelerate.utils import pad_across_processes, send_to_device + + # The tensor needs to be on the device before we can pad it + tensorized_result = send_to_device(result, self.device) + result = pad_across_processes(tensorized_result, pad_index=inputs[-1]) + else: + result += [result[-1]] * (num_samples_per_process + (1 if num_extras > 0 else 0) - len(result)) + return result + elif isinstance(inputs, dict): + for key in inputs.keys(): + inputs[key] = _split_values(inputs[key], start_index, end_index) + return inputs + else: + if is_datasets_available(): + from datasets import Dataset + + if isinstance(inputs, Dataset): + if start_index >= len(inputs): + start_index = len(inputs) - 1 + if end_index > len(inputs): + end_index = len(inputs) + result_idcs = list(range(start_index, end_index)) + if apply_padding: + result_idcs += [end_index - 1] * ( + num_samples_per_process + (1 if num_extras > 0 else 0) - len(result_idcs) + ) + return inputs.select(result_idcs) + return inputs + + yield _split_values(inputs, start_index, end_index) + + @contextmanager + def main_process_first(self): + """ + Lets the main process go first inside a with block. + + The other processes will enter the with block after the main process exits. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> with accelerator.main_process_first(): + ... # This will be printed first by process 0 then in a seemingly + ... # random order by the other processes. + ... print(f"This will be printed by process {accelerator.process_index}") + ``` + """ + yield from self._goes_first(self.is_main_process) + + @contextmanager + def local_main_process_first(self): + """ + Lets the local main process go inside a with block. + + The other processes will enter the with block after the main process exits. + + Example: + + ```python + >>> from accelerate.state import PartialState + + >>> state = PartialState() + >>> with state.local_main_process_first(): + ... # This will be printed first by local process 0 then in a seemingly + ... # random order by the other processes. + ... print(f"This will be printed by process {state.local_process_index}") + ``` + """ + yield from self._goes_first(self.is_local_main_process) + + def on_main_process(self, function: Callable[..., Any] = None): + """ + Decorator that only runs the decorated function on the main process. + + Args: + function (`Callable`): The function to decorate. + + Example: + + ```python + >>> from accelerate.state import PartialState + + >>> state = PartialState() + + + >>> @state.on_main_process + ... def print_something(): + ... print("This will be printed by process 0 only.") + + + >>> print_something() + "This will be printed by process 0 only" + ``` + """ + if not self.initialized: + raise ValueError("The `PartialState` or `Accelerator` must be initialized before calling this function.") + if self.is_main_process or not self.use_distributed: + return function + return do_nothing + + def on_local_main_process(self, function: Callable[..., Any] = None): + """ + Decorator that only runs the decorated function on the local main process. + + Args: + function (`Callable`): The function to decorate. + + Example: + ```python + # Assume we have 2 servers with 4 processes each. + from accelerate.state import PartialState + + state = PartialState() + + + @state.on_local_main_process + def print_something(): + print("This will be printed by process 0 only on each server.") + + + print_something() + # On server 1: + "This will be printed by process 0 only" + # On server 2: + "This will be printed by process 0 only" + ``` + """ + if self.is_local_main_process or not self.use_distributed: + return function + return do_nothing + + def on_last_process(self, function: Callable[..., Any]): + """ + Decorator that only runs the decorated function on the last process. + + Args: + function (`Callable`): The function to decorate. + + Example: + ```python + # Assume we have 4 processes. + from accelerate.state import PartialState + + state = PartialState() + + + @state.on_last_process + def print_something(): + print(f"Printed on process {state.process_index}") + + + print_something() + "Printed on process 3" + ``` + """ + if self.is_last_process or not self.use_distributed: + return function + return do_nothing + + def on_process(self, function: Callable[..., Any] = None, process_index: int = None): + """ + Decorator that only runs the decorated function on the process with the given index. + + Args: + function (`Callable`, `optional`): + The function to decorate. + process_index (`int`, `optional`): + The index of the process on which to run the function. + + Example: + ```python + # Assume we have 4 processes. + from accelerate.state import PartialState + + state = PartialState() + + + @state.on_process(process_index=2) + def print_something(): + print(f"Printed on process {state.process_index}") + + + print_something() + "Printed on process 2" + ``` + """ + if function is None: + return partial(self.on_process, process_index=process_index) + if (self.process_index == process_index) or (not self.use_distributed): + return function + return do_nothing + + def on_local_process(self, function: Callable[..., Any] = None, local_process_index: int = None): + """ + Decorator that only runs the decorated function on the process with the given index on the current node. + + Args: + function (`Callable`, *optional*): + The function to decorate. + local_process_index (`int`, *optional*): + The index of the local process on which to run the function. + + Example: + ```python + # Assume we have 2 servers with 4 processes each. + from accelerate import Accelerator + + accelerator = Accelerator() + + + @accelerator.on_local_process(local_process_index=2) + def print_something(): + print(f"Printed on process {accelerator.local_process_index}") + + + print_something() + # On server 1: + "Printed on process 2" + # On server 2: + "Printed on process 2" + ``` + """ + if function is None: + return partial(self.on_local_process, local_process_index=local_process_index) + if (self.local_process_index == local_process_index) or (not self.use_distributed): + return function + return do_nothing + + def print(self, *args, **kwargs): + if self.is_local_main_process: + print(*args, **kwargs) + + @property + def default_device(self) -> torch.device: + """ + Returns the default device which is: + - MPS if `torch.backends.mps.is_available()` and `torch.backends.mps.is_built()` both return True. + - CUDA if `torch.cuda.is_available()` + - MLU if `is_mlu_available()` + - SDAA if `is_sdaa_available()` + - MUSA if `is_musa_available()` + - NPU if `is_npu_available()` + - HPU if `is_hpu_available()` + - CPU otherwise + """ + if is_mps_available(): + os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" + return torch.device("mps") + elif is_mlu_available(): + return torch.device("mlu") + elif is_sdaa_available(): + return torch.device("sdaa") + elif is_musa_available(): + return torch.device("musa") + # NPU should be checked before CUDA when using `transfer_to_npu` + # See issue #3020: https://github.com/huggingface/accelerate/issues/3020 + elif is_npu_available(): + return torch.device("npu") + elif is_hpu_available(): + return torch.device("hpu") + elif torch.cuda.is_available(): + return torch.device("cuda") + elif is_xpu_available(): + return torch.device("xpu") + else: + return torch.device("cpu") + + def _prepare_backend( + self, cpu: bool = False, sagemaker_dp=False, backend: str = None + ) -> tuple[str, DistributedType]: + "Prepares any imports needed before initializing the distributed backend and sets `self.backend` properly" + distributed_type = None + if sagemaker_dp: + import smdistributed.dataparallel.torch.torch_smddp # noqa + + backend = "smddp" + distributed_type = DistributedType.MULTI_GPU + elif is_torch_xla_available(): + backend = "xla" + distributed_type = DistributedType.XLA + + elif int(os.environ.get("LOCAL_RANK", -1)) != -1 and not cpu: + if is_mlu_available(): + backend = "cncl" + distributed_type = DistributedType.MULTI_MLU + if is_sdaa_available(): + backend = "tccl" + distributed_type = DistributedType.MULTI_SDAA + elif is_musa_available(): + backend = "mccl" + distributed_type = DistributedType.MULTI_MUSA + # NPU should be checked before CUDA when using `transfer_to_npu` + # See issue #3020: https://github.com/huggingface/accelerate/issues/3020 + elif is_npu_available(): + backend = "hccl" + distributed_type = DistributedType.MULTI_NPU + elif is_hpu_available(init_hccl=True): + if backend is None: + backend = "hccl" + distributed_type = DistributedType.MULTI_HPU + elif torch.cuda.is_available(): + if backend is None: + backend = "nccl" + distributed_type = DistributedType.MULTI_GPU + elif is_xpu_available() and is_xccl_available(): + if backend is None: + backend = "xccl" + distributed_type = DistributedType.MULTI_XPU + + if distributed_type is None and ( + int(os.environ.get("LOCAL_RANK", -1)) != -1 + or get_int_from_env(["PMI_SIZE", "OMPI_COMM_WORLD_SIZE", "MV2_COMM_WORLD_SIZE", "WORLD_SIZE"], 1) > 1 + ): + if not cpu and is_xpu_available(): + distributed_type = DistributedType.MULTI_XPU + else: + distributed_type = DistributedType.MULTI_CPU + + if ( + backend in (None, "ccl") + and is_ccl_available() + and (get_int_from_env(["CCL_WORKER_COUNT"], 0) > 0 or distributed_type == DistributedType.MULTI_XPU) + ): + import oneccl_bindings_for_pytorch # noqa: F401 + + backend = "ccl" + elif backend in (None, "mpi") and torch.distributed.is_mpi_available(): + backend = "mpi" + else: + backend = "gloo" + if distributed_type is None: + distributed_type = DistributedType.NO + + return backend, distributed_type + + def set_device(self): + """ + Sets the device in `self.device` to the current distributed environment. + """ + if self.device is not None: + return + if self.distributed_type == DistributedType.NO: + self.device = torch.device("cpu") if self._cpu else self.default_device + return + device = str(self.distributed_type).split(".")[-1].replace("MULTI_", "").lower() + if device not in ("cpu", "gpu", "mlu", "musa", "npu", "xpu", "xla", "hpu", "sdaa"): + raise ValueError( + f"Can't set device for {self.distributed_type} ({device}), verify we should be calling `_set_device()` for it!" + ) + if device == "xla": + self.device = xm.xla_device() + elif device == "hpu": + self.device = torch.device("hpu", torch.hpu.current_device()) + else: + if device == "gpu": + device = "cuda" + device_module = getattr(torch, device) + device_index = self.local_process_index % device_module.device_count() + self.device = torch.device(device, device_index) + device_module.set_device(self.device) + + def destroy_process_group(self, group=None): + """ + Destroys the process group. If one is not specified, the default process group is destroyed. + """ + if self.fork_launched and group is None: + return + # needed when using torch.distributed.init_process_group + if torch.distributed.is_initialized(): + torch.distributed.destroy_process_group(group) + + def __getattr__(self, name: str): + # By this point we know that no attributes of `self` contain `name`, + # so we just modify the error message + if name in self._known_attrs: + raise AttributeError( + f"`PartialState` object has no attribute `{name}`. " + "This happens if `PartialState._reset_state()` was called and " + "an `Accelerator` or `PartialState` was not reinitialized." + ) + # Raise a typical AttributeError + raise AttributeError(f"'PartialState' object has no attribute '{name}'") + + +class AcceleratorState: + """ + Singleton class that has information about the current training environment. + + **Available attributes:** + + - **device** (`torch.device`) -- The device to use. + - **distributed_type** ([`~accelerate.state.DistributedType`]) -- The type of distributed environment currently + in use. + - **parallelism_config** ([`~accelerate.utils.ParallelismConfig`]) -- The parallelism configuration for the + current training environment. This is used to configure the distributed training environment. + - **initialized** (`bool`) -- Whether or not the `AcceleratorState` has been initialized from `Accelerator`. + - **local_process_index** (`int`) -- The index of the current process on the current server. + - **mixed_precision** (`str`) -- Whether or not the current script will use mixed precision, and if so the type + of mixed precision being performed. (Choose from 'no','fp16','bf16 or 'fp8'). + - **num_processes** (`int`) -- The number of processes currently launched in parallel. + - **process_index** (`int`) -- The index of the current process. + - **is_last_process** (`bool`) -- Whether or not the current process is the last one. + - **is_main_process** (`bool`) -- Whether or not the current process is the main one. + - **is_local_main_process** (`bool`) -- Whether or not the current process is the main one on the local node. + - **debug** (`bool`) -- Whether or not the current script is being run in debug mode. + """ + + _shared_state = SharedDict() + _known_attrs = PartialState._known_attrs + [ + "deepspeed_plugin", + "use_ipex", + "fsdp_plugin", + "megatron_lm_plugin", + "dynamo_plugin", + ] + + def __init__( + self, + mixed_precision: str = None, + cpu: bool = False, + dynamo_plugin=None, + deepspeed_plugin=None, + fsdp_plugin=None, + torch_tp_plugin=None, + megatron_lm_plugin=None, + parallelism_config=None, + _from_accelerator: bool = False, + **kwargs, + ): + self.__dict__ = self._shared_state + if parse_flag_from_env("ACCELERATE_USE_CPU"): + cpu = True + if PartialState._shared_state == {}: + PartialState(cpu, **kwargs) + self.__dict__.update(PartialState._shared_state) + self._check_initialized(mixed_precision, cpu) + if not self.initialized: + self.deepspeed_plugins = None + self.use_ipex = None + self.torch_tp_plugin = torch_tp_plugin + self.parallelism_config = parallelism_config + mixed_precision = ( + parse_choice_from_env("ACCELERATE_MIXED_PRECISION", "no") + if mixed_precision is None + else mixed_precision.lower() + ) + if mixed_precision == "fp8": + # this is confusing, why is is_fp8_available only checks for library availability ? + if not is_fp8_available(): + raise ValueError( + "Using `fp8` precision requires `transformer_engine` or `MS-AMP` to be installed." + ) + elif torch.cuda.is_available() and not check_cuda_fp8_capability(): + logger.warning( + f"The current device has compute capability of {torch.cuda.get_device_capability()} which is " + "insufficient for FP8 mixed precision training (requires a GPU Hopper/Ada Lovelace " + "or higher, compute capability of 8.9 or higher). Will use FP16 instead." + ) + mixed_precision = "fp16" + elif is_habana_gaudi1(): + logger.warning( + "The current HPU device is Gaudi1 which does not support FP8 mixed precision training (requires " + "Gaudi2 or higher). Will use BF16 instead." + ) + mixed_precision = "bf16" + + self.dynamo_plugin = dynamo_plugin + if not _from_accelerator: + raise ValueError( + "Please make sure to properly initialize your accelerator via `accelerator = Accelerator()` " + "before using any functionality from the `accelerate` library." + ) + # deepspeed handles mixed_precision using deepspeed_config + self._mixed_precision = "no" if self.distributed_type == DistributedType.DEEPSPEED else mixed_precision + if self.distributed_type == DistributedType.XLA and is_torch_xla_available(check_is_tpu=True): + if mixed_precision == "bf16": + if os.environ.get("ACCELERATE_DOWNCAST_BF16"): + os.environ["XLA_USE_BF16"] = str(0) + os.environ["XLA_DOWNCAST_BF16"] = str(1) + self.downcast_bfloat = True + else: + os.environ["XLA_USE_BF16"] = str(1) + os.environ["XLA_DOWNCAST_BF16"] = str(0) + self.downcast_bfloat = False + elif os.environ.get("ACCELERATE_USE_DEEPSPEED", "false").lower() == "true" and not cpu: + self.distributed_type = DistributedType.DEEPSPEED + if not isinstance(deepspeed_plugin, dict): + deepspeed_plugin.set_mixed_precision(mixed_precision) + deepspeed_plugin.select(_from_accelerator_state=True) + else: + for plugin in deepspeed_plugin.values(): + plugin.set_mixed_precision(mixed_precision) + # The first plugin passed in is always the active one + first_plugin = next(iter(deepspeed_plugin.values())) + first_plugin.select(_from_accelerator_state=True) + self.deepspeed_plugins = deepspeed_plugin + elif self.distributed_type in [ + DistributedType.MULTI_GPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_SDAA, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_NPU, + DistributedType.MULTI_XPU, + DistributedType.MULTI_HPU, + ]: + # TODO: Siro - remove when axolotl fixes their side + if not os.environ.get("ACCELERATE_ALLOW_CP_STANDALONE", "false").lower() == "true": + if self.parallelism_config and self.parallelism_config.cp_enabled and fsdp_plugin is None: + raise ValueError( + "`cp_size > 1` specified in the `parallelism_config`, but no `fsdp_plugin` was provided. We need a `fsdp_plugin` to use context parallelism, as we also shard the model across the device mesh to save more memory" + ) + if ( + self.parallelism_config is not None + and self.parallelism_config.cp_enabled + and fsdp_plugin.fsdp_version == 1 + ): + raise ValueError( + "Using `cp_size>1` requires FSDP2, but the provided `fsdp_plugin` is using FSDP1. " + ) + if (os.environ.get("ACCELERATE_USE_FSDP", "false").lower() == "true" or fsdp_plugin is not None) or ( + self.parallelism_config is not None and self.parallelism_config.cp_enabled + ): + self.distributed_type = DistributedType.FSDP + if self._mixed_precision != "no" and fsdp_plugin is not None: + fsdp_plugin.set_mixed_precision(self._mixed_precision) + self.fsdp_plugin = fsdp_plugin + if os.environ.get( + "ACCELERATE_USE_MEGATRON_LM", "false" + ).lower() == "true" and self.distributed_type not in [ + DistributedType.MULTI_XPU, + ]: + self.distributed_type = DistributedType.MEGATRON_LM + megatron_lm_plugin.set_mixed_precision(self._mixed_precision) + self.megatron_lm_plugin = megatron_lm_plugin + elif self.distributed_type in [DistributedType.MULTI_CPU, DistributedType.MULTI_XPU, DistributedType.NO]: + if is_ipex_available(): + # check if user disables it explicitly + self.use_ipex = parse_flag_from_env("ACCELERATE_USE_IPEX", default=True) + else: + self.use_ipex = False + if ( + self.dynamo_plugin.backend != DynamoBackend.NO + and self._mixed_precision == "no" + and self.device.type == "cuda" + ): + torch.backends.cuda.matmul.allow_tf32 = True + if ( + self.dynamo_plugin.backend != DynamoBackend.NO + and self._mixed_precision == "no" + and self.device.type == "musa" + ): + torch.backends.musa.matmul.allow_tf32 = True + PartialState._shared_state["distributed_type"] = self.distributed_type + + @property + def initialized(self) -> bool: + return self._shared_state != PartialState._shared_state + + def __repr__(self): + repr = PartialState().__repr__() + f"\nMixed precision type: {self.mixed_precision}\n" + if self.distributed_type == DistributedType.DEEPSPEED: + repr += f"ds_config: {self.deepspeed_plugin.deepspeed_config}\n" + return repr + + def _check_initialized(self, mixed_precision=None, cpu=None): + "Checks if a modification is trying to be made and the `AcceleratorState` has already been initialized" + if self.initialized: + err = "AcceleratorState has already been initialized and cannot be changed, restart your runtime completely and pass `{flag}` to `Accelerator()`." + if cpu and self.device.type != "cpu": + raise ValueError(err.format(flag="cpu=True")) + if ( + mixed_precision is not None + and mixed_precision != self._mixed_precision + and self.distributed_type != DistributedType.DEEPSPEED + ): + raise ValueError(err.format(flag=f"mixed_precision='{mixed_precision}'")) + + @property + def mixed_precision(self): + if self.distributed_type == DistributedType.DEEPSPEED: + config = self.deepspeed_plugin.deepspeed_config + if config.get("fp16", {}).get("enabled", False): + mixed_precision = "fp16" + elif config.get("bf16", {}).get("enabled", False): + mixed_precision = "bf16" + else: + mixed_precision = "no" + else: + mixed_precision = self._mixed_precision + return mixed_precision + + @staticmethod + def _reset_state(reset_partial_state: bool = False): + "Resets `_shared_state`, is used internally and should not be called" + AcceleratorState._shared_state.clear() + if reset_partial_state: + PartialState._reset_state() + + def destroy_process_group(self, group=None): + """ + Destroys the process group. If one is not specified, the default process group is destroyed. + + If `self.fork_lauched` is `True` and `group` is `None`, nothing happens. + """ + PartialState().destroy_process_group(group) + + @property + def fork_launched(self): + return PartialState().fork_launched + + @property + def use_distributed(self): + """ + Whether the Accelerator is configured for distributed training + """ + return PartialState().use_distributed + + @property + def is_fsdp2(self) -> bool: + return self.distributed_type == DistributedType.FSDP and self.fsdp_plugin.fsdp_version == 2 + + @property + def is_last_process(self) -> bool: + "Returns whether the current process is the last one" + return PartialState().is_last_process + + @property + def is_main_process(self) -> bool: + "Returns whether the current process is the main process" + return PartialState().is_main_process + + @property + def is_local_main_process(self) -> bool: + "Returns whether the current process is the main process on the local node" + return PartialState().is_local_main_process + + def wait_for_everyone(self): + PartialState().wait_for_everyone() + + @contextmanager + def split_between_processes(self, inputs: list | tuple | dict | torch.Tensor, apply_padding: bool = False): + """ + Splits `input` between `self.num_processes` quickly and can be then used on that process. Useful when doing + distributed inference, such as with different prompts. + + Note that when using a `dict`, all keys need to have the same number of elements. + + Args: + inputs (`list`, `tuple`, `torch.Tensor`, or `dict` of `list`/`tuple`/`torch.Tensor`): + The input to split between processes. + apply_padding (`bool`, `optional`, defaults to `False`): + Whether to apply padding by repeating the last element of the input so that all processes have the same + number of elements. Useful when trying to perform actions such as `gather()` on the outputs or passing + in less inputs than there are processes. If so, just remember to drop the padded elements afterwards. + + + Example: + + ```python + # Assume there are two processes + from accelerate.state import AcceleratorState + + state = AcceleratorState() + with state.split_between_processes(["A", "B", "C"]) as inputs: + print(inputs) + # Process 0 + ["A", "B"] + # Process 1 + ["C"] + + with state.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs: + print(inputs) + # Process 0 + ["A", "B"] + # Process 1 + ["C", "C"] + ``` + """ + with PartialState().split_between_processes(inputs, apply_padding=apply_padding) as inputs: + yield inputs + + @contextmanager + def main_process_first(self): + """ + Lets the main process go first inside a with block. + + The other processes will enter the with block after the main process exits. + """ + with PartialState().main_process_first(): + yield + + @contextmanager + def local_main_process_first(self): + """ + Lets the local main process go inside a with block. + + The other processes will enter the with block after the main process exits. + """ + with PartialState().local_main_process_first(): + yield + + @property + def deepspeed_plugin(self): + """ + Returns the currently active DeepSpeedPlugin. + + If not using deepspeed, returns `None`. + """ + # To maintain original behavior, return None if not using deepspeed. + if self.distributed_type != DistributedType.DEEPSPEED: + return None + from accelerate.utils.deepspeed import get_active_deepspeed_plugin + + return get_active_deepspeed_plugin(self) + + @deepspeed_required + def get_deepspeed_plugin(self, name: str): + """ + Returns the DeepSpeedPlugin with the given plugin_key. + """ + return self.deepspeed_plugins[name] + + @deepspeed_required + def select_deepspeed_plugin(self, name: str = None): + """ + Activates the DeepSpeedPlugin with the given `name`, and will disable all other plugins. + """ + for key, plugin in self.deepspeed_plugins.items(): + if key != name: + plugin._unselect() + self.deepspeed_plugins[name].select(_from_accelerator_state=True) + + def print(self, *args, **kwargs): + PartialState().print(*args, **kwargs) + + def __getattr__(self, name: str): + # By this point we know that no attributes of `self` contain `name`, + # so we just modify the error message + if name in self._known_attrs: + raise AttributeError( + f"`AcceleratorState` object has no attribute `{name}`. " + "This happens if `AcceleratorState._reset_state()` was called and " + "an `Accelerator` or `PartialState` was not reinitialized." + ) + # Raise a typical AttributeError + raise AttributeError(f"'AcceleratorState' object has no attribute '{name}'") + + +class GradientState: + """ + Singleton class that has information related to gradient synchronization for gradient accumulation + + **Available attributes:** + + - **end_of_dataloader** (`bool`) -- Whether we have reached the end the current dataloader + - **remainder** (`int`) -- The number of extra samples that were added from padding the dataloader + - **sync_gradients** (`bool`) -- Whether the gradients should be synced across all devices + - **active_dataloader** (`Optional[DataLoader]`) -- The dataloader that is currently being iterated over + - **dataloader_references** (`List[Optional[DataLoader]]`) -- A list of references to the dataloaders that are + being iterated over + - **num_steps** (`int`) -- The number of steps to accumulate over + - **adjust_scheduler** (`bool`) -- Whether the scheduler should be adjusted to account for the gradient + accumulation + - **sync_with_dataloader** (`bool`) -- Whether the gradients should be synced at the end of the dataloader + iteration and the number of total steps reset + - **is_xla_gradients_synced** (`bool`) -- Whether the XLA gradients have been synchronized. It is initialized + as false. Once gradients have been reduced before the optimizer step, this flag is set to true. Subsequently, + after each step, the flag is reset to false. FSDP will always synchronize the gradients, hence + is_xla_gradients_synced is always true. + """ + + _shared_state = SharedDict() + + def __init__(self, gradient_accumulation_plugin: GradientAccumulationPlugin | None = None): + self.__dict__ = self._shared_state + if not self.initialized: + self.sync_gradients = True + self._dataloader_references_ref = [None] + self.plugin_kwargs = ( + gradient_accumulation_plugin.to_kwargs() if gradient_accumulation_plugin is not None else {} + ) + self._is_xla_gradients_synced = False + + # Plugin args are different and can be updated + if gradient_accumulation_plugin is not None and self.plugin_kwargs != gradient_accumulation_plugin.to_kwargs(): + self.plugin_kwargs = gradient_accumulation_plugin.to_kwargs() + + @property + def num_steps(self) -> int: + "Returns the number of steps to accumulate over" + return self.plugin_kwargs.get("num_steps", 1) + + @property + def adjust_scheduler(self) -> bool: + "Returns whether the scheduler should be adjusted" + return self.plugin_kwargs.get("adjust_scheduler", False) + + @property + def sync_with_dataloader(self) -> bool: + "Returns whether the gradients should be synced at the end of the dataloader iteration and the number of total steps reset" + return self.plugin_kwargs.get("sync_with_dataloader", True) + + @property + def initialized(self) -> bool: + "Returns whether the `GradientState` has been initialized" + return GradientState._shared_state != {} + + @property + def end_of_dataloader(self) -> bool: + "Returns whether we have reached the end of the current dataloader" + if not self.in_dataloader: + return False + return self.active_dataloader.end_of_dataloader + + @property + def remainder(self) -> int: + "Returns the number of extra samples that were added from padding the dataloader" + if not self.in_dataloader: + return -1 + return self.active_dataloader.remainder + + def __repr__(self): + return ( + f"Sync Gradients: {self.sync_gradients}\n" + f"At end of current dataloader: {self.end_of_dataloader}\n" + f"Extra samples added: {self.remainder}\n" + f"Gradient accumulation plugin: {self.plugin_kwargs}\n" + ) + + @property + def is_xla_gradients_synced(self): + "Returns the value of is_xla_gradients_synced. FSDP will always synchronize the gradients, hence is_xla_gradients_synced is always true." + if parse_flag_from_env("ACCELERATE_USE_FSDP", default=False): + return True + return self._is_xla_gradients_synced + + @is_xla_gradients_synced.setter + def is_xla_gradients_synced(self, is_synced): + "Set the _is_xla_gradients_synced attribute." + self._is_xla_gradients_synced = is_synced + + def _set_sync_gradients(self, sync_gradients): + "Private function that sets whether gradients should be synchronized. Users should not have to call this." + self.sync_gradients = sync_gradients + # Allow grad-sync to automatically work on TPUs + if ( + self.sync_gradients + and is_torch_xla_available(check_is_tpu=True) + and PartialState().distributed_type == DistributedType.XLA + ): + xm.mark_step() + + def _add_dataloader(self, dataloader): + "Private function that adds a dataloader to `self.dataloader_references` and sets `in_dataloader` to `True`. Users should not have to call this." + # We explicitly use assignment to ensure that the property setter is triggered, which is required for garbage collection. + # Avoid using self.dataloader_references.append as it will not trigger the setter. + self.dataloader_references += [dataloader] + + def _remove_dataloader(self, dataloader): + "Private function that removes a dataloader from `self.dataloader_references` and sets `in_dataloader` to `False` if there are no more dataloaders. Users should not have to call this." + # We explicitly use assignment to ensure that the property setter is triggered. + self.dataloader_references = [ + dataloader_ref for dataloader_ref in self.dataloader_references if dataloader_ref != dataloader + ] + + @property + def active_dataloader(self): + return self.dataloader_references[-1] + + @property + def dataloader_references(self): + # We use a property getter and setter with weakrefs to avoid circular references that prevent garbage collection + return [reference() if reference is not None else reference for reference in self._dataloader_references_ref] + + @dataloader_references.setter + def dataloader_references(self, references): + self._dataloader_references_ref = [ + weakref.ref(dataloader) if dataloader is not None else dataloader for dataloader in references + ] + + @property + def in_dataloader(self) -> bool: + "Returns whether the current process is in a dataloader" + return self.active_dataloader is not None + + @staticmethod + def _reset_state(): + "Resets `_shared_state`, is used internally and should not be called" + GradientState._shared_state.clear() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/__init__.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..14f2f4f5a459fef9e9862ab32ce42c36e2ed573e --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/__init__.py @@ -0,0 +1,65 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from .testing import ( + DEFAULT_LAUNCH_COMMAND, + are_the_same_tensors, + assert_exception, + capture_call_output, + device_count, + execute_subprocess_async, + get_launch_command, + get_torch_dist_unique_port, + memory_allocated_func, + path_in_accelerate_package, + pytest_xdist_worker_id, + require_bnb, + require_cpu, + require_cuda, + require_cuda_or_hpu, + require_cuda_or_xpu, + require_fp8, + require_fp16, + require_huggingface_suite, + require_mlu, + require_mps, + require_multi_device, + require_multi_gpu, + require_multi_gpu_or_xpu, + require_multi_xpu, + require_musa, + require_non_cpu, + require_non_hpu, + require_non_torch_xla, + require_non_xpu, + require_npu, + require_pippy, + require_sdaa, + require_single_device, + require_single_gpu, + require_single_xpu, + require_torch_min_version, + require_torchao, + require_torchvision, + require_tpu, + require_transformer_engine, + require_xpu, + run_first, + skip, + slow, + torch_device, +) +from .training import RegressionDataset, RegressionModel, RegressionModel4XPU + + +from .scripts import test_script, test_sync, test_ops # isort: skip diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/examples.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/examples.py new file mode 100644 index 0000000000000000000000000000000000000000..79d09eedbc263dcab49519bd7e15d08c7cf15ed2 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/examples.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python + +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +A collection of utilities for comparing `examples/complete_*_example.py` scripts with the capabilities inside of each +`examples/by_feature` example. `compare_against_test` is the main function that should be used when testing, while the +others are used to either get the code that matters, or to preprocess them (such as stripping comments) +""" + +import os + + +def get_function_contents_by_name(lines: list[str], name: str): + """ + Extracts a function from `lines` of segmented source code with the name `name`. + + Args: + lines (`List[str]`): + Source code of a script separated by line. + name (`str`): + The name of the function to extract. Should be either `training_function` or `main` + """ + if name != "training_function" and name != "main": + raise ValueError(f"Incorrect function name passed: {name}, choose either 'main' or 'training_function'") + good_lines, found_start = [], False + for line in lines: + if not found_start and f"def {name}" in line: + found_start = True + good_lines.append(line) + continue + if found_start: + if name == "training_function" and "def main" in line: + return good_lines + if name == "main" and "if __name__" in line: + return good_lines + good_lines.append(line) + + +def clean_lines(lines: list[str]): + """ + Filters `lines` and removes any entries that start with a comment ('#') or is just a newline ('\n') + + Args: + lines (`List[str]`): + Source code of a script separated by line. + """ + return [line for line in lines if not line.lstrip().startswith("#") and line != "\n"] + + +def compare_against_test(base_filename: str, feature_filename: str, parser_only: bool, secondary_filename: str = None): + """ + Tests whether the additional code inside of `feature_filename` was implemented in `base_filename`. This should be + used when testing to see if `complete_*_.py` examples have all of the implementations from each of the + `examples/by_feature/*` scripts. + + It utilizes `nlp_example.py` to extract out all of the repeated training code, so that only the new additional code + is examined and checked. If something *other* than `nlp_example.py` should be used, such as `cv_example.py` for the + `complete_cv_example.py` script, it should be passed in for the `secondary_filename` parameter. + + Args: + base_filename (`str` or `os.PathLike`): + The filepath of a single "complete" example script to test, such as `examples/complete_cv_example.py` + feature_filename (`str` or `os.PathLike`): + The filepath of a single feature example script. The contents of this script are checked to see if they + exist in `base_filename` + parser_only (`bool`): + Whether to compare only the `main()` sections in both files, or to compare the contents of + `training_loop()` + secondary_filename (`str`, *optional*): + A potential secondary filepath that should be included in the check. This function extracts the base + functionalities off of "examples/nlp_example.py", so if `base_filename` is a script other than + `complete_nlp_example.py`, the template script should be included here. Such as `examples/cv_example.py` + """ + with open(base_filename) as f: + base_file_contents = f.readlines() + with open(os.path.abspath(os.path.join("examples", "nlp_example.py"))) as f: + full_file_contents = f.readlines() + with open(feature_filename) as f: + feature_file_contents = f.readlines() + if secondary_filename is not None: + with open(secondary_filename) as f: + secondary_file_contents = f.readlines() + + # This is our base, we remove all the code from here in our `full_filename` and `feature_filename` to find the new content + if parser_only: + base_file_func = clean_lines(get_function_contents_by_name(base_file_contents, "main")) + full_file_func = clean_lines(get_function_contents_by_name(full_file_contents, "main")) + feature_file_func = clean_lines(get_function_contents_by_name(feature_file_contents, "main")) + if secondary_filename is not None: + secondary_file_func = clean_lines(get_function_contents_by_name(secondary_file_contents, "main")) + else: + base_file_func = clean_lines(get_function_contents_by_name(base_file_contents, "training_function")) + full_file_func = clean_lines(get_function_contents_by_name(full_file_contents, "training_function")) + feature_file_func = clean_lines(get_function_contents_by_name(feature_file_contents, "training_function")) + if secondary_filename is not None: + secondary_file_func = clean_lines( + get_function_contents_by_name(secondary_file_contents, "training_function") + ) + + _dl_line = "train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)\n" + + # Specific code in our script that differs from the full version, aka what is new + new_feature_code = [] + passed_idxs = [] # We keep track of the idxs just in case it's a repeated statement + it = iter(feature_file_func) + for i in range(len(feature_file_func) - 1): + if i not in passed_idxs: + line = next(it) + if (line not in full_file_func) and (line.lstrip() != _dl_line): + if "TESTING_MOCKED_DATALOADERS" not in line: + new_feature_code.append(line) + passed_idxs.append(i) + else: + # Skip over the `config['num_epochs'] = 2` statement + _ = next(it) + + # Extract out just the new parts from the full_file_training_func + new_full_example_parts = [] + passed_idxs = [] # We keep track of the idxs just in case it's a repeated statement + for i, line in enumerate(base_file_func): + if i not in passed_idxs: + if (line not in full_file_func) and (line.lstrip() != _dl_line): + if "TESTING_MOCKED_DATALOADERS" not in line: + new_full_example_parts.append(line) + passed_idxs.append(i) + + # Finally, get the overall diff + diff_from_example = [line for line in new_feature_code if line not in new_full_example_parts] + if secondary_filename is not None: + diff_from_two = [line for line in full_file_contents if line not in secondary_file_func] + diff_from_example = [line for line in diff_from_example if line not in diff_from_two] + + return diff_from_example diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/__init__.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c9cbe26c257b515f657c05e1996d517e69613972 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/__init__.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c9cbe26c257b515f657c05e1996d517e69613972 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_checkpointing.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_checkpointing.py new file mode 100644 index 0000000000000000000000000000000000000000..6a1553898ec3d55e64822c204ddf7e705069ce8a --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_checkpointing.py @@ -0,0 +1,269 @@ +# Copyright 2022 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import argparse +import json +import os + +import evaluate +import torch +from datasets import load_dataset +from torch.optim import AdamW +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed + +from accelerate import Accelerator, DistributedType +from accelerate.utils.deepspeed import DummyOptim, DummyScheduler + + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + + +def get_dataloaders(accelerator: Accelerator, batch_size: int = 16, model_name: str = "bert-base-cased"): + """ + Creates a set of `DataLoader`s for the `glue` dataset. + + Args: + accelerator (`Accelerator`): + An `Accelerator` object + batch_size (`int`, *optional*): + The batch size for the train and validation DataLoaders. + model_name (`str`, *optional*): + """ + tokenizer = AutoTokenizer.from_pretrained(model_name) + datasets = load_dataset("glue", "mrpc") + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + tokenized_datasets = datasets.map( + tokenize_function, batched=True, remove_columns=["idx", "sentence1", "sentence2"], load_from_cache_file=False + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + if accelerator.distributed_type == DistributedType.XLA: + return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt") + return tokenizer.pad(examples, padding="longest", return_tensors="pt") + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE + ) + + return train_dataloader, eval_dataloader + + +def evaluation_loop(accelerator, model, eval_dataloader, metric): + model.eval() + samples_seen = 0 + for step, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits.argmax(dim=-1) + # It is slightly faster to call this once, than multiple times + predictions, references = accelerator.gather( + (predictions, batch["labels"]) + ) # If we are in a multiprocess environment, the last batch has duplicates + if accelerator.use_distributed: + if step == len(eval_dataloader) - 1: + predictions = predictions[: len(eval_dataloader.dataset) - samples_seen] + references = references[: len(eval_dataloader.dataset) - samples_seen] + else: + samples_seen += references.shape[0] + metric.add_batch( + predictions=predictions, + references=references, + ) + + eval_metric = metric.compute() + return eval_metric["accuracy"] + + +def training_function(config, args): + # Initialize accelerator + accelerator = Accelerator() + + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + model_name = args.model_name_or_path + + set_seed(seed) + train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size, model_name) + + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained(model_name, return_dict=True) + + # Instantiate optimizer + optimizer_cls = ( + AdamW + if accelerator.state.deepspeed_plugin is None + or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config + else DummyOptim + ) + optimizer = optimizer_cls(params=model.parameters(), lr=lr) + + if accelerator.state.deepspeed_plugin is not None: + gradient_accumulation_steps = accelerator.state.deepspeed_plugin.deepspeed_config[ + "gradient_accumulation_steps" + ] + else: + gradient_accumulation_steps = 1 + max_training_steps = (len(train_dataloader) * num_epochs) // gradient_accumulation_steps + + # Instantiate scheduler + if ( + accelerator.state.deepspeed_plugin is None + or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config + ): + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=max_training_steps, + ) + else: + lr_scheduler = DummyScheduler(optimizer, total_num_steps=max_training_steps, warmup_num_steps=0) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # We need to keep track of how many total steps we have iterated over + overall_step = 0 + # We also need to keep track of the stating epoch so files are named properly + starting_epoch = 0 + metric = evaluate.load("glue", "mrpc") + ending_epoch = num_epochs + + if args.partial_train_epoch is not None: + ending_epoch = args.partial_train_epoch + + if args.resume_from_checkpoint: + accelerator.load_state(args.resume_from_checkpoint) + epoch_string = args.resume_from_checkpoint.split("epoch_")[1] + state_epoch_num = "" + for char in epoch_string: + if char.isdigit(): + state_epoch_num += char + else: + break + starting_epoch = int(state_epoch_num) + 1 + accuracy = evaluation_loop(accelerator, model, eval_dataloader, metric) + accelerator.print("resumed checkpoint performance:", accuracy) + accelerator.print("resumed checkpoint's scheduler's lr:", lr_scheduler.get_lr()[0]) + accelerator.print("resumed optimizers's lr:", optimizer.param_groups[0]["lr"]) + with open(os.path.join(args.output_dir, f"state_{starting_epoch - 1}.json")) as f: + resumed_state = json.load(f) + assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" + assert resumed_state["lr"] == lr_scheduler.get_lr()[0], ( + "Scheduler learning rate mismatch, loading from checkpoint failed" + ) + assert resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"], ( + "Optimizer learning rate mismatch, loading from checkpoint failed" + ) + assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" + return + + # Now we train the model + state = {} + for epoch in range(starting_epoch, ending_epoch): + model.train() + for step, batch in enumerate(train_dataloader): + outputs = model(**batch) + loss = outputs.loss + loss = loss / gradient_accumulation_steps + accelerator.backward(loss) + if step % gradient_accumulation_steps == 0: + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + overall_step += 1 + output_dir = f"epoch_{epoch}" + output_dir = os.path.join(args.output_dir, output_dir) + accelerator.save_state(output_dir) + accuracy = evaluation_loop(accelerator, model, eval_dataloader, metric) + state["accuracy"] = accuracy + state["lr"] = lr_scheduler.get_lr()[0] + state["optimizer_lr"] = optimizer.param_groups[0]["lr"] + state["epoch"] = epoch + state["step"] = overall_step + accelerator.print(f"epoch {epoch}:", state) + + accelerator.wait_for_everyone() + if accelerator.is_main_process: + with open(os.path.join(args.output_dir, f"state_{epoch}.json"), "w") as f: + json.dump(state, f) + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage.") + parser.add_argument( + "--model_name_or_path", + type=str, + default="bert-base-cased", + help="Path to pretrained model or model identifier from huggingface.co/models.", + required=False, + ) + parser.add_argument( + "--output_dir", + type=str, + default=".", + help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.", + ) + parser.add_argument( + "--resume_from_checkpoint", + type=str, + default=None, + help="If the training should continue from a checkpoint folder.", + ) + parser.add_argument( + "--partial_train_epoch", + type=int, + default=None, + help="If passed, the training will stop after this number of epochs.", + ) + parser.add_argument( + "--num_epochs", + type=int, + default=2, + help="Number of train epochs.", + ) + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16} + + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_ds_multiple_model.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_ds_multiple_model.py new file mode 100644 index 0000000000000000000000000000000000000000..3729ecf4c72190bf865d620b6941206ab904818c --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_ds_multiple_model.py @@ -0,0 +1,332 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Test script for verifying multiple models can be utilized with Accelerate + DeepSpeed: + +Scenario 1: One model is training, another model is being used for inference/logits to impact training in some form. +Scenario 2: Two models are training simultaneously, which means two optimizers, etc. +""" + +import argparse +from pathlib import Path + +import evaluate +import torch +from datasets import load_dataset +from torch.optim import AdamW +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup + +from accelerate import Accelerator, DeepSpeedPlugin, DistributedType +from accelerate.state import AcceleratorState +from accelerate.utils.deepspeed import get_active_deepspeed_plugin + + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + + +class NoiseModel(torch.nn.Module): + def __init__(self, noise_factor=0.1): + super().__init__() + self.noise_factor = torch.nn.Parameter(torch.tensor(noise_factor, dtype=torch.float32)) + + def forward(self, loss): + return loss * self.noise_factor + + +def get_dataloaders(accelerator: Accelerator, batch_size: int = 16, model_name: str = "bert-base-cased"): + """ + Creates a set of `DataLoader`s for the `glue` dataset. + + Args: + accelerator (`Accelerator`): + An `Accelerator` object + batch_size (`int`, *optional*): + The batch size for the train and validation DataLoaders. + model_name (`str`, *optional*): + """ + tokenizer = AutoTokenizer.from_pretrained(model_name) + datasets = load_dataset("glue", "mrpc") + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + tokenized_datasets = datasets.map( + tokenize_function, batched=True, remove_columns=["idx", "sentence1", "sentence2"], load_from_cache_file=False + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + if accelerator.distributed_type == DistributedType.XLA: + return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt") + return tokenizer.pad(examples, padding="longest", return_tensors="pt") + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE + ) + + return train_dataloader, eval_dataloader + + +test_file_path = __file__ +path = Path(test_file_path).resolve() +test_file_dir_str = str(path.parent.parent.parent.parent.parent.parent) + +# Create our DS plugins +# We use custom schedulers and optimizers, hence `model_only` +ds_config_file = dict( + zero2=f"{test_file_dir_str}/tests/deepspeed/ds_config_zero2_model_only.json", + zero3=f"{test_file_dir_str}/tests/deepspeed/ds_config_zero3_model_only.json", +) + + +def single_model_training(config, args): + # Training a single model, we have a `noise` model that is untrainable used to inject some noise into the training process + num_epochs = config["num_epochs"] + zero2_plugin = DeepSpeedPlugin(hf_ds_config=ds_config_file["zero2"]) + zero3_plugin = DeepSpeedPlugin(hf_ds_config=ds_config_file["zero3"]) + + deepspeed_plugins = {"training": zero2_plugin, "inference": zero3_plugin} + + # Initialize accelerator + accelerator = Accelerator( + deepspeed_plugins=deepspeed_plugins, + mixed_precision="bf16", + ) + + # Initialize model under zero2 plugin + assert get_active_deepspeed_plugin(accelerator.state) is zero2_plugin + train_model = AutoModelForSequenceClassification.from_pretrained(args.model_name_or_path) + train_dataloader, eval_dataloader = get_dataloaders( + accelerator, batch_size=config["batch_size"], model_name=args.model_name_or_path + ) + max_training_steps = len(train_dataloader) * config["num_epochs"] + optimizer = AdamW(train_model.parameters(), lr=config["lr"]) + lr_scheduler = get_linear_schedule_with_warmup( + optimizer, num_warmup_steps=0, num_training_steps=max_training_steps + ) + + train_dataloader, eval_dataloader, train_model, optimizer, lr_scheduler = accelerator.prepare( + train_dataloader, eval_dataloader, train_model, optimizer, lr_scheduler + ) + + # Now prepare the model under zero3 plugin + accelerator.state.select_deepspeed_plugin("inference") + assert get_active_deepspeed_plugin(accelerator.state) is zero3_plugin + inference_model = NoiseModel() + inference_model = accelerator.prepare(inference_model) + inference_model.eval() + + # Run training loop + accelerator.state.select_deepspeed_plugin("training") + # We also need to keep track of the stating epoch so files are named properly + starting_epoch = 0 + + # Now we train the model + best_performance = 0 + metric = evaluate.load("glue", "mrpc") + performance_metric = {} + for epoch in range(starting_epoch, num_epochs): + train_model.train() + inference_model.train() + for step, batch in enumerate(train_dataloader): + with accelerator.accumulate(train_model): + outputs_1 = train_model(**batch) + with torch.no_grad(): + outputs_2 = inference_model(outputs_1.loss) + # Combine the losses + loss = outputs_1.loss + outputs_2 + accelerator.backward(loss) + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + train_model.eval() + for step, batch in enumerate(eval_dataloader): + with torch.no_grad(): + outputs = train_model(**batch) + predictions = outputs.logits.argmax(dim=-1) + # It is slightly faster to call this once, than multiple times + predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"])) + metric.add_batch( + predictions=predictions, + references=references, + ) + + eval_metric = metric.compute() + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}:", eval_metric) + performance_metric[f"epoch-{epoch}"] = eval_metric["accuracy"] + + if best_performance < eval_metric["accuracy"]: + best_performance = eval_metric["accuracy"] + assert best_performance > performance_metric["epoch-0"] + + +def multiple_model_training(config, args): + # This will essentially be like a k-fold model, but one model is Zero-2 and another model is Zero-3 + num_epochs = config["num_epochs"] + zero2_plugin = DeepSpeedPlugin(hf_ds_config=ds_config_file["zero2"]) + zero3_plugin = DeepSpeedPlugin(hf_ds_config=ds_config_file["zero3"]) + + deepspeed_plugins = {"zero2": zero2_plugin, "zero3": zero3_plugin} + + # Initialize accelerator + zero2_accelerator = Accelerator( + deepspeed_plugins=deepspeed_plugins, + mixed_precision="bf16", + ) + + # Since an `AcceleratorState` has already been made, we can just reuse it here + zero3_accelerator = Accelerator() + + # Initialize model under zero2 plugin + assert get_active_deepspeed_plugin(zero2_accelerator.state) is zero2_plugin + zero2_model = AutoModelForSequenceClassification.from_pretrained(args.model_name_or_path) + train_dataloader, eval_dataloader = get_dataloaders( + zero2_accelerator, batch_size=config["batch_size"], model_name=args.model_name_or_path + ) + max_training_steps = len(train_dataloader) * config["num_epochs"] + zero2_optimizer = AdamW(zero2_model.parameters(), lr=config["lr"]) + zero2_lr_scheduler = get_linear_schedule_with_warmup( + zero2_optimizer, num_warmup_steps=0, num_training_steps=max_training_steps + ) + + train_dataloader, eval_dataloader, zero2_model, zero2_optimizer, zero2_lr_scheduler = zero2_accelerator.prepare( + train_dataloader, eval_dataloader, zero2_model, zero2_optimizer, zero2_lr_scheduler + ) + assert zero2_accelerator.deepspeed_engine_wrapped.engine is zero2_model + + # now do Zero3 + zero3_accelerator.state.select_deepspeed_plugin("zero3") + zero3_plugin.deepspeed_config["train_micro_batch_size_per_gpu"] = zero2_plugin.deepspeed_config[ + "train_micro_batch_size_per_gpu" + ] + assert get_active_deepspeed_plugin(zero3_accelerator.state) is zero3_plugin + zero3_model = AutoModelForSequenceClassification.from_pretrained(args.model_name_or_path) + zero3_optimizer = AdamW(zero3_model.parameters(), lr=config["lr"]) + zero3_lr_scheduler = get_linear_schedule_with_warmup( + zero3_optimizer, num_warmup_steps=0, num_training_steps=max_training_steps + ) + zero3_model, zero3_optimizer, zero3_lr_scheduler = zero3_accelerator.prepare( + zero3_model, zero3_optimizer, zero3_lr_scheduler + ) + assert zero3_accelerator.deepspeed_engine_wrapped.engine is zero3_model + + # Run training loop + starting_epoch = 0 + + # Now we train the model + best_performance_a = 0 + best_performance_b = 0 + metric_a = evaluate.load("glue", "mrpc") + metric_b = evaluate.load("glue", "mrpc") + performance_metric_a = {} + performance_metric_b = {} + for epoch in range(starting_epoch, num_epochs): + zero2_model.train() + zero3_model.train() + for step, batch in enumerate(train_dataloader): + with zero2_accelerator.accumulate(zero2_model, zero3_model): + outputs_1 = zero2_model(**batch) + zero2_accelerator.backward(outputs_1.loss) + zero2_optimizer.step() + zero2_lr_scheduler.step() + zero2_optimizer.zero_grad() + outputs_2 = zero3_model(**batch) + zero3_accelerator.backward(outputs_2.loss) + zero3_optimizer.step() + zero3_lr_scheduler.step() + zero3_optimizer.zero_grad() + + zero2_model.eval() + zero3_model.eval() + for step, batch in enumerate(eval_dataloader): + with torch.no_grad(): + logits_a = zero2_model(**batch).logits + logits_b = zero3_model(**batch).logits + # Combine the logits from both models + predictions_a = logits_a.argmax(dim=-1) + predictions_b = logits_b.argmax(dim=-1) + # It is slightly faster to call this once, than multiple times + predictions_a, predictions_b, references = zero2_accelerator.gather_for_metrics( + (predictions_a, predictions_b, batch["labels"]) + ) + metric_a.add_batch( + predictions=predictions_a, + references=references, + ) + metric_b.add_batch( + predictions=predictions_b, + references=references, + ) + + eval_metric_a = metric_a.compute() + eval_metric_b = metric_b.compute() + # Use accelerator.print to print only on the main process. + zero2_accelerator.print(f"epoch {epoch}:", eval_metric_a, eval_metric_b) + performance_metric_a[f"epoch-{epoch}"] = eval_metric_a["accuracy"] + performance_metric_b[f"epoch-{epoch}"] = eval_metric_b["accuracy"] + + if best_performance_a < eval_metric_a["accuracy"]: + best_performance_a = eval_metric_a["accuracy"] + if best_performance_b < eval_metric_b["accuracy"]: + best_performance_b = eval_metric_b["accuracy"] + assert best_performance_a > performance_metric_a["epoch-0"] + assert best_performance_b > performance_metric_b["epoch-0"] + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage.") + parser.add_argument( + "--model_name_or_path", + type=str, + default="bert-base-cased", + help="Path to pretrained model or model identifier from huggingface.co/models.", + required=False, + ) + parser.add_argument( + "--performance_lower_bound", + type=float, + default=None, + help="Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.", + ) + parser.add_argument( + "--num_epochs", + type=int, + default=2, + help="Number of train epochs.", + ) + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16} + single_model_training(config, args) + AcceleratorState._reset_state(True) + multiple_model_training(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_metrics.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..d1bfe351509148ebc48067584e9d61b93e7210a6 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_metrics.py @@ -0,0 +1,307 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import math +import os +from copy import deepcopy + +import datasets +import evaluate +import torch +import transformers +from datasets import load_dataset +from torch.utils.data import DataLoader, IterableDataset +from transformers import AutoModelForSequenceClassification, AutoTokenizer + +from accelerate import Accelerator, DataLoaderConfiguration, DistributedType +from accelerate.data_loader import DataLoaderDispatcher +from accelerate.test_utils import RegressionDataset, RegressionModel, torch_device +from accelerate.utils import is_torch_xla_available, set_seed + + +os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "true" + + +class ListHandler(logging.Handler): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.logs = [] + + def emit(self, record): + self.logs.append(record) + + +def get_basic_setup(accelerator, num_samples=82, batch_size=16): + "Returns everything needed to perform basic training" + set_seed(42) + model = RegressionModel() + ddp_model = deepcopy(model) + dset = RegressionDataset(length=num_samples) + dataloader = DataLoader(dset, batch_size=batch_size) + model.to(accelerator.device) + ddp_model, dataloader = accelerator.prepare(ddp_model, dataloader) + return model, ddp_model, dataloader + + +def get_dataloader(accelerator: Accelerator, use_longest=False): + tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/mrpc-bert-base-cased") + dataset = load_dataset("glue", "mrpc", split="validation") + + def tokenize_function(examples): + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + with accelerator.main_process_first(): + tokenized_datasets = dataset.map( + tokenize_function, + batched=True, + remove_columns=["idx", "sentence1", "sentence2"], + ) + + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + if use_longest: + return tokenizer.pad(examples, padding="longest", return_tensors="pt") + return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt") + + return DataLoader(tokenized_datasets, shuffle=False, collate_fn=collate_fn, batch_size=16) + + +def get_mrpc_setup(dispatch_batches, split_batches): + dataloader_config = DataLoaderConfiguration(dispatch_batches=dispatch_batches, split_batches=split_batches) + accelerator = Accelerator(dataloader_config=dataloader_config) + dataloader = get_dataloader(accelerator, not dispatch_batches) + model = AutoModelForSequenceClassification.from_pretrained( + "hf-internal-testing/mrpc-bert-base-cased", return_dict=True + ) + ddp_model, ddp_dataloader = accelerator.prepare(model, dataloader) + return { + "ddp": [ddp_model, ddp_dataloader, torch_device], + "no": [model, dataloader, accelerator.device], + }, accelerator + + +def generate_predictions(model, dataloader, accelerator): + logits_and_targets = [] + for batch in dataloader: + input, target = batch.values() + with torch.no_grad(): + logit = model(input) + logit, target = accelerator.gather_for_metrics((logit, target)) + logits_and_targets.append((logit, target)) + logits, targs = [], [] + for logit, targ in logits_and_targets: + logits.append(logit) + targs.append(targ) + logits, targs = torch.cat(logits), torch.cat(targs) + return logits, targs + + +def test_torch_metrics( + accelerator: Accelerator, num_samples=82, dispatch_batches=False, split_batches=False, batch_size=16 +): + _, ddp_model, dataloader = get_basic_setup(accelerator, num_samples, batch_size) + logits, _ = generate_predictions(ddp_model, dataloader, accelerator) + assert len(logits) == num_samples, ( + f"Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(logits)}" + ) + + +def test_mrpc(dispatch_batches: bool = False, split_batches: bool = False): + metric = evaluate.load("glue", "mrpc") + setup, accelerator = get_mrpc_setup(dispatch_batches, split_batches) + # First do baseline + model, dataloader, device = setup["no"] + model.to(device) + model.eval() + for batch in dataloader: + batch.to(device) + with torch.inference_mode(): + outputs = model(**batch) + preds = outputs.logits.argmax(dim=-1) + metric.add_batch(predictions=preds, references=batch["labels"]) + baseline = metric.compute() + + # Then do distributed + model, dataloader, device = setup["ddp"] + model.eval() + for batch in dataloader: + with torch.inference_mode(): + outputs = model(**batch) + preds = outputs.logits.argmax(dim=-1) + references = batch["labels"] + preds, references = accelerator.gather_for_metrics((preds, references)) + metric.add_batch(predictions=preds, references=references) + distributed = metric.compute() + + for key in "accuracy f1".split(): + assert math.isclose(baseline[key], distributed[key]), ( + f"Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n" + ) + + +def test_gather_for_metrics_with_non_tensor_objects_iterable_dataset(): + class DummyIterableDataset(IterableDataset): + def __init__(self, data): + self.data = data + + def __len__(self): + return len(self.data) + + def __iter__(self): + yield from self.data + + iterable_dataset = DummyIterableDataset([n for n in range(30)]) + dataloader = DataLoader(iterable_dataset, batch_size=4) + accelerator = Accelerator() + prepared_dataloader = accelerator.prepare(dataloader) + + if accelerator.is_main_process: + logger = logging.root.manager.loggerDict["accelerate.accelerator"] + list_handler = ListHandler() + logger.addHandler(list_handler) + + batches_for_metrics = [] + for batch in prepared_dataloader: + batches_for_metrics.append(accelerator.gather_for_metrics(batch)) + + assert torch.cat(batches_for_metrics).size(0) == 30 + + if accelerator.is_main_process: + assert len(list_handler.logs) == 0 + logger.removeHandler(list_handler) + + +def test_gather_for_metrics_with_iterable_dataset(): + class DummyIterableDataset(IterableDataset): + def __init__(self, data): + self.data = data + + def __len__(self): + return len(self.data) + + def __iter__(self): + yield from self.data + + iterable_dataset = DummyIterableDataset(torch.as_tensor(range(30))) + dataloader = DataLoader(iterable_dataset, batch_size=4) + + accelerator = Accelerator() + prepared_dataloader = accelerator.prepare(dataloader) + + assert isinstance(prepared_dataloader, DataLoaderDispatcher) + + if accelerator.is_main_process: + logger = logging.root.manager.loggerDict["accelerate.accelerator"] + list_handler = ListHandler() + logger.addHandler(list_handler) + + batches_for_metrics = [] + for batch in prepared_dataloader: + batches_for_metrics.append(accelerator.gather_for_metrics(batch)) + + assert torch.cat(batches_for_metrics).size(0) == 30 + + if accelerator.is_main_process: + assert len(list_handler.logs) == 0 + + logger.removeHandler(list_handler) + + +def test_gather_for_metrics_drop_last(): + accelerator = Accelerator() + per_device_batch_size = 5 + num_items = (10 * accelerator.num_processes) + 1 + dataloader = DataLoader(range(num_items), batch_size=per_device_batch_size, drop_last=True) + dataloader = accelerator.prepare(dataloader) + + iterator = iter(dataloader) + next(iterator) # Skip first batch tensor([0, 1, 2, 3, 4], device='cuda:0') + batch = next(iterator) + gathered_items = accelerator.gather_for_metrics(batch) + + # Should return a full set of complete batches from each GPU + num_expected_items = per_device_batch_size * accelerator.num_processes + assert gathered_items.size(0) == (num_expected_items), ( + f"Expected number of items: {num_expected_items}, Actual: {gathered_items.size(0)}" + ) + + +def main(): + dataloader_config = DataLoaderConfiguration(split_batches=False, dispatch_batches=False) + accelerator = Accelerator(dataloader_config=dataloader_config) + if accelerator.is_local_main_process: + datasets.utils.logging.set_verbosity_warning() + transformers.utils.logging.set_verbosity_warning() + else: + datasets.utils.logging.set_verbosity_error() + transformers.utils.logging.set_verbosity_error() + # TorchXLA does not support batch dispatching. 'put_on_device' is always False for + # TorchXLA, which can cause a value error in 'prepare_data_loader' function. + dispatch_batches_options = [False] if accelerator.state.distributed_type == DistributedType.XLA else [True, False] + + # Temporarily close this test for TorchXLA due to the 'Cannot set version_counter for + # inference tensor' error in inference mode. Reopen it after TorchXLA fixes this bug. + # These are a bit slower so they should only be ran on the GPU or TPU + if accelerator.device.type != "cpu" and not is_torch_xla_available(): + if accelerator.is_local_main_process: + print("**Testing gather_for_metrics**") + for split_batches in [True, False]: + for dispatch_batches in dispatch_batches_options: + if accelerator.is_local_main_process: + print(f"With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`") + test_mrpc(dispatch_batches, split_batches) + accelerator.state._reset_state() + print("test_gather_for_metrics_with_iterable_dataset") + test_gather_for_metrics_with_iterable_dataset() + print("test gather_for_metrics_with_non_tensor_objects_iterable_dataset") + test_gather_for_metrics_with_non_tensor_objects_iterable_dataset() + + # MpDeviceLoader in TorchXLA is an asynchronous loader that preloads several batches into cache. + # This can cause the 'end_of_dataloader' of DataLoaderStateMixin to be set earlier than intended. + # Skip this test when TorchXLA is enabled. + if accelerator.state.distributed_type != DistributedType.XLA: + if accelerator.is_local_main_process: + print("**Test torch metrics**") + for split_batches in [True, False]: + for dispatch_batches in dispatch_batches_options: + dataloader_config = DataLoaderConfiguration( + split_batches=split_batches, dispatch_batches=dispatch_batches + ) + accelerator = Accelerator(dataloader_config=dataloader_config) + if accelerator.is_local_main_process: + print(f"With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99") + test_torch_metrics(accelerator, 99) + accelerator.state._reset_state() + if accelerator.is_local_main_process: + print("**Test last batch is not dropped when perfectly divisible**") + accelerator = Accelerator() + test_torch_metrics(accelerator, 512) + accelerator.state._reset_state() + if accelerator.is_local_main_process: + print("**Test that `drop_last` is taken into account**") + test_gather_for_metrics_drop_last() + accelerator.end_training() + accelerator.state._reset_state() + + +def _mp_fn(index): + # For xla_spawn (TPUs) + main() + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_peak_memory_usage.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_peak_memory_usage.py new file mode 100644 index 0000000000000000000000000000000000000000..723e5497656020516bf072cf4112f61f59c2e5cb --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_peak_memory_usage.py @@ -0,0 +1,314 @@ +# Copyright 2022 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import argparse +import gc +import json +import os + +import torch +from datasets import load_dataset +from torch.optim import AdamW +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed + +from accelerate import Accelerator, DistributedType +from accelerate.utils import ( + is_hpu_available, + is_mlu_available, + is_musa_available, + is_npu_available, + is_sdaa_available, + is_xpu_available, +) +from accelerate.utils.deepspeed import DummyOptim, DummyScheduler + + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + + +# Converting Bytes to Megabytes +def b2mb(x): + return int(x / 2**20) + + +# This context manager is used to track the peak memory usage of the process +class TorchTracemalloc: + def __enter__(self): + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero + self.begin = torch.cuda.memory_allocated() + elif is_mlu_available(): + torch.mlu.empty_cache() + torch.mlu.reset_max_memory_allocated() # reset the peak gauge to zero + self.begin = torch.mlu.memory_allocated() + elif is_sdaa_available(): + torch.sdaa.empty_cache() + torch.sdaa.reset_max_memory_allocated() # reset the peak gauge to zero + self.begin = torch.sdaa.memory_allocated() + elif is_musa_available(): + torch.musa.empty_cache() + torch.musa.reset_max_memory_allocated() # reset the peak gauge to zero + self.begin = torch.musa.memory_allocated() + elif is_npu_available(): + torch.npu.empty_cache() + torch.npu.reset_max_memory_allocated() # reset the peak gauge to zero + self.begin = torch.npu.memory_allocated() + elif is_xpu_available(): + torch.xpu.empty_cache() + torch.xpu.reset_max_memory_allocated() # reset the peak gauge to zero + self.begin = torch.xpu.memory_allocated() + elif is_hpu_available(): + # torch.hpu.empty_cache() # not available on hpu as it reserves all device memory for the current process + torch.hpu.reset_peak_memory_stats() # reset the peak gauge to zero + self.begin = torch.hpu.memory_allocated() + return self + + def __exit__(self, *exc): + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + self.end = torch.cuda.memory_allocated() + self.peak = torch.cuda.max_memory_allocated() + elif is_mlu_available(): + torch.mlu.empty_cache() + self.end = torch.mlu.memory_allocated() + self.begin = torch.mlu.max_memory_allocated() + elif is_sdaa_available(): + torch.sdaa.empty_cache() + self.end = torch.sdaa.memory_allocated() + self.begin = torch.sdaa.max_memory_allocated() + elif is_musa_available(): + torch.musa.empty_cache() + self.end = torch.musa.memory_allocated() + self.begin = torch.musa.max_memory_allocated() + elif is_npu_available(): + torch.npu.empty_cache() + self.end = torch.npu.memory_allocated() + self.peak = torch.npu.max_memory_allocated() + elif is_xpu_available(): + torch.xpu.empty_cache() + self.end = torch.xpu.memory_allocated() + self.peak = torch.xpu.max_memory_allocated() + elif is_hpu_available(): + # torch.hpu.empty_cache() # not available on hpu as it reserves all device memory for the current process + self.end = torch.hpu.memory_allocated() + self.peak = torch.hpu.max_memory_allocated() + self.used = b2mb(self.end - self.begin) + self.peaked = b2mb(self.peak - self.begin) + # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}") + + +def get_dataloaders( + accelerator: Accelerator, + batch_size: int = 16, + model_name: str = "bert-base-cased", + n_train: int = 320, + n_val: int = 160, +): + """ + Creates a set of `DataLoader`s for the `glue` dataset. + + Args: + accelerator (`Accelerator`): + An `Accelerator` object + batch_size (`int`, *optional*): + The batch size for the train and validation DataLoaders. + model_name (`str`, *optional*): + The name of the model to use. + n_train (`int`, *optional*): + The number of training examples to use. + n_val (`int`, *optional*): + The number of validation examples to use. + """ + tokenizer = AutoTokenizer.from_pretrained(model_name) + datasets = load_dataset( + "glue", "mrpc", split={"train": f"train[:{n_train}]", "validation": f"validation[:{n_val}]"} + ) + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + tokenized_datasets = datasets.map( + tokenize_function, batched=True, remove_columns=["idx", "sentence1", "sentence2"], load_from_cache_file=False + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + if accelerator.distributed_type == DistributedType.XLA: + return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt") + return tokenizer.pad(examples, padding="longest", return_tensors="pt") + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE + ) + + return train_dataloader, eval_dataloader + + +def training_function(config, args): + # Initialize accelerator + accelerator = Accelerator() + + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + model_name = args.model_name_or_path + + set_seed(seed) + train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size, model_name, args.n_train, args.n_val) + + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained(model_name, return_dict=True) + + # Instantiate optimizer + optimizer_cls = ( + AdamW + if accelerator.state.deepspeed_plugin is None + or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config + else DummyOptim + ) + optimizer = optimizer_cls(params=model.parameters(), lr=lr) + + if accelerator.state.deepspeed_plugin is not None: + gradient_accumulation_steps = accelerator.state.deepspeed_plugin.deepspeed_config[ + "gradient_accumulation_steps" + ] + else: + gradient_accumulation_steps = 1 + max_training_steps = (len(train_dataloader) * num_epochs) // gradient_accumulation_steps + + # Instantiate scheduler + if ( + accelerator.state.deepspeed_plugin is None + or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config + ): + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=max_training_steps, + ) + else: + lr_scheduler = DummyScheduler(optimizer, total_num_steps=max_training_steps, warmup_num_steps=0) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # We need to keep track of how many total steps we have iterated over + overall_step = 0 + # We also need to keep track of the stating epoch so files are named properly + starting_epoch = 0 + + # Now we train the model + train_total_peak_memory = {} + for epoch in range(starting_epoch, num_epochs): + with TorchTracemalloc() as tracemalloc: + model.train() + for step, batch in enumerate(train_dataloader): + outputs = model(**batch) + loss = outputs.loss + loss = loss / gradient_accumulation_steps + accelerator.backward(loss) + if step % gradient_accumulation_steps == 0: + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + overall_step += 1 + + # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage + accelerator.print(f"Memory before entering the train : {b2mb(tracemalloc.begin)}") + accelerator.print(f"Memory consumed at the end of the train (end-begin): {tracemalloc.used}") + accelerator.print(f"Peak Memory consumed during the train (max-begin): {tracemalloc.peaked}") + accelerator.print( + f"Total Peak Memory consumed during the train (max): {tracemalloc.peaked + b2mb(tracemalloc.begin)}" + ) + train_total_peak_memory[f"epoch-{epoch}"] = tracemalloc.peaked + b2mb(tracemalloc.begin) + if args.peak_memory_upper_bound is not None: + assert train_total_peak_memory[f"epoch-{epoch}"] <= args.peak_memory_upper_bound, ( + "Peak memory usage exceeded the upper bound" + ) + + accelerator.wait_for_everyone() + if accelerator.is_main_process: + with open(os.path.join(args.output_dir, "peak_memory_utilization.json"), "w") as f: + json.dump(train_total_peak_memory, f) + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage.") + parser.add_argument( + "--model_name_or_path", + type=str, + default="bert-base-cased", + help="Path to pretrained model or model identifier from huggingface.co/models.", + required=False, + ) + parser.add_argument( + "--output_dir", + type=str, + default=".", + help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.", + ) + parser.add_argument( + "--peak_memory_upper_bound", + type=float, + default=None, + help="The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value.", + ) + parser.add_argument( + "--n_train", + type=int, + default=320, + help="Number of training examples to use.", + ) + parser.add_argument( + "--n_val", + type=int, + default=160, + help="Number of validation examples to use.", + ) + parser.add_argument( + "--num_epochs", + type=int, + default=1, + help="Number of train epochs.", + ) + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_performance.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_performance.py new file mode 100644 index 0000000000000000000000000000000000000000..8e500bdd4c01013904375f010e99d22aea4e4ff9 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_performance.py @@ -0,0 +1,299 @@ +# Copyright 2022 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import argparse +import json +import os +from contextlib import nullcontext +from pathlib import Path + +import evaluate +import torch +from datasets import load_dataset +from torch.optim import AdamW +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup + +from accelerate import Accelerator, DistributedType +from accelerate.parallelism_config import ParallelismConfig +from accelerate.utils import SAFE_WEIGHTS_NAME, set_seed +from accelerate.utils.deepspeed import DummyOptim, DummyScheduler + + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + + +def get_dataloaders(accelerator: Accelerator, batch_size: int = 16, model_name: str = "bert-base-cased"): + """ + Creates a set of `DataLoader`s for the `glue` dataset. + + Args: + accelerator (`Accelerator`): + An `Accelerator` object + batch_size (`int`, *optional*): + The batch size for the train and validation DataLoaders. + model_name (`str`, *optional*): + """ + tokenizer = AutoTokenizer.from_pretrained(model_name) + + datasets = load_dataset("glue", "mrpc") + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + tokenized_datasets = datasets.map( + tokenize_function, batched=True, remove_columns=["idx", "sentence1", "sentence2"], load_from_cache_file=False + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + if accelerator.distributed_type == DistributedType.XLA: + return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt") + return tokenizer.pad(examples, padding="longest", return_tensors="pt") + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE + ) + + return train_dataloader, eval_dataloader + + +def training_function(config, args): + accelerator_kwargs = {} + # need this for DeepSpeed tests as `args.tp_size` would be None and `torch.distributed.init_device_mesh` would fail + if args.tp_size is not None: + accelerator_kwargs["parallelism_config"] = ParallelismConfig(tp_size=args.tp_size) + + # Initialize accelerator + accelerator = Accelerator(**accelerator_kwargs) + + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + model_name = args.model_name_or_path + + set_seed(seed) + train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size, model_name) + + # Add TP related kwargs if provided + model_kwargs = {} + if args.tp_plan is not None: + model_kwargs["tp_plan"] = args.tp_plan + if args.tp_size is not None: + model_kwargs["tp_size"] = args.tp_size + + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained(model_name, return_dict=True, **model_kwargs) + + if args.add_pad_token: + if model.config.pad_token_id is None: + model.config.pad_token_id = 0 + + # Instantiate optimizer + optimizer_cls = ( + AdamW + if accelerator.state.deepspeed_plugin is None + or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config + else DummyOptim + ) + optimizer = optimizer_cls(params=model.parameters(), lr=lr) + + max_training_steps = len(train_dataloader) * num_epochs + + # Instantiate scheduler + linear_decay_scheduler = False + if ( + accelerator.state.deepspeed_plugin is None + or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config + ): + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=max_training_steps, + ) + linear_decay_scheduler = True + else: + lr_scheduler = DummyScheduler(optimizer, total_num_steps=max_training_steps, warmup_num_steps=0) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # We also need to keep track of the stating epoch so files are named properly + starting_epoch = 0 + + # Now we train the model + metric = evaluate.load("glue", "mrpc") + best_performance = 0 + performance_metric = {} + expected_lr_after_first_optim_step = lr * ( + 1 - 1 / (max_training_steps / accelerator.num_processes / accelerator.gradient_accumulation_steps) + ) + lr_scheduler_check_completed = False + for epoch in range(starting_epoch, num_epochs): + model.train() + for step, batch in enumerate(train_dataloader): + with accelerator.accumulate(model): + outputs = model(**batch) + loss = outputs.loss + accelerator.backward(loss) + context = nullcontext + if args.tp_plan is not None: + from torch.distributed._tensor.experimental import implicit_replication + + context = implicit_replication + with context(): + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + # assert the learning rate after first optimizer step + if ( + accelerator.sync_gradients + and not lr_scheduler_check_completed + and linear_decay_scheduler + and accelerator.state.mixed_precision == "no" + ): + assert lr_scheduler.get_last_lr()[0] == expected_lr_after_first_optim_step, ( + f"Wrong lr found at second step, expected {expected_lr_after_first_optim_step}, got {lr_scheduler.get_last_lr()[0]}" + ) + lr_scheduler_check_completed = True + + model.eval() + samples_seen = 0 + for step, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits.argmax(dim=-1) + # It is slightly faster to call this once, than multiple times + predictions, references = accelerator.gather( + (predictions, batch["labels"]) + ) # If we are in a multiprocess environment, the last batch has duplicates + if accelerator.use_distributed: + if step == len(eval_dataloader) - 1: + predictions = predictions[: len(eval_dataloader.dataset) - samples_seen] + references = references[: len(eval_dataloader.dataset) - samples_seen] + else: + samples_seen += references.shape[0] + metric.add_batch( + predictions=predictions, + references=references, + ) + + eval_metric = metric.compute() + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}:", eval_metric) + performance_metric[f"epoch-{epoch}"] = eval_metric["accuracy"] + + if best_performance < eval_metric["accuracy"]: + best_performance = eval_metric["accuracy"] + + # check that the LR is 0 + if linear_decay_scheduler and accelerator.state.mixed_precision == "no": + assert lr_scheduler.get_last_lr()[0] == 0, ( + f"Wrong lr found at last step, expected 0, got {lr_scheduler.get_last_lr()[0]}" + ) + + if args.performance_lower_bound is not None: + assert args.performance_lower_bound <= best_performance, ( + f"Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}" + ) + + accelerator.wait_for_everyone() + if accelerator.is_main_process: + with open(os.path.join(args.output_dir, "all_results.json"), "w") as f: + json.dump(performance_metric, f) + + # TODO: skip saving of the model test for TP until the feature lands + if args.tp_plan is None: + # Finally try saving the model + accelerator.save_model(model, args.output_dir) + accelerator.wait_for_everyone() + if args.tp_plan is None: + assert Path(args.output_dir, SAFE_WEIGHTS_NAME).exists(), ( + "Model was not saved when calling `Accelerator.save_model`" + ) + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage.") + parser.add_argument( + "--model_name_or_path", + type=str, + default="bert-base-cased", + help="Path to pretrained model or model identifier from huggingface.co/models.", + required=False, + ) + parser.add_argument( + "--output_dir", + type=str, + default=".", + help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.", + ) + parser.add_argument( + "--performance_lower_bound", + type=float, + default=None, + help="Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.", + ) + parser.add_argument( + "--num_epochs", + type=int, + default=3, + help="Number of train epochs.", + ) + parser.add_argument( + "--add_pad_token", + type=bool, + default=False, + help="To add pad token if not exists.", + ) + parser.add_argument( + "--tp_plan", + type=str, + default=None, + help="pass 'auto' to use TP", + ) + parser.add_argument( + "--tp_size", + type=int, + default=None, + help="TP size to be used to shard the model", + ) + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_pippy.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_pippy.py new file mode 100644 index 0000000000000000000000000000000000000000..1dbd86c46b4a0c12df8ea4d736c7cd1e03f81813 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_pippy.py @@ -0,0 +1,117 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import torch +from transformers import ( + BertConfig, + BertForMaskedLM, + GPT2Config, + GPT2ForSequenceClassification, +) + +from accelerate import PartialState +from accelerate.inference import prepare_pippy +from accelerate.test_utils import torch_device +from accelerate.utils import DistributedType, set_seed + + +model_to_config = { + "bert": (BertForMaskedLM, BertConfig, 512), + "gpt2": (GPT2ForSequenceClassification, GPT2Config, 1024), +} + + +def get_model_and_data_for_text(model_name, device, num_processes: int = 2): + initializer, config, seq_len = model_to_config[model_name] + config_args = {} + # Eventually needed for batch inference tests on gpt-2 when bs != 1 + # if model_name == "gpt2": + # config_args["pad_token_id"] = 0 + model_config = config(**config_args) + model = initializer(model_config) + kwargs = dict(low=0, high=model_config.vocab_size, device=device, dtype=torch.int64, requires_grad=False) + trace_input = torch.randint(size=(1, seq_len), **kwargs) + inference_inputs = torch.randint(size=(num_processes, seq_len), **kwargs) + return model, trace_input, inference_inputs + + +def test_bert(batch_size: int = 2): + set_seed(42) + state = PartialState() + model, trace_input, inference_inputs = get_model_and_data_for_text("bert", "cpu", batch_size) + model = prepare_pippy(model, example_args=(trace_input,), no_split_module_classes=model._no_split_modules) + # For inference args need to be a tuple + inputs = inference_inputs.to(torch_device) + with torch.no_grad(): + output = model(inputs) + # Zach: Check that we just grab the real outputs we need at the end + if not state.is_last_process: + assert output is None, "Output was not generated on just the last process!" + else: + assert output is not None, "Output was not generated in the last process!" + + +def test_gpt2(batch_size: int = 2): + set_seed(42) + state = PartialState() + model, trace_input, inference_inputs = get_model_and_data_for_text("gpt2", "cpu", batch_size) + model = prepare_pippy(model, example_args=(trace_input,), no_split_module_classes=model._no_split_modules) + # For inference args need to be a tuple + inputs = inference_inputs.to(torch_device) + with torch.no_grad(): + output = model(inputs) + # Zach: Check that we just grab the real outputs we need at the end + if not state.is_last_process: + assert output is None, "Output was not generated on just the last process!" + else: + assert output is not None, "Output was not generated in the last process!" + + +# Currently disabled, enable again once PyTorch pippy interface can trace a resnet34 +# def test_resnet(batch_size: int = 2): +# set_seed(42) +# state = PartialState() +# model = resnet34() +# input_tensor = torch.rand(1, 3, 224, 224) +# model = prepare_pippy( +# model, +# example_args=(input_tensor,), +# ) +# inference_inputs = torch.rand(batch_size, 3, 224, 224) +# inputs = send_to_device(inference_inputs, torch_device) +# with torch.no_grad(): +# output = model(inputs) +# # Zach: Check that we just grab the real outputs we need at the end +# if not state.is_last_process: +# assert output is None, "Output was not generated on just the last process!" +# else: +# assert output is not None, "Output was not generated in the last process!" + + +if __name__ == "__main__": + state = PartialState() + state.print("Testing pippy integration...") + try: + if state.distributed_type in [DistributedType.MULTI_GPU, DistributedType.MULTI_XPU, DistributedType.MULTI_HPU]: + state.print("Testing GPT2...") + test_gpt2() + # Issue: When modifying the tokenizer for batch GPT2 inference, there's an issue + # due to references + # NameError: cannot access free variable 'chunk_args_list' where it is not associated with a value in enclosing scope + # test_gpt2(3) + state.print("Testing BERT...") + test_bert() + else: + print("Less than two GPUs found, not running tests!") + finally: + state.destroy_process_group() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_zero3_integration.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_zero3_integration.py new file mode 100644 index 0000000000000000000000000000000000000000..f5352b19980288115d2442229620105b8440d03d --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_zero3_integration.py @@ -0,0 +1,59 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch.distributed + +from accelerate.test_utils import require_huggingface_suite, torch_device +from accelerate.utils import is_transformers_available + + +if is_transformers_available(): + from transformers import AutoModel, TrainingArguments + + +GPT2_TINY = "sshleifer/tiny-gpt2" + + +@require_huggingface_suite +def init_torch_dist_then_launch_deepspeed(): + if torch_device == "xpu": + backend = "ccl" + elif torch_device == "hpu": + backend = "hccl" + else: + backend = "nccl" + + torch.distributed.init_process_group(backend=backend) + deepspeed_config = { + "zero_optimization": { + "stage": 3, + }, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + } + train_args = TrainingArguments( + output_dir="./", + deepspeed=deepspeed_config, + ) + model = AutoModel.from_pretrained(GPT2_TINY) + assert train_args is not None + assert model is not None + + +def main(): + init_torch_dist_then_launch_deepspeed() + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_cli.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..fc9dd1d36e8f2949d6e3cebb8ce65efbf0b9e5e4 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_cli.py @@ -0,0 +1,32 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import torch + +from accelerate.utils import is_xpu_available + + +def main(): + accelerator_type = "GPU" + num_accelerators = 0 + if torch.cuda.is_available(): + num_accelerators = torch.cuda.device_count() + accelerator_type = "GPU" + elif is_xpu_available(): + num_accelerators = torch.xpu.device_count() + accelerator_type = "XPU" + print(f"Successfully ran on {num_accelerators} {accelerator_type}s") + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_ddp_comm_hook.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_ddp_comm_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..0db5844e026d1c035670e518a8f81d33136ea665 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_ddp_comm_hook.py @@ -0,0 +1,85 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import torch + +from accelerate import Accelerator, DDPCommunicationHookType, DistributedDataParallelKwargs, PartialState +from accelerate.utils import is_hpu_available + + +class MockModel(torch.nn.Module): + def __init__(self): + super().__init__() + torch.manual_seed(0) + self.p = torch.nn.Parameter(torch.randn(40, 20)) + + def forward(self, x, rank): + return self.p * (x ** (1 + rank)) + + +def _run_and_get_grads(model, rank): + torch.manual_seed(2024) + input = torch.randn(40, 20) + output = model(input, rank) + output.mean().backward() + param = next(model.parameters()) + return param.grad + + +def test_ddp_comm_hook(comm_hook, comm_wrapper, comm_state_option): + ddp_kwargs = DistributedDataParallelKwargs( + comm_hook=comm_hook, + comm_wrapper=comm_wrapper, + comm_state_option=comm_state_option, + ) + accelerator = Accelerator(kwargs_handlers=[ddp_kwargs]) + + model = accelerator.prepare(MockModel()) + hook_grads = _run_and_get_grads(model, accelerator.local_process_index) + + reference_model = torch.nn.parallel.DistributedDataParallel( + MockModel().to(accelerator.device), + device_ids=[accelerator.local_process_index], + output_device=accelerator.local_process_index, + ) + reference_grads = _run_and_get_grads(reference_model, accelerator.local_process_index) + + torch.testing.assert_close(hook_grads, reference_grads, rtol=1e-2, atol=1e-2) + + +def main(): + for comm_hook, comm_wrapper, comm_state_option in [ + (DDPCommunicationHookType.NO, DDPCommunicationHookType.NO, {}), + (DDPCommunicationHookType.FP16, DDPCommunicationHookType.NO, {}), + (DDPCommunicationHookType.BF16, DDPCommunicationHookType.NO, {}), + (DDPCommunicationHookType.POWER_SGD, DDPCommunicationHookType.NO, {}), + (DDPCommunicationHookType.POWER_SGD, DDPCommunicationHookType.FP16, {}), + (DDPCommunicationHookType.POWER_SGD, DDPCommunicationHookType.BF16, {}), + (DDPCommunicationHookType.POWER_SGD, DDPCommunicationHookType.NO, {"matrix_approximation_rank": 2}), + (DDPCommunicationHookType.BATCHED_POWER_SGD, DDPCommunicationHookType.NO, {}), + (DDPCommunicationHookType.BATCHED_POWER_SGD, DDPCommunicationHookType.FP16, {}), + (DDPCommunicationHookType.BATCHED_POWER_SGD, DDPCommunicationHookType.BF16, {}), + ]: + if is_hpu_available(): + HPU_UNSUPPORTED_COMM_HOOKS = {DDPCommunicationHookType.FP16, DDPCommunicationHookType.BF16} + if comm_hook in HPU_UNSUPPORTED_COMM_HOOKS or comm_wrapper in HPU_UNSUPPORTED_COMM_HOOKS: + print(f"Skipping test DDP comm hook: {comm_hook}, comm wrapper: {comm_wrapper} on HPU") + continue + + print(f"Test DDP comm hook: {comm_hook}, comm wrapper: {comm_wrapper}") + test_ddp_comm_hook(comm_hook, comm_wrapper, comm_state_option) + PartialState().destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_distributed_data_loop.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_distributed_data_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..08cbbeb844bcc3189c99d328580c251aeafc2052 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_distributed_data_loop.py @@ -0,0 +1,410 @@ +#!/usr/bin/env python + +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pickle +import tempfile +import warnings +from unittest.mock import Mock + +import torch +from torch.utils.data import ( + BatchSampler, + DataLoader, + Dataset, + IterableDataset, + RandomSampler, + TensorDataset, + default_collate, +) + +from accelerate.accelerator import Accelerator, DataLoaderConfiguration +from accelerate.utils.dataclasses import DistributedType + + +NUM_ELEMENTS = 22 +NUM_WORKERS = 4 +BATCH_SIZE = 4 + + +class DummyDataset(Dataset): + def __len__(self): + return NUM_ELEMENTS + + def __getitem__(self, index): + squeeze = False + + if isinstance(index, int): + index = [index] + squeeze = True + elif isinstance(index, slice): + index = list(range(*index.indices(self.size))) + else: + index = list(index) + + batch = [{"index": i, "label": i % 2, "random_augmentation": torch.rand(1).item()} for i in index] + + if squeeze: + batch = batch[0] + + return batch + + +class DummyIterableDataset(IterableDataset): + def __init__(self, data): + self.data = data + + def __iter__(self): + yield from self.data + + +def create_accelerator(even_batches=True): + dataloader_config = DataLoaderConfiguration(even_batches=even_batches) + accelerator = Accelerator(dataloader_config=dataloader_config) + assert accelerator.num_processes == 2, "this script expects that two GPUs are available" + return accelerator + + +def create_dataloader( + accelerator: Accelerator, dataset_size: int, batch_size: int, iterable: bool = False, shuffle: bool = False +): + """ + Create a simple DataLoader to use during the test cases + """ + values = torch.as_tensor(range(dataset_size)) + if shuffle: + values = values[torch.randperm(values.size(0))] + if iterable: + dataset = DummyIterableDataset(values) + else: + dataset = TensorDataset(torch.as_tensor(range(dataset_size))) + + dl = DataLoader(dataset, batch_size=batch_size) + dl = accelerator.prepare(dl) + + return dl + + +def verify_dataloader_batch_sizes( + accelerator: Accelerator, + dataset_size: int, + batch_size: int, + process_0_expected_batch_sizes: list[int], + process_1_expected_batch_sizes: list[int], +): + """ + A helper function for verifying the batch sizes coming from a prepared dataloader in each process + """ + dl = create_dataloader(accelerator=accelerator, dataset_size=dataset_size, batch_size=batch_size) + + batch_sizes = [len(batch[0]) for batch in dl] + + if accelerator.process_index == 0: + assert batch_sizes == process_0_expected_batch_sizes + elif accelerator.process_index == 1: + assert batch_sizes == process_1_expected_batch_sizes + + +def test_default_ensures_even_batch_sizes(): + accelerator = create_accelerator() + + # without padding, we would expect a different number of batches + verify_dataloader_batch_sizes( + accelerator, + dataset_size=3, + batch_size=1, + process_0_expected_batch_sizes=[1, 1], + process_1_expected_batch_sizes=[1, 1], + ) + + # without padding, we would expect the same number of batches, but different sizes + verify_dataloader_batch_sizes( + accelerator, + dataset_size=7, + batch_size=2, + process_0_expected_batch_sizes=[2, 2], + process_1_expected_batch_sizes=[2, 2], + ) + + +def test_can_disable_even_batches(): + accelerator = create_accelerator(even_batches=False) + + verify_dataloader_batch_sizes( + accelerator, + dataset_size=3, + batch_size=1, + process_0_expected_batch_sizes=[1, 1], + process_1_expected_batch_sizes=[1], + ) + + verify_dataloader_batch_sizes( + accelerator, + dataset_size=7, + batch_size=2, + process_0_expected_batch_sizes=[2, 2], + process_1_expected_batch_sizes=[2, 1], + ) + + +def test_can_join_uneven_inputs(): + accelerator = create_accelerator(even_batches=False) + + model = torch.nn.Linear(1, 1) + ddp_model = accelerator.prepare(model) + + dl = create_dataloader(accelerator, dataset_size=3, batch_size=1) + + batch_idxs = [] + with accelerator.join_uneven_inputs([ddp_model]): + for batch_idx, batch in enumerate(dl): + output = ddp_model(batch[0].float()) + loss = output.sum() + loss.backward() + batch_idxs.append(batch_idx) + + accelerator.wait_for_everyone() + + if accelerator.process_index == 0: + assert batch_idxs == [0, 1] + elif accelerator.process_index == 1: + assert batch_idxs == [0] + + +def test_join_raises_warning_for_non_ddp_distributed(accelerator): + with warnings.catch_warnings(record=True) as w: + with accelerator.join_uneven_inputs([Mock()]): + pass + + assert issubclass(w[-1].category, UserWarning) + assert "only supported for multi-GPU" in str(w[-1].message) + + +def test_join_can_override_even_batches(): + default_even_batches = True + overridden_even_batches = False + accelerator = create_accelerator(even_batches=default_even_batches) + model = torch.nn.Linear(1, 1) + ddp_model = accelerator.prepare(model) + train_dl = create_dataloader(accelerator, dataset_size=3, batch_size=1) + valid_dl = create_dataloader(accelerator, dataset_size=3, batch_size=1) + + with accelerator.join_uneven_inputs([ddp_model], even_batches=overridden_even_batches): + train_dl_overridden_value = train_dl.batch_sampler.even_batches + valid_dl_overridden_value = valid_dl.batch_sampler.even_batches + + assert train_dl_overridden_value == overridden_even_batches + assert valid_dl_overridden_value == overridden_even_batches + assert train_dl.batch_sampler.even_batches == default_even_batches + assert valid_dl.batch_sampler.even_batches == default_even_batches + + +def test_join_can_override_for_mixed_type_dataloaders(): + default_even_batches = True + overridden_even_batches = False + accelerator = create_accelerator(even_batches=default_even_batches) + model = torch.nn.Linear(1, 1) + ddp_model = accelerator.prepare(model) + create_dataloader(accelerator, dataset_size=3, batch_size=1, iterable=True) + batch_dl = create_dataloader(accelerator, dataset_size=3, batch_size=1) + + with warnings.catch_warnings(): + warnings.filterwarnings("ignore") + try: + with accelerator.join_uneven_inputs([ddp_model], even_batches=overridden_even_batches): + batch_dl_overridden_value = batch_dl.batch_sampler.even_batches + except AttributeError: + # ensure attribute error is not raised when processing iterable dl + raise AssertionError + + assert batch_dl_overridden_value == overridden_even_batches + assert batch_dl.batch_sampler.even_batches == default_even_batches + + +def test_join_raises_warning_for_iterable_when_overriding_even_batches(): + accelerator = create_accelerator() + model = torch.nn.Linear(1, 1) + ddp_model = accelerator.prepare(model) + create_dataloader(accelerator, dataset_size=3, batch_size=1, iterable=True) + + with warnings.catch_warnings(record=True) as w: + with accelerator.join_uneven_inputs([ddp_model], even_batches=False): + pass + + assert issubclass(w[-1].category, UserWarning) + assert "only supported for map-style datasets" in str(w[-1].message) + + +def test_pickle_accelerator(): + accelerator = create_accelerator() + data_loader = create_dataloader(accelerator, dataset_size=32, batch_size=4) + _ = accelerator.prepare(data_loader) + pickled_accelerator = pickle.dumps(accelerator) + unpickled_accelerator = pickle.loads(pickled_accelerator) + # TODO: Maybe this should be implemented as __eq__ for AcceleratorState? + assert accelerator.state.__dict__ == unpickled_accelerator.state.__dict__ + + +def test_data_loader(data_loader, accelerator): + # Prepare the DataLoader + data_loader = accelerator.prepare(data_loader) + + all_examples = [] + for i, batch in enumerate(data_loader): + index, _ = accelerator.gather_for_metrics((batch["index"], batch["label"])) + all_examples.extend(index.detach().cpu().numpy().tolist()) + + # Sort the examples + sorted_all_examples = sorted(all_examples) + + # Check if all elements are present in the sorted list of iterated samples + assert len(set(sorted_all_examples)) == NUM_ELEMENTS, ( + "Not all the dataset elements have been iterated in an epoch due to duplication of samples across processes." + ) + + +def test_stateful_dataloader(accelerator): + """ + Tests that a stateful dataloader can be iterated over, saved after a few batches using `load_state_dict`, and then + resumed from the saved state. + + The result should be the same as the rest of the data that iterated over after saving. + """ + old_dataloader_config = accelerator.dataloader_config + try: + accelerator.dataloader_config = DataLoaderConfiguration(use_stateful_dataloader=True) + prepared_dl = create_dataloader( + accelerator, dataset_size=32 * accelerator.num_processes, batch_size=4, iterable=True, shuffle=True + ) + untrained_batches = [] + # Calculate what step that will be + total_batches = 32 * accelerator.num_processes // (4 * accelerator.num_processes) + last_batch_num = total_batches - 1 + for step, batch in enumerate(prepared_dl): + # Step just before + if step == last_batch_num - 1: + state_dict = prepared_dl.state_dict() + if step >= last_batch_num: + # Otherwise grab the "unseen" batches + untrained_batches.append(batch) + not_skipped_batches = accelerator.gather(untrained_batches) + prepared_dl.load_state_dict(state_dict) + resumed_batches = [] + for batch in prepared_dl: + resumed_batches.append(batch) + resumed_batches = accelerator.gather(resumed_batches) + for b1, b2 in zip(not_skipped_batches, resumed_batches): + for v1, v2 in zip(b1, b2): + assert torch.equal(v1, v2), f"Batch {b1} and {b2} are not equal" + finally: + accelerator.dataloader_config = old_dataloader_config + + +def test_stateful_dataloader_save_state(accelerator): + """ + Tests that a stateful dataloader can be iterated over, saved after a few batches using `Accelerator.save_state`, + and then resumed from the saved state. + + The result should be the same as the rest of the data that iterated over after saving. + """ + old_dataloader_config = accelerator.dataloader_config + try: + with tempfile.TemporaryDirectory() as tmpdir: + accelerator.dataloader_config = DataLoaderConfiguration(use_stateful_dataloader=True) + prepared_dl = create_dataloader( + accelerator, dataset_size=32 * accelerator.num_processes, batch_size=4, iterable=True, shuffle=True + ) + untrained_batches = [] + # Calculate what step that will be + total_batches = 32 * accelerator.num_processes // (4 * accelerator.num_processes) + last_batch_num = total_batches - 1 + for step, batch in enumerate(prepared_dl): + # Step just before + if step == last_batch_num - 1: + accelerator.save_state(tmpdir) + if step >= last_batch_num: + # Otherwise grab the "unseen" batches + untrained_batches.append(batch) + not_skipped_batches = accelerator.gather(untrained_batches) + accelerator.load_state(tmpdir) + resumed_batches = [] + for batch in prepared_dl: + resumed_batches.append(batch) + resumed_batches = accelerator.gather(resumed_batches) + for b1, b2 in zip(not_skipped_batches, resumed_batches): + for v1, v2 in zip(b1, b2): + assert torch.equal(v1, v2), f"Batch {b1} and {b2} are not equal" + finally: + accelerator.dataloader_config = old_dataloader_config + + +def main(): + accelerator = create_accelerator() + torch.manual_seed(accelerator.process_index) + + accelerator.print("Test that even_batches variable ensures uniform batches across processes") + test_default_ensures_even_batch_sizes() + + accelerator.print("Run tests with even_batches disabled") + test_can_disable_even_batches() + + accelerator.print("Test joining uneven inputs") + test_can_join_uneven_inputs() + + accelerator.print("Test overriding even_batches when joining uneven inputs") + test_join_can_override_even_batches() + + accelerator.print("Test overriding even_batches for mixed dataloader types") + test_join_can_override_for_mixed_type_dataloaders() + + accelerator.print("Test overriding even_batches raises a warning for iterable dataloaders") + test_join_raises_warning_for_iterable_when_overriding_even_batches() + + accelerator.print("Test join with non DDP distributed raises warning") + original_state = accelerator.state.distributed_type + accelerator.state.distributed_type = DistributedType.FSDP + test_join_raises_warning_for_non_ddp_distributed(accelerator) + accelerator.state.distributed_type = original_state + + accelerator.print("Test pickling an accelerator") + test_pickle_accelerator() + + dataset = DummyDataset() + + accelerator.print("Test DataLoader with shuffle=False") + loader = DataLoader(dataset, shuffle=False, batch_size=BATCH_SIZE, num_workers=NUM_WORKERS) + test_data_loader(loader, accelerator) + + accelerator.print("Test DataLoader with shuffle=True") + loader = DataLoader(dataset, shuffle=True, batch_size=BATCH_SIZE, num_workers=NUM_WORKERS) + test_data_loader(loader, accelerator) + + accelerator.print("Test DataLoader with batch_sampler") + sampler = BatchSampler(RandomSampler(dataset), batch_size=BATCH_SIZE, drop_last=False) + loader = DataLoader(dataset, batch_sampler=sampler, num_workers=NUM_WORKERS) + test_data_loader(loader, accelerator) + + accelerator.print("Test DataLoader with sampler as an instance of `BatchSampler`") + sampler = BatchSampler(RandomSampler(dataset), batch_size=BATCH_SIZE, drop_last=False) + loader = DataLoader(dataset, sampler=sampler, batch_size=None, collate_fn=default_collate, num_workers=NUM_WORKERS) + test_data_loader(loader, accelerator) + test_stateful_dataloader(accelerator) + test_stateful_dataloader_save_state(accelerator) + + accelerator.end_training() + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_merge_weights.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_merge_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..f280c8fa17919367001389a8efcd78faaa041f0c --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_merge_weights.py @@ -0,0 +1,158 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import gc +import logging +import shutil +from pathlib import Path + +import torch +from safetensors.torch import load_file +from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy, StateDictType +from torch.utils.data import DataLoader + +from accelerate import Accelerator, FullyShardedDataParallelPlugin +from accelerate.commands.merge import merge_command, merge_command_parser +from accelerate.state import AcceleratorState +from accelerate.test_utils import torch_device +from accelerate.test_utils.training import RegressionDataset +from accelerate.utils import merge_fsdp_weights, patch_environment, save_fsdp_model + + +logging.basicConfig(level=logging.INFO) + +parser = merge_command_parser() + + +class TinyModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear1 = torch.nn.Linear(16, 16) + self.activation = torch.nn.ReLU() + self.linear2 = torch.nn.Linear(16, 16) + self.softmax = torch.nn.Softmax() + + def forward(self, x): + return self.linear2(self.activation(self.linear1(x))) + + +def setup(): + if AcceleratorState._shared_state != {}: + AcceleratorState()._reset_state() + plugin = FullyShardedDataParallelPlugin( + sharding_strategy=ShardingStrategy.FULL_SHARD, state_dict_type=StateDictType.SHARDED_STATE_DICT + ) + model = TinyModel() + with patch_environment(fsdp_auto_wrap_policy="SIZE_BASED_WRAP"): + plugin.set_auto_wrap_policy(model) + accelerator = Accelerator(fsdp_plugin=plugin) + model = accelerator.prepare(model) + return model, plugin, accelerator + + +def mock_training(accelerator, model): + train_set = RegressionDataset(length=128, seed=42) + train_dl = DataLoader(train_set, batch_size=16, shuffle=False) + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + + train_dl, model, optimizer = accelerator.prepare(train_dl, model, optimizer) + for _ in range(3): + for batch in train_dl: + model.zero_grad() + output = model(batch["x"]) + loss = torch.nn.functional.mse_loss(output, batch["y"]) + accelerator.backward(loss) + optimizer.step() + return model + + +def check_weights(operation, state_1, state_2): + for weight_1, weight_2 in zip(state_1.values(), state_2.values()): + if operation == "same": + assert torch.allclose(weight_1, weight_2) + else: + assert not torch.allclose(weight_1, weight_2) + + +def check_safetensors_weights(path, model): + safe_state_dict = load_file(path / "model.safetensors") + safe_loaded_model = TinyModel().to(torch_device) + check_weights("diff", model.state_dict(), safe_loaded_model.state_dict()) + safe_loaded_model.load_state_dict(safe_state_dict) + check_weights("same", model.state_dict(), safe_loaded_model.state_dict()) + + +def check_pytorch_weights(path, model): + nonsafe_state_dict = torch.load(path / "pytorch_model.bin", weights_only=True) + nonsafe_loaded_model = TinyModel().to(torch_device) + check_weights("diff", model.state_dict(), nonsafe_loaded_model.state_dict()) + nonsafe_loaded_model.load_state_dict(nonsafe_state_dict) + check_weights("same", model.state_dict(), nonsafe_loaded_model.state_dict()) + + +def test_merge_weights_safetensors(model, path): + # Should now be saved at `path/merged.safetensors` + merge_fsdp_weights(path / "pytorch_model_fsdp_0", path, safe_serialization=True) + check_safetensors_weights(path, model) + + +def test_merge_weights_command_safetensors(model, path): + args = parser.parse_args([str(path / "pytorch_model_fsdp_0"), str(path)]) + merge_command(args) + check_safetensors_weights(path, model) + + +def test_merge_weights_pytorch(model, path): + # Should now be saved at `path/merged.bin` + merge_fsdp_weights(path / "pytorch_model_fsdp_0", path, safe_serialization=False) + check_pytorch_weights(path, model) + + +def test_merge_weights_command_pytorch(model, path): + args = parser.parse_args([str(path / "pytorch_model_fsdp_0"), str(path), "--unsafe_serialization"]) + merge_command(args) + check_pytorch_weights(path, model) + + +if __name__ == "__main__": + # Note this test requires at least two accelerators! + model, plugin, accelerator = setup() + if accelerator.num_processes > 1: + try: + # Initial setup for things + out_path = Path("test_merge_weights_fsdp_weights") + if not out_path.exists(): + out_path.mkdir(parents=True, exist_ok=True) + + # Train briefly once weights aren't the baseline + model = mock_training(accelerator, model) + accelerator.wait_for_everyone() + + gc.collect() # Needed for some lingering refs after training + save_fsdp_model(plugin, accelerator, model, out_path) + accelerator.wait_for_everyone() + + # Finally we can test + test_merge_weights_safetensors(model, out_path) + test_merge_weights_command_safetensors(model, out_path) + test_merge_weights_pytorch(model, out_path) + test_merge_weights_command_pytorch(model, out_path) + except Exception: + raise + finally: + # Cleanup in case of any failures + if accelerator.is_main_process: + shutil.rmtree(out_path) + accelerator.wait_for_everyone() + accelerator.end_training() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_notebook.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_notebook.py new file mode 100644 index 0000000000000000000000000000000000000000..267c11b50b22250e781f94e3643b8895cc6aeb02 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_notebook.py @@ -0,0 +1,118 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Test file to ensure that in general certain situational setups for notebooks work. +""" + +import os +import time +from multiprocessing import Queue + +from pytest import mark, raises +from torch.distributed.elastic.multiprocessing.errors import ChildFailedError + +from accelerate import PartialState, notebook_launcher +from accelerate.test_utils import require_bnb +from accelerate.utils import is_bnb_available + + +def basic_function(): + # Just prints the PartialState + print(f"PartialState:\n{PartialState()}") + + +def tough_nut_function(queue: Queue): + if queue.empty(): + return + trial = queue.get() + if trial > 0: + queue.put(trial - 1) + raise RuntimeError("The nut hasn't cracked yet! Try again.") + + print(f"PartialState:\n{PartialState()}") + + +def bipolar_sleep_function(sleep_sec: int): + state = PartialState() + if state.process_index % 2 == 0: + raise RuntimeError("I'm an even process. I don't like to sleep.") + else: + time.sleep(sleep_sec) + + +NUM_PROCESSES = int(os.environ.get("ACCELERATE_NUM_PROCESSES", 1)) + + +def test_can_initialize(): + notebook_launcher(basic_function, (), num_processes=NUM_PROCESSES) + + +@mark.skipif(NUM_PROCESSES < 2, reason="Need at least 2 processes to test static rendezvous backends") +def test_static_rdzv_backend(): + notebook_launcher(basic_function, (), num_processes=NUM_PROCESSES, rdzv_backend="static") + + +@mark.skipif(NUM_PROCESSES < 2, reason="Need at least 2 processes to test c10d rendezvous backends") +def test_c10d_rdzv_backend(): + notebook_launcher(basic_function, (), num_processes=NUM_PROCESSES, rdzv_backend="c10d") + + +@mark.skipif(NUM_PROCESSES < 2, reason="Need at least 2 processes to test fault tolerance") +def test_fault_tolerant(max_restarts: int = 3): + queue = Queue() + queue.put(max_restarts) + notebook_launcher(tough_nut_function, (queue,), num_processes=NUM_PROCESSES, max_restarts=max_restarts) + + +@mark.skipif(NUM_PROCESSES < 2, reason="Need at least 2 processes to test monitoring") +def test_monitoring(monitor_interval: float = 0.01, sleep_sec: int = 100): + start_time = time.time() + with raises(ChildFailedError, match="I'm an even process. I don't like to sleep."): + notebook_launcher( + bipolar_sleep_function, + (sleep_sec,), + num_processes=NUM_PROCESSES, + monitor_interval=monitor_interval, + ) + assert time.time() - start_time < sleep_sec, "Monitoring did not stop the process in time." + + +@require_bnb +def test_problematic_imports(): + with raises(RuntimeError, match="Please keep these imports"): + import bitsandbytes as bnb # noqa: F401 + + notebook_launcher(basic_function, (), num_processes=NUM_PROCESSES) + + +def main(): + print("Test basic notebook can be ran") + test_can_initialize() + print("Test static rendezvous backend") + test_static_rdzv_backend() + print("Test c10d rendezvous backend") + test_c10d_rdzv_backend() + print("Test fault tolerant") + test_fault_tolerant() + print("Test monitoring") + test_monitoring() + if is_bnb_available(): + print("Test problematic imports (bnb)") + test_problematic_imports() + if NUM_PROCESSES > 1: + PartialState().destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_ops.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..f8f535d7b25a7bda527901787261591364545c09 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_ops.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python + +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch + +from accelerate import PartialState +from accelerate.test_utils.testing import assert_exception +from accelerate.utils.dataclasses import DistributedType +from accelerate.utils.operations import ( + DistributedOperationException, + broadcast, + copy_tensor_to_devices, + gather, + gather_object, + pad_across_processes, + reduce, +) + + +def create_tensor(state): + return (torch.arange(state.num_processes) + 1.0 + (state.num_processes * state.process_index)).to(state.device) + + +def test_gather(state): + tensor = create_tensor(state) + gathered_tensor = gather(tensor) + assert gathered_tensor.tolist() == list(range(1, state.num_processes**2 + 1)) + + +def test_gather_object(state): + # Gather objects in TorchXLA is not supported. + if state.distributed_type == DistributedType.XLA: + return + obj = [state.process_index] + gathered_obj = gather_object(obj) + assert len(gathered_obj) == state.num_processes, f"{gathered_obj}, {len(gathered_obj)} != {state.num_processes}" + assert gathered_obj == list(range(state.num_processes)), f"{gathered_obj} != {list(range(state.num_processes))}" + + +def test_gather_non_contigous(state): + # Skip this test because the 'is_contiguous' function of XLA tensor always returns True. + if state.distributed_type == DistributedType.XLA: + return + + # Create a non-contiguous tensor (enforce non-contiguity after device memory allocation) + tensor = torch.arange(12, device=state.device).view(4, 3).t() + assert not tensor.is_contiguous() + # Shouldn't error out + _ = gather(tensor) + + +def test_broadcast(state): + tensor = create_tensor(state) + broadcasted_tensor = broadcast(tensor) + assert broadcasted_tensor.shape == torch.Size([state.num_processes]) + assert broadcasted_tensor.tolist() == list(range(1, state.num_processes + 1)) + + +def test_pad_across_processes(state): + # We need to pad the tensor with one more element if we are the main process + # to ensure that we can pad + if state.is_main_process: + tensor = torch.arange(state.num_processes + 1).to(state.device) + else: + tensor = torch.arange(state.num_processes).to(state.device) + padded_tensor = pad_across_processes(tensor) + assert padded_tensor.shape == torch.Size([state.num_processes + 1]) + if not state.is_main_process: + assert padded_tensor.tolist() == list(range(0, state.num_processes)) + [0] + + +def test_reduce_sum(state): + # For now runs on only two processes + if state.num_processes != 2: + return + tensor = create_tensor(state) + reduced_tensor = reduce(tensor, "sum") + truth_tensor = torch.tensor([4.0, 6]).to(state.device) + assert torch.allclose(reduced_tensor, truth_tensor), f"{reduced_tensor} != {truth_tensor}" + + +def test_reduce_mean(state): + # For now runs on only two processes + if state.num_processes != 2: + return + tensor = create_tensor(state) + reduced_tensor = reduce(tensor, "mean") + truth_tensor = torch.tensor([2.0, 3]).to(state.device) + assert torch.allclose(reduced_tensor, truth_tensor), f"{reduced_tensor} != {truth_tensor}" + + +def test_op_checker(state): + # Must be in a distributed state, and gathering is currently not supported in TorchXLA. + if state.distributed_type in [DistributedType.NO, DistributedType.XLA]: + return + state.debug = True + # `pad_across_processes` + if state.process_index == 0: + data = {"tensor": torch.tensor([[0.0, 1, 2, 3, 4]]).to(state.device)} + else: + data = {"tensor": torch.tensor([[[0.0, 1, 2, 3, 4, 5]]]).to(state.device)} + + with assert_exception(DistributedOperationException): + pad_across_processes(data, dim=0) + + # `reduce` + if state.process_index == 0: + data = {"tensor": torch.tensor([[0.0, 1, 2, 3, 4]]).to(state.device)} + else: + data = {"tensor": torch.tensor([[[0.0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]]).to(state.device)} + + with assert_exception(DistributedOperationException): + reduce(data) + + # `broadcast` + if state.process_index == 0: + data = {"tensor": torch.tensor([[0.0, 1, 2, 3, 4]]).to(state.device)} + else: + data = {"tensor": torch.tensor([[[0.0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]]).to(state.device)} + + with assert_exception(DistributedOperationException): + broadcast(data) + + state.debug = False + + +def test_copy_tensor_to_devices(state): + if state.distributed_type not in [DistributedType.MULTI_GPU, DistributedType.XLA]: + return + if state.is_main_process: + tensor = torch.tensor([1, 2, 3], dtype=torch.int).to(state.device) + else: + tensor = None + tensor = copy_tensor_to_devices(tensor) + assert torch.allclose(tensor, torch.tensor([1, 2, 3], dtype=torch.int, device=state.device)) + + +def _mp_fn(index): + # For xla_spawn (TPUs) + main() + + +def main(): + state = PartialState() + state.print(f"State: {state}") + state.print("testing gather") + test_gather(state) + state.print("testing gather_object") + test_gather_object(state) + state.print("testing gather non-contigous") + test_gather_non_contigous(state) + state.print("testing broadcast") + test_broadcast(state) + state.print("testing pad_across_processes") + test_pad_across_processes(state) + state.print("testing reduce_sum") + test_reduce_sum(state) + state.print("testing reduce_mean") + test_reduce_mean(state) + state.print("testing op_checker") + test_op_checker(state) + state.print("testing sending tensors across devices") + test_copy_tensor_to_devices(state) + state.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_script.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_script.py new file mode 100644 index 0000000000000000000000000000000000000000..fa0e3b601e38057e254067984042197098efdfd6 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_script.py @@ -0,0 +1,952 @@ +#!/usr/bin/env python + +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import contextlib +import io +import math +import time +from copy import deepcopy +from pathlib import Path + +import numpy as np +import torch +from torch.utils.data import DataLoader, Dataset + +from accelerate import Accelerator +from accelerate.data_loader import SeedableRandomSampler, prepare_data_loader +from accelerate.state import AcceleratorState +from accelerate.test_utils import RegressionDataset, are_the_same_tensors +from accelerate.utils import ( + DataLoaderConfiguration, + DistributedType, + gather, + gather_object, + is_bf16_available, + is_datasets_available, + is_fp16_available, + is_hpu_available, + is_ipex_available, + is_pytest_available, + is_xpu_available, + set_seed, + synchronize_rng_states, +) + + +# TODO: remove RegressionModel4XPU once ccl support empty buffer in broadcasting. +if is_xpu_available(): + from accelerate.test_utils import RegressionModel4XPU as RegressionModel +else: + from accelerate.test_utils import RegressionModel + +if is_hpu_available(): + ATOL = 1e-3 + RTOL = 1e-3 +else: + ATOL = 1e-6 + RTOL = 1e-6 + + +def generate_baseline_dataloader(train_set, generator, batch_size, use_seedable_sampler=False): + "Creates a dataloader that can also use the `SeedableRandomSampler`" + if use_seedable_sampler: + # The SeedableRandomSampler is needed during distributed setups + # for full reproducibility across processes with the `DataLoader` + sampler = SeedableRandomSampler( + generator=generator, + data_source=train_set, + num_samples=len(train_set), + ) + return DataLoader(train_set, batch_size=batch_size, sampler=sampler) + else: + return DataLoader(train_set, batch_size=batch_size, shuffle=True, generator=generator) + + +def print_main(state): + print(f"Printing from the main process {state.process_index}") + + +def print_local_main(state): + print(f"Printing from the local main process {state.local_process_index}") + + +def print_last(state): + print(f"Printing from the last process {state.process_index}") + + +def print_on(state, process_idx): + print(f"Printing from process {process_idx}: {state.process_index}") + + +def process_execution_check(): + accelerator = Accelerator() + num_processes = accelerator.num_processes + # Test main_process_first context manager + path = Path("check_main_process_first.txt") + with accelerator.main_process_first(): + if accelerator.is_main_process: + time.sleep(0.1) # ensure main process takes longest + with open(path, "a+") as f: + f.write("Currently in the main process\n") + else: + with open(path, "a+") as f: + f.write("Now on another process\n") + accelerator.wait_for_everyone() + + if accelerator.is_main_process: + with open(path) as f: + text = "".join(f.readlines()) + try: + assert text.startswith("Currently in the main process\n"), "Main process was not first" + if num_processes > 1: + assert text.endswith("Now on another process\n"), "Main process was not first" + assert text.count("Now on another process\n") == accelerator.num_processes - 1, ( + f"Only wrote to file {text.count('Now on another process') + 1} times, not {accelerator.num_processes}" + ) + except AssertionError: + path.unlink() + raise + + if accelerator.is_main_process and path.exists(): + path.unlink() + accelerator.wait_for_everyone() + # Test the decorators + f = io.StringIO() + with contextlib.redirect_stdout(f): + accelerator.on_main_process(print_main)(accelerator.state) + result = f.getvalue().rstrip() + if accelerator.is_main_process: + assert result == "Printing from the main process 0", f"{result} != Printing from the main process 0" + else: + assert f.getvalue().rstrip() == "", f'{result} != ""' + f.truncate(0) + f.seek(0) + + with contextlib.redirect_stdout(f): + accelerator.on_local_main_process(print_local_main)(accelerator.state) + if accelerator.is_local_main_process: + assert f.getvalue().rstrip() == "Printing from the local main process 0" + else: + assert f.getvalue().rstrip() == "" + f.truncate(0) + f.seek(0) + + with contextlib.redirect_stdout(f): + accelerator.on_last_process(print_last)(accelerator.state) + if accelerator.is_last_process: + assert f.getvalue().rstrip() == f"Printing from the last process {accelerator.state.num_processes - 1}" + else: + assert f.getvalue().rstrip() == "" + f.truncate(0) + f.seek(0) + + for process_idx in range(num_processes): + with contextlib.redirect_stdout(f): + accelerator.on_process(print_on, process_index=process_idx)(accelerator.state, process_idx) + if accelerator.process_index == process_idx: + assert f.getvalue().rstrip() == f"Printing from process {process_idx}: {accelerator.process_index}" + else: + assert f.getvalue().rstrip() == "" + f.truncate(0) + f.seek(0) + + +def init_state_check(): + # Test we can instantiate this twice in a row. + state = AcceleratorState() + if state.local_process_index == 0: + print("Testing, testing. 1, 2, 3.") + print(state) + + +def rng_sync_check(): + state = AcceleratorState() + synchronize_rng_states(["torch"]) + assert are_the_same_tensors(torch.get_rng_state()), "RNG states improperly synchronized on CPU." + if state.distributed_type == DistributedType.MULTI_GPU: + synchronize_rng_states(["cuda"]) + assert are_the_same_tensors(torch.cuda.get_rng_state()), "RNG states improperly synchronized on GPU." + elif state.distributed_type == DistributedType.MULTI_XPU: + synchronize_rng_states(["xpu"]) + assert are_the_same_tensors(torch.xpu.get_rng_state()), "RNG states improperly synchronized on XPU." + generator = torch.Generator() + synchronize_rng_states(["generator"], generator=generator) + assert are_the_same_tensors(generator.get_state()), "RNG states improperly synchronized in generator." + + if state.local_process_index == 0: + print("All rng are properly synched.") + + +def dl_preparation_check(): + state = AcceleratorState() + length = 32 * state.num_processes + + dl = DataLoader(range(length), batch_size=8) + dl = prepare_data_loader(dl, state.device, state.num_processes, state.process_index, put_on_device=True) + result = [] + for batch in dl: + result.append(gather(batch)) + result = torch.cat(result) + + assert torch.equal(result.cpu(), torch.arange(0, length).long()), "Wrong non-shuffled dataloader result." + + dl = DataLoader(range(length), batch_size=8) + dl = prepare_data_loader( + dl, + state.device, + state.num_processes, + state.process_index, + put_on_device=True, + split_batches=True, + ) + result = [] + for batch in dl: + result.append(gather(batch)) + result = torch.cat(result) + assert torch.equal(result.cpu(), torch.arange(0, length).long()), "Wrong non-shuffled dataloader result." + + if state.process_index == 0: + print("Non-shuffled dataloader passing.") + + dl = DataLoader(range(length), batch_size=8, shuffle=True) + dl = prepare_data_loader(dl, state.device, state.num_processes, state.process_index, put_on_device=True) + result = [] + for batch in dl: + result.append(gather(batch)) + result = torch.cat(result).tolist() + result.sort() + assert result == list(range(length)), "Wrong shuffled dataloader result." + + dl = DataLoader(range(length), batch_size=8, shuffle=True) + dl = prepare_data_loader( + dl, + state.device, + state.num_processes, + state.process_index, + put_on_device=True, + split_batches=True, + ) + result = [] + for batch in dl: + result.append(gather(batch)) + result = torch.cat(result).tolist() + result.sort() + assert result == list(range(length)), "Wrong shuffled dataloader result." + + if state.local_process_index == 0: + print("Shuffled dataloader passing.") + + +def central_dl_preparation_check(): + state = AcceleratorState() + length = 32 * state.num_processes + + dl = DataLoader(range(length), batch_size=8) + dl = prepare_data_loader( + dl, state.device, state.num_processes, state.process_index, put_on_device=True, dispatch_batches=True + ) + result = [] + for batch in dl: + result.append(gather(batch)) + result = torch.cat(result) + assert torch.equal(result.cpu(), torch.arange(0, length).long()), "Wrong non-shuffled dataloader result." + + dl = DataLoader(range(length), batch_size=8) + dl = prepare_data_loader( + dl, + state.device, + state.num_processes, + state.process_index, + put_on_device=True, + split_batches=True, + dispatch_batches=True, + ) + result = [] + for batch in dl: + result.append(gather(batch)) + result = torch.cat(result) + assert torch.equal(result.cpu(), torch.arange(0, length).long()), "Wrong non-shuffled dataloader result." + + if state.process_index == 0: + print("Non-shuffled central dataloader passing.") + + dl = DataLoader(range(length), batch_size=8, shuffle=True) + dl = prepare_data_loader( + dl, state.device, state.num_processes, state.process_index, put_on_device=True, dispatch_batches=True + ) + result = [] + for batch in dl: + result.append(gather(batch)) + result = torch.cat(result).tolist() + result.sort() + assert result == list(range(length)), "Wrong shuffled dataloader result." + + dl = DataLoader(range(length), batch_size=8, shuffle=True) + dl = prepare_data_loader( + dl, + state.device, + state.num_processes, + state.process_index, + put_on_device=True, + split_batches=True, + dispatch_batches=True, + ) + result = [] + for batch in dl: + result.append(gather(batch)) + result = torch.cat(result).tolist() + result.sort() + assert result == list(range(length)), "Wrong shuffled dataloader result." + + if state.local_process_index == 0: + print("Shuffled central dataloader passing.") + + +def custom_sampler_check(): + state = AcceleratorState() + + class CustomDataset(Dataset): + def __init__(self, data): + self.data = data + + def __len__(self): + return len(self.data) + + def __getitem__(self, index): + return self.data[index] + + class CustomBatchSampler: + def __init__(self, dataset_length: int, batch_size: int, shuffle: bool = True): + self.batch_size = batch_size + self.data_index = np.arange(dataset_length) + self.shuffle = shuffle + + def __iter__(self): + num_batches = len(self) + if self.shuffle: + index = np.random.permutation(self.data_index) + else: + index = self.data_index + output = np.array_split(index, num_batches) + yield from output + + def __len__(self): + return math.ceil(len(self.data_index) / self.batch_size) + + dataset = CustomDataset(range(32 * state.num_processes)) + sampler = CustomBatchSampler(len(dataset), batch_size=8) + dl = DataLoader(dataset, batch_sampler=sampler) + dl = prepare_data_loader(dl, state.device, state.num_processes, state.process_index) + # We need just ensure that `dl.batch_sampler` (or `dl.batch_sampler.batch_sampler` is indeed the old batch sampler + if hasattr(dl.batch_sampler, "batch_sampler"): + assert isinstance(dl.batch_sampler.batch_sampler, CustomBatchSampler), ( + "Custom sampler was changed after calling `prepare_data_loader`" + ) + else: + assert isinstance(dl.batch_sampler, CustomBatchSampler), ( + "Custom sampler was changed after calling `prepare_data_loader`" + ) + + +def check_seedable_sampler(): + # Set seed + set_seed(42) + train_set = RegressionDataset(length=10, seed=42) + train_dl = DataLoader(train_set, batch_size=2, shuffle=True) + + config = DataLoaderConfiguration(use_seedable_sampler=True) + accelerator = Accelerator(dataloader_config=config) + train_dl = accelerator.prepare(train_dl) + original_items = [] + for _ in range(3): + for batch in train_dl: + original_items.append(batch["x"]) + original_items = torch.cat(original_items) + + # Set seed again and the epoch + set_seed(42) + train_dl.set_epoch(0) + new_items = [] + for _ in range(3): + for batch in train_dl: + new_items.append(batch["x"]) + new_items = torch.cat(new_items) + assert torch.allclose(original_items, new_items), "Did not obtain the same items with the same seed and epoch." + + +def check_seedable_sampler_in_batch_sampler_shard(): + set_seed(42) + + config = DataLoaderConfiguration(use_seedable_sampler=True) + accelerator = Accelerator(dataloader_config=config) + assert accelerator.num_processes > 1, "This test requires more than one process." + + dataloader = DataLoader(list(range(10)), batch_size=1, shuffle=True) + prepared_data_loader = prepare_data_loader( + dataloader=dataloader, + use_seedable_sampler=True, + ) + + target_sampler = prepared_data_loader.batch_sampler.batch_sampler.sampler + assert isinstance(target_sampler, SeedableRandomSampler), ( + "Sampler in BatchSamplerShard is not SeedableRandomSampler." + ) + + +def check_seedable_sampler_with_data_seed(): + # Set seed + set_seed(42) + data_seed = 42 + train_set = RegressionDataset(length=10, seed=42) + train_dl = DataLoader(train_set, batch_size=2, shuffle=True) + + config = DataLoaderConfiguration(use_seedable_sampler=True, data_seed=data_seed) + accelerator = Accelerator(dataloader_config=config) + prepared_dl = accelerator.prepare(train_dl) + original_items = [] + for _ in range(3): + for batch in prepared_dl: + original_items.append(batch["x"]) + original_items = torch.cat(original_items) + + # Set new data seed + config.data_seed = 43 + accelerator = Accelerator(dataloader_config=config) + prepared_dl = accelerator.prepare(train_dl) + new_items = [] + for _ in range(3): + for batch in prepared_dl: + new_items.append(batch["x"]) + new_items = torch.cat(new_items) + assert not torch.allclose(original_items, new_items), "Obtained the same items with different data seed." + + +def mock_training(length, batch_size, generator, use_seedable_sampler=False): + set_seed(42) + generator.manual_seed(42) + train_set = RegressionDataset(length=length, seed=42) + + train_dl = generate_baseline_dataloader(train_set, generator, batch_size, use_seedable_sampler) + model = RegressionModel() + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + for epoch in range(3): + for batch in train_dl: + model.zero_grad() + output = model(batch["x"]) + loss = torch.nn.functional.mse_loss(output, batch["y"]) + loss.backward() + optimizer.step() + return train_set, model + + +def training_check(use_seedable_sampler=False): + state = AcceleratorState() + generator = torch.Generator() + batch_size = 8 + length = batch_size * 4 * state.num_processes + + train_set, old_model = mock_training(length, batch_size * state.num_processes, generator, use_seedable_sampler) + assert are_the_same_tensors(old_model.a), "Did not obtain the same model on both processes." + assert are_the_same_tensors(old_model.b), "Did not obtain the same model on both processes." + + accelerator = Accelerator() + train_dl = generate_baseline_dataloader(train_set, generator, batch_size, use_seedable_sampler) + model = RegressionModel() + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + + train_dl, model, optimizer = accelerator.prepare(train_dl, model, optimizer) + set_seed(42) + generator.manual_seed(42) + for _ in range(3): + for batch in train_dl: + model.zero_grad() + output = model(batch["x"]) + loss = torch.nn.functional.mse_loss(output, batch["y"]) + accelerator.backward(loss) + optimizer.step() + + model = accelerator.unwrap_model(model).cpu() + torch.testing.assert_close( + old_model.a, + model.a, + atol=ATOL, + rtol=RTOL, + msg=lambda msg: f"Did not obtain the same model on CPU or distributed training.\n{msg}", + ) + torch.testing.assert_close( + old_model.b, + model.b, + atol=ATOL, + rtol=RTOL, + msg=lambda msg: f"Did not obtain the same model on CPU or distributed training.\n{msg}", + ) + + accelerator.print("Training yielded the same results on one CPU or distributed setup with no batch split.") + + dataloader_config = DataLoaderConfiguration(split_batches=True, use_seedable_sampler=use_seedable_sampler) + accelerator = Accelerator(dataloader_config=dataloader_config) + train_dl = generate_baseline_dataloader( + train_set, generator, batch_size * state.num_processes, use_seedable_sampler + ) + model = RegressionModel() + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + + train_dl, model, optimizer = accelerator.prepare(train_dl, model, optimizer) + set_seed(42) + generator.manual_seed(42) + for _ in range(3): + for batch in train_dl: + model.zero_grad() + output = model(batch["x"]) + loss = torch.nn.functional.mse_loss(output, batch["y"]) + accelerator.backward(loss) + optimizer.step() + + model = accelerator.unwrap_model(model).cpu() + torch.testing.assert_close( + old_model.a, + model.a, + atol=ATOL, + rtol=RTOL, + msg=lambda msg: f"Did not obtain the same model on CPU or distributed training.\n{msg}", + ) + torch.testing.assert_close( + old_model.b, + model.b, + atol=ATOL, + rtol=RTOL, + msg=lambda msg: f"Did not obtain the same model on CPU or distributed training.\n{msg}", + ) + + accelerator.print("Training yielded the same results on one CPU or distributed setup with batch split.") + + # FP32 wrapper check + if torch.cuda.is_available(): + # Mostly a test that model.forward will have autocast when running unwrap_model(model, keep_fp32_wrapper=True) + print("Keep fp32 wrapper check.") + AcceleratorState._reset_state() + accelerator = Accelerator(mixed_precision="fp16") + + model = torch.nn.Linear(2, 4) + model = accelerator.prepare(model) + model_with_fp32_wrapper = accelerator.unwrap_model(model, keep_fp32_wrapper=True) + + # Run forward with fp16 as input. + # When the model is with mixed precision wrapper, no error will be raised. + input_tensor = torch.Tensor([1, 2]).to(dtype=torch.float16, device=accelerator.device) + output = model_with_fp32_wrapper(input_tensor) + + # BF16 support + if is_bf16_available(): + # Mostly a test that BF16 doesn't crash as the operation inside the model is not converted to BF16 + print("BF16 training check.") + AcceleratorState._reset_state() + dataloader_config = DataLoaderConfiguration(use_seedable_sampler=use_seedable_sampler) + accelerator = Accelerator(mixed_precision="bf16", dataloader_config=dataloader_config) + train_dl = generate_baseline_dataloader(train_set, generator, batch_size, use_seedable_sampler) + model = RegressionModel() + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + + train_dl, model, optimizer = accelerator.prepare(train_dl, model, optimizer) + set_seed(42) + generator.manual_seed(42) + for _ in range(3): + for batch in train_dl: + model.zero_grad() + output = model(batch["x"]) + loss = torch.nn.functional.mse_loss(output, batch["y"]) + accelerator.backward(loss) + optimizer.step() + + model = accelerator.unwrap_model(model).cpu() + torch.testing.assert_close( + old_model.a, + model.a, + atol=ATOL, + rtol=RTOL, + msg=lambda msg: f"Did not obtain the same model on CPU or distributed training.\n{msg}", + ) + torch.testing.assert_close( + old_model.b, + model.b, + atol=ATOL, + rtol=RTOL, + msg=lambda msg: f"Did not obtain the same model on CPU or distributed training.\n{msg}", + ) + + # FP16 support (HPU fp16 model seems to be off by 10% from the CPU, which is a lot of numerical error) + if is_fp16_available() and not is_hpu_available(): + # Mostly a test that FP16 doesn't crash as the operation inside the model is not converted to FP16 + print("FP16 training check.") + AcceleratorState._reset_state() + dataloader_config = DataLoaderConfiguration(use_seedable_sampler=use_seedable_sampler) + accelerator = Accelerator(mixed_precision="fp16", dataloader_config=dataloader_config) + train_dl = generate_baseline_dataloader(train_set, generator, batch_size, use_seedable_sampler) + model = RegressionModel() + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + + train_dl, model, optimizer = accelerator.prepare(train_dl, model, optimizer) + set_seed(42) + generator.manual_seed(42) + for _ in range(3): + for batch in train_dl: + model.zero_grad() + output = model(batch["x"]) + loss = torch.nn.functional.mse_loss(output, batch["y"]) + accelerator.backward(loss) + optimizer.step() + + model = accelerator.unwrap_model(model).cpu() + torch.testing.assert_close( + old_model.a, + model.a, + atol=ATOL, + rtol=RTOL, + msg=lambda msg: f"Did not obtain the same model on CPU or distributed training.\n{msg}", + ) + torch.testing.assert_close( + old_model.b, + model.b, + atol=ATOL, + rtol=RTOL, + msg=lambda msg: f"Did not obtain the same model on CPU or distributed training.\n{msg}", + ) + + # IPEX CPU tests + if is_ipex_available(): + print("ipex BF16 training check.") + AcceleratorState._reset_state() + dataloader_config = DataLoaderConfiguration(use_seedable_sampler=use_seedable_sampler) + accelerator = Accelerator(mixed_precision="bf16", cpu=True, dataloader_config=dataloader_config) + train_dl = generate_baseline_dataloader(train_set, generator, batch_size, use_seedable_sampler) + model = RegressionModel() + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + + train_dl, model, optimizer = accelerator.prepare(train_dl, model, optimizer) + set_seed(42) + generator.manual_seed(42) + for _ in range(3): + for batch in train_dl: + model.zero_grad() + output = model(batch["x"]) + loss = torch.nn.functional.mse_loss(output, batch["y"]) + accelerator.backward(loss) + optimizer.step() + + model = accelerator.unwrap_model(model).cpu() + torch.testing.assert_close( + old_model.a, + model.a, + atol=ATOL, + rtol=RTOL, + msg=lambda msg: f"Did not obtain the same model on CPU or distributed training.\n{msg}", + ) + torch.testing.assert_close( + old_model.b, + model.b, + atol=ATOL, + rtol=RTOL, + msg=lambda msg: f"Did not obtain the same model on CPU or distributed training.\n{msg}", + ) + + +def test_split_between_processes_dataset(datasets_Dataset): + state = AcceleratorState() + data = datasets_Dataset.from_list([dict(k=v) for v in range(2 * state.num_processes)]) + with state.split_between_processes(data, apply_padding=False) as results: + assert len(results) == 2, ( + f"Each process did not have two items. Process index: {state.process_index}; Length: {len(results)}" + ) + + data = datasets_Dataset.from_list([dict(k=v) for v in range(2 * state.num_processes - 1)]) + with state.split_between_processes(data, apply_padding=False) as results: + if state.is_last_process: + assert len(results) == 1, ( + f"Last process did not receive a single item. Process index: {state.process_index}; Length: {len(results)}" + ) + else: + assert len(results) == 2, ( + f"One of the intermediate processes did not receive two items. Process index: {state.process_index}; Length: {len(results)}" + ) + state.wait_for_everyone() + + odd_data = datasets_Dataset.from_list([dict(k=v) for v in range(2 * state.num_processes - 1)]) + even_data = datasets_Dataset.from_list([dict(k=v) for v in range(2 * state.num_processes)]) + + for data in [odd_data, even_data]: + expected_output = data["k"] + + with state.split_between_processes(data, apply_padding=True) as results: + if state.num_processes == 1: + assert len(results) == len(data), ( + f"Single process did not receive all items. Process index: {state.process_index}; Length: {len(results)}" + ) + else: + assert len(results) == 2, ( + f"Each process did not have two items. Process index: {state.process_index}; Length: {len(results)}" + ) + + results_per_process = [] + for result in results: + results_per_process.append(result) + + state.wait_for_everyone() + + gathered_results = gather_object(results_per_process) + output = [r["k"] for r in gathered_results[: len(data)]] + + assert expected_output == output, f"Gathered results is incorrect. Expected: {expected_output}; Got: {output}" + + +def test_split_between_processes_list(): + state = AcceleratorState() + data = list(range(0, 2 * state.num_processes)) + with state.split_between_processes(data) as results: + assert len(results) == 2, ( + f"Each process did not have two items. Process index: {state.process_index}; Length: {len(results)}" + ) + state.wait_for_everyone() + + even_data = list(range(0, (2 * state.num_processes))) + odd_data = list(range(0, (2 * state.num_processes) - 1)) + for data in [odd_data, even_data]: + expected_output = data + + with state.split_between_processes(data, apply_padding=True) as results: + num_samples_per_device = math.ceil(len(data) / state.num_processes) + # Test all processes gets the correct number of item(s) + assert len(results) == num_samples_per_device, ( + f"Process {state.device} did not get the correct number of item(s). Process index: {state.process_index}; Length: {len(results)}" + ) + + results_per_process = [] + for result in results: + results_per_process.append(result) + + state.wait_for_everyone() + + gathered_results = gather_object(results_per_process) + output = gathered_results[: len(data)] + + assert expected_output == output, f"Gathered results is incorrect. Expected: {expected_output}; Got: {output}" + + +def test_split_between_processes_nested_dict(): + state = AcceleratorState() + a = [1, 2, 3, 4, 5, 6, 7, 8] + b = ["a", "b", "c", "d", "e", "f", "g", "h"] + c = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]) + if state.num_processes in (1, 2, 4): + data = {"a": a, "b": b, "c": c} + data_copy = deepcopy(data) + with state.split_between_processes(data) as results: + if state.process_index == 0: + assert results["a"] == data_copy["a"][: 8 // state.num_processes] + elif state.num_processes == 2: + assert results["a"] == data_copy["a"][4:] + elif state.process_index == 3: + # We return a list each time + assert results["a"] == data_copy["a"][-2:], f"Expected: {data_copy['a'][-2]}, Actual: {results['a']}" + if state.process_index == 0: + assert results["b"] == data_copy["b"][: 8 // state.num_processes] + elif state.num_processes == 2: + assert results["b"] == data_copy["b"][4:] + elif state.process_index == 3: + assert results["b"] == data_copy["b"][-2:] + if state.process_index == 0: + assert torch.allclose(results["c"], data_copy["c"][: 8 // state.num_processes]), ( + f"Did not obtain expected values on process 0, expected `{data['c'][: 8 // state.num_processes]}`, received: {results['c']}" + ) + elif state.num_processes == 2: + assert torch.allclose(results["c"], data_copy["c"][4:]), ( + f"Did not obtain expected values on process 2, expected `{data['c'][4:]}`, received: {results['c']}" + ) + elif state.process_index == 3: + assert torch.allclose(results["c"], data_copy["c"][-2:]), ( + f"Did not obtain expected values on process 4, expected `{data['c'][-2:]}`, received: {results['c']}" + ) + + state.wait_for_everyone() + + +def test_split_between_processes_tensor(): + state = AcceleratorState() + if state.num_processes > 1: + data = torch.tensor([[0, 1, 2, 3], [4, 5, 6, 7]]).to(state.device) + with state.split_between_processes(data) as results: + if state.process_index == 0: + expected = torch.tensor([[0, 1, 2, 3]]).to(state.device) + else: + expected = torch.tensor([[4, 5, 6, 7]]).to(state.device) + torch.testing.assert_close(results, expected) + state.wait_for_everyone() + + even_data = torch.tensor([[i] for i in range(2 * state.num_processes)]).to(state.device) + odd_data = torch.tensor([[i] for i in range(2 * state.num_processes - 1)]).to(state.device) + for data in [even_data, odd_data]: + expected_output = [torch.tensor(i) for i in data.tolist()] + + with state.split_between_processes(data, apply_padding=True) as results: + num_samples_per_device = math.ceil(len(data) / state.num_processes) + assert len(results) == num_samples_per_device, ( + f"Process {state.device} did not get the correct number of item(s). Process index: {state.process_index}; Length: {len(results)}" + ) + results_per_process = [] + for result in results: + results_per_process.append(result.to("cpu")) + + state.wait_for_everyone() + + gathered_results = gather_object(results_per_process) + output = gathered_results[: len(data)] + + assert expected_output == output, f"Gathered results is incorrect. Expected: {expected_output}; Got: {output}" + + +def test_split_between_processes_evenly(): + state = AcceleratorState() + if state.num_processes in (1, 2, 4, 8): + data = list(range(17)) + num_samples_per_process = len(data) // state.num_processes + num_extras = len(data) % state.num_processes + with state.split_between_processes(data) as results: + if state.process_index < num_extras: + assert len(results) == num_samples_per_process + 1, ( + f"Each Process should have even elements. Expected: {num_samples_per_process + 1}, Actual: {len(results)}" + ) + else: + assert len(results) == num_samples_per_process, ( + f"Each Process should have even elements. Expected: {num_samples_per_process}, Actual: {len(results)}" + ) + state.wait_for_everyone() + + +def test_trigger(): + accelerator = Accelerator() + # should start with being false + assert accelerator.check_trigger() is False + + # set a breakpoint on the main process + if accelerator.is_main_process: + accelerator.set_trigger() + + # check it's been activated across all processes + # calls `all_reduce` and triggers a sync + assert accelerator.check_trigger() is True + + # check it's been reset after the sync + assert accelerator.check_trigger() is False + + +def test_reinstantiated_state(): + import pytest + + AcceleratorState._reset_state() + simple_model = torch.nn.Linear(1, 1) + # First define an accelerator + accelerator = Accelerator() + # Then call `reset_state`, breaking the state existing in the accelerator + AcceleratorState._reset_state() + # Now try and prepare a simple model, should raise the custom error early + with pytest.raises(AttributeError) as cm: + accelerator.prepare(simple_model) + assert "`AcceleratorState` object has no attribute" in str(cm.value.args[0]) + assert "This happens if `AcceleratorState._reset_state()`" in str(cm.value.args[0]) + + +def main(): + accelerator = Accelerator() + state = accelerator.state + if state.local_process_index == 0: + print("**Initialization**") + init_state_check() + state.wait_for_everyone() + + if state.distributed_type == DistributedType.MULTI_GPU: + num_processes_per_node = torch.cuda.device_count() + else: + num_processes_per_node = state.num_processes + + # We only run this test on non-multinode + if num_processes_per_node == state.num_processes: + if state.process_index == 0: + print("\n**Test process execution**") + process_execution_check() + + if state.process_index == 0: + print("\n**Test split between processes as a list**") + test_split_between_processes_list() + + if state.process_index == 0: + print("\n**Test split between processes as a dict**") + test_split_between_processes_nested_dict() + + if state.process_index == 0: + print("\n**Test split between processes as a tensor**") + test_split_between_processes_tensor() + + if state.process_index == 0: + print("\n**Test split between processes evenly**") + test_split_between_processes_evenly() + + if state.process_index == 0: + print("\n**Test split between processes as a datasets.Dataset**") + if is_datasets_available(): + from datasets import Dataset as datasets_Dataset + + test_split_between_processes_dataset(datasets_Dataset) + else: + print("Skipped because Hugging Face datasets is not available") + + if state.local_process_index == 0: + print("\n**Test random number generator synchronization**") + rng_sync_check() + + if state.local_process_index == 0: + print("\n**DataLoader integration test**") + dl_preparation_check() + if state.distributed_type != DistributedType.XLA: + central_dl_preparation_check() + custom_sampler_check() + check_seedable_sampler() + check_seedable_sampler_with_data_seed() + + if state.num_processes > 1: + check_seedable_sampler_in_batch_sampler_shard() + + # Trainings are not exactly the same in DeepSpeed and CPU mode + if state.distributed_type == DistributedType.DEEPSPEED: + return + + if state.local_process_index == 0: + print("\n**Training integration test**") + training_check(use_seedable_sampler=False) + training_check(use_seedable_sampler=True) + + if state.local_process_index == 0: + print("\n**Breakpoint trigger test**") + test_trigger() + + if is_pytest_available(): + if state.local_process_index == 0: + print("\n**Test reinstantiated state**") + test_reinstantiated_state() + + state.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_sync.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..44e1ecc1d59c5691f284282fb8cd2259c8a70658 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/test_sync.py @@ -0,0 +1,410 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from copy import deepcopy + +import torch +import torch.nn.functional as F +from torch.optim import AdamW +from torch.optim.lr_scheduler import LambdaLR +from torch.utils.data import DataLoader + +from accelerate.accelerator import Accelerator, DataLoaderConfiguration, GradientAccumulationPlugin +from accelerate.state import GradientState +from accelerate.test_utils import RegressionDataset, RegressionModel +from accelerate.utils import DistributedType, set_seed + + +def check_model_parameters(model_a, model_b, did_step, iteration, **kwargs): + for param, grad_param in zip(model_a.parameters(), model_b.parameters()): + if not param.requires_grad: + continue + if not did_step: + # Grads should not be in sync + assert torch.allclose(param.grad, grad_param.grad, **kwargs) is False, ( + f"Gradients in sync when they should not be at iteration {iteration}:\nmodel_a grad ({param.grad}) == model_b grad ({grad_param.grad})" + ) + else: + # Grads should be in sync + assert torch.allclose(param.grad, grad_param.grad, **kwargs) is True, ( + f"Gradients not in sync when they should be at iteration {iteration}:\nmodel_a grad ({param.grad}) != model_b grad ({grad_param.grad})" + ) + + +def step_model(model, input, target, accelerator, do_backward=True): + model.train() + output = model(input) + loss = F.mse_loss(output, target.to(output.device)) + if not do_backward: + loss /= accelerator.gradient_accumulation_steps + loss.backward() + else: + accelerator.backward(loss) + + +def get_training_setup(accelerator, sched=False): + "Returns everything needed to perform basic training" + set_seed(42) + model = RegressionModel() + ddp_model = deepcopy(model) + dset = RegressionDataset(length=80) + dataloader = DataLoader(dset, batch_size=16) + model.to(accelerator.device) + if sched: + opt = AdamW(params=model.parameters(), lr=1e-3) + ddp_opt = AdamW(params=ddp_model.parameters(), lr=1e-3) + sched = LambdaLR(opt, lr_lambda=lambda epoch: epoch**0.65) + ddp_sched = LambdaLR(ddp_opt, lr_lambda=lambda epoch: epoch**0.65) + # Make a copy of `model` + if sched: + ddp_model, ddp_opt, ddp_sched, dataloader = accelerator.prepare(ddp_model, ddp_opt, ddp_sched, dataloader) + else: + ddp_model, dataloader = accelerator.prepare(ddp_model, dataloader) + if sched: + return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched) + return model, ddp_model, dataloader + + +def test_noop_sync(accelerator): + # Test when on a single CPU or GPU that the context manager does nothing + model, ddp_model, dataloader = get_training_setup(accelerator) + # Use a single batch + ddp_input, ddp_target = next(iter(dataloader)).values() + for iteration in range(3): + # Gather the distributed inputs and targs for the base model + input, target = accelerator.gather((ddp_input, ddp_target)) + input, target = input.to(accelerator.device), target.to(accelerator.device) + # Perform our initial ground truth step in non "DDP" + step_model(model, input, target, accelerator) + # Do "gradient accumulation" (noop) + if iteration % 2 == 0: + # Accumulate grads locally + with accelerator.no_sync(ddp_model): + step_model(ddp_model, ddp_input, ddp_target, accelerator) + else: + # Sync grads + step_model(ddp_model, ddp_input, ddp_target, accelerator) + + # Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync + check_model_parameters(model, ddp_model, True, iteration) + for param, ddp_param in zip(model.parameters(), ddp_model.parameters()): + if not param.requires_grad: + continue + assert torch.allclose(param.grad, ddp_param.grad), ( + f"Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})" + ) + + # Shuffle ddp_input on each iteration + torch.manual_seed(1337 + iteration) + ddp_input = ddp_input[torch.randperm(len(ddp_input))] + + +def test_distributed_sync(accelerator): + # Test on distributed setup that context manager behaves properly + model, ddp_model, dataloader = get_training_setup(accelerator) + # Use a single batch + ddp_input, ddp_target = next(iter(dataloader)).values() + for iteration in range(3): + # Gather the distributed inputs and targs for the base model + input, target = accelerator.gather((ddp_input, ddp_target)) + input, target = input.to(accelerator.device), target.to(accelerator.device) + # Perform our initial ground truth step in non "DDP" + step_model(model, input, target, accelerator) + # Do "gradient accumulation" (noop) + if iteration % 2 == 0: + # Accumulate grads locally + with accelerator.no_sync(ddp_model): + step_model(ddp_model, ddp_input, ddp_target, accelerator) + else: + # Sync grads + step_model(ddp_model, ddp_input, ddp_target, accelerator) + + # DDP model and model should only be in sync when not (iteration % 2 == 0) + for param, ddp_param in zip(model.parameters(), ddp_model.parameters()): + if not param.requires_grad: + continue + if iteration % 2 == 0: + # Grads should not be in sync + assert torch.allclose(param.grad, ddp_param.grad) is False, ( + f"Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})" + ) + else: + # Grads should be in sync + assert torch.allclose(param.grad, ddp_param.grad) is True, ( + f"Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})" + ) + + # Shuffle ddp_input on each iteration + torch.manual_seed(1337 + iteration) + ddp_input = ddp_input[torch.randperm(len(ddp_input))] + + +def test_distributed_sync_multiple_fwd(accelerator): + # Test on distributed setup that context manager behaves properly when used with multiple forwards followed by multiple backwards + model, ddp_model, dataloader = get_training_setup(accelerator) + # Do multiple forwards + losses = [] + num_iterations = 3 + for iteration in range(num_iterations): + ddp_input, ddp_target = next(iter(dataloader)).values() + + # Gather the distributed inputs and targs for the base model + input, target = accelerator.gather((ddp_input, ddp_target)) + input, target = input.to(accelerator.device), target.to(accelerator.device) + + # Perform our initial ground truth step in non "DDP" + step_model(model, input, target, accelerator) + + # Accumulate grads locally + with accelerator.no_sync(ddp_model): + ddp_output = ddp_model(ddp_input) + loss = F.mse_loss(ddp_output, ddp_target.to(ddp_output.device)) + losses.append(loss) + + # Do multiple backwards and sync only at the last backward + for iteration in range(num_iterations): + loss = losses[iteration] + + if iteration < num_iterations - 1: + # Accumulate grads locally + accelerator.backward(loss) + + # DDP model and model should only be in sync after last backward + for param, ddp_param in zip(model.parameters(), ddp_model.parameters()): + if not param.requires_grad: + continue + # Grads should not be in sync + assert torch.allclose(param.grad, ddp_param.grad) is False, ( + f"Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})" + ) + + else: + # Sync grads if last backward + with accelerator.trigger_sync_in_backward(ddp_model): + accelerator.backward(loss) + + # DDP model and model should only be in sync after last backward + for param, ddp_param in zip(model.parameters(), ddp_model.parameters()): + if not param.requires_grad: + continue + # Grads should be in sync + assert torch.allclose(param.grad, ddp_param.grad) is True, ( + f"Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})" + ) + + +def test_gradient_accumulation(split_batches=False, dispatch_batches=False, sync_each_batch=False): + gradient_accumulation_plugin = GradientAccumulationPlugin(num_steps=2, sync_each_batch=sync_each_batch) + dataloader_config = DataLoaderConfiguration(split_batches=split_batches, dispatch_batches=dispatch_batches) + accelerator = Accelerator( + dataloader_config=dataloader_config, + gradient_accumulation_plugin=gradient_accumulation_plugin, + ) + # Test that context manager behaves properly + model, ddp_model, dataloader = get_training_setup(accelerator) + for iteration, batch in enumerate(dataloader): + ddp_input, ddp_target = batch.values() + # Gather the distributed inputs and targs for the base model + input, target = accelerator.gather((ddp_input, ddp_target)) + input, target = input.to(accelerator.device), target.to(accelerator.device) + # Perform our initial ground truth step in non "DDP" + step_model(model, input, target, accelerator, False) + # Do "gradient accumulation" (noop) + with accelerator.accumulate(ddp_model): + step_model(ddp_model, ddp_input, ddp_target, accelerator) + + # DDP model and model should only be in sync when not (iteration % 2 == 0) + for param, ddp_param in zip(model.parameters(), ddp_model.parameters()): + if not param.requires_grad: + continue + if ((iteration + 1) % 2 == 0) or (iteration == len(dataloader) - 1) or sync_each_batch: + # Grads should be in sync + assert torch.allclose(param.grad, ddp_param.grad) is True, ( + f"Gradients not in sync when they should be at iteration {iteration}:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})" + ) + else: + # Grads should not be in sync + assert torch.allclose(param.grad, ddp_param.grad) is False, ( + f"Gradients in sync when they should not be at iteration {iteration}:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})" + ) + + # Shuffle ddp_input on each iteration + torch.manual_seed(1337 + iteration) + ddp_input = ddp_input[torch.randperm(len(ddp_input))] + GradientState._reset_state() + + +def test_gradient_accumulation_with_opt_and_scheduler( + split_batches=False, dispatch_batches=False, sync_each_batch=False +): + gradient_accumulation_plugin = GradientAccumulationPlugin(num_steps=2, sync_each_batch=sync_each_batch) + dataloader_config = DataLoaderConfiguration(split_batches=split_batches, dispatch_batches=dispatch_batches) + accelerator = Accelerator( + dataloader_config=dataloader_config, + gradient_accumulation_plugin=gradient_accumulation_plugin, + ) + # Test that context manager behaves properly + model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched = get_training_setup(accelerator, True) + for iteration, batch in enumerate(dataloader): + ddp_input, ddp_target = batch.values() + # Gather the distributed inputs and targs for the base model + input, target = accelerator.gather((ddp_input, ddp_target)) + input, target = input.to(accelerator.device), target.to(accelerator.device) + # Perform our initial ground truth step in non "DDP" + model.train() + ddp_model.train() + step_model(model, input, target, accelerator, False) + opt.step() + + if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(dataloader)): + if split_batches: + sched.step() + else: + for _ in range(accelerator.num_processes): + sched.step() + + # Perform gradient accumulation under wrapper + with accelerator.accumulate(ddp_model): + step_model(ddp_model, ddp_input, ddp_target, accelerator) + ddp_opt.step() + ddp_sched.step() + + # Learning rates should be the same + assert opt.param_groups[0]["lr"] == ddp_opt.param_groups[0]["lr"], ( + f"Learning rates found in each optimizer did not align\nopt: {opt.param_groups[0]['lr']}\nDDP opt: {ddp_opt.param_groups[0]['lr']}\n" + ) + did_step = (((iteration + 1) % 2) == 0) or ((iteration + 1) == len(dataloader)) + if accelerator.num_processes > 1: + check_model_parameters( + model, + ddp_model, + did_step or sync_each_batch, # syncs at each grad_accum interval of if sync_each_batch==True + iteration, + rtol=1e-3, # needs a relative tolerance due to roundoff errors + ) + + if did_step: + opt.zero_grad() # flush gradients every accum step + ddp_opt.zero_grad() + + # Shuffle ddp_input on each iteration + torch.manual_seed(1337 + iteration) + GradientState._reset_state() + + +def test_dataloader_break(): + accelerator = Accelerator() + first_dset = RegressionDataset(length=80) + first_dataloader = DataLoader(first_dset, batch_size=16) + second_dset = RegressionDataset(length=96) + second_dataloader = DataLoader(second_dset, batch_size=16) + first_dataloader, second_dataloader = accelerator.prepare(first_dataloader, second_dataloader) + + assert accelerator.gradient_state.active_dataloader is None + for iteration, _ in enumerate(first_dataloader): + assert id(accelerator.gradient_state.active_dataloader) == id(first_dataloader) + if iteration < len(first_dataloader) - 1: + assert not accelerator.gradient_state.end_of_dataloader + if iteration == 1: + for batch_num, _ in enumerate(second_dataloader): + assert id(accelerator.gradient_state.active_dataloader) == id(second_dataloader) + if batch_num < len(second_dataloader) - 1: + assert not accelerator.gradient_state.end_of_dataloader + else: + assert accelerator.gradient_state.end_of_dataloader + else: + assert accelerator.gradient_state.end_of_dataloader + assert accelerator.gradient_state.active_dataloader is None + + +def main(): + accelerator = Accelerator() + state = accelerator.state + if state.local_process_index == 0: + print("**Test `accumulate` gradient accumulation with dataloader break**") + if state.distributed_type != DistributedType.XLA: + test_dataloader_break() + if state.distributed_type == DistributedType.NO: + if state.local_process_index == 0: + print("**Test NOOP `no_sync` context manager**") + test_noop_sync(accelerator) + if state.distributed_type in ( + DistributedType.MULTI_GPU, + DistributedType.MULTI_NPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_SDAA, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_CPU, + DistributedType.MULTI_HPU, + ): + if state.local_process_index == 0: + print("**Test Distributed `no_sync` context manager**") + test_distributed_sync(accelerator) + if state.local_process_index == 0: + print("**Test Distributed `no_sync` context manager with multiple forwards**") + test_distributed_sync_multiple_fwd(accelerator) + if state.distributed_type in ( + DistributedType.MULTI_GPU, + DistributedType.MULTI_NPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_SDAA, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_HPU, + ): + for split_batch in [True, False]: + for dispatch_batches in [True, False]: + for sync_each_batch in [True, False]: + if state.local_process_index == 0: + print( + "**Test `accumulate` gradient accumulation, ", + f"`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}` and `sync_each_batch={sync_each_batch}`**", + ) + test_gradient_accumulation(split_batch, dispatch_batches, sync_each_batch) + + # Currently will break on torch 2.0 +, need to investigate why + if state.local_process_index == 0: + print( + "**Test `accumulate` gradient accumulation with optimizer and scheduler, ", + "`split_batches=False`, `dispatch_batches=False`, `sync_each_batch=False`**", + ) + test_gradient_accumulation_with_opt_and_scheduler() + if state.distributed_type in ( + DistributedType.MULTI_GPU, + DistributedType.MULTI_NPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_SDAA, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_HPU, + ): + for split_batch in [True, False]: + for dispatch_batches in [True, False]: + for sync_each_batch in [True, False]: + if not split_batch and not dispatch_batches and not sync_each_batch: + continue + if state.local_process_index == 0: + print( + "**Test `accumulate` gradient accumulation with optimizer and scheduler, ", + f"`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}` and `sync_each_batch={sync_each_batch}`**", + ) + test_gradient_accumulation_with_opt_and_scheduler(split_batch, dispatch_batches, sync_each_batch) + state.destroy_process_group() + + +def _mp_fn(index): + # For xla_spawn (TPUs) + main() + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/testing.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..e964399784779fb9bf3d34269d08fd76d4e96319 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/testing.py @@ -0,0 +1,870 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import asyncio +import inspect +import io +import os +import re +import shutil +import subprocess +import sys +import tempfile +import unittest +from contextlib import contextmanager +from functools import partial +from pathlib import Path +from typing import Union +from unittest import mock + +import torch + +import accelerate + +from ..state import AcceleratorState +from ..utils import ( + check_cuda_fp8_capability, + compare_versions, + gather, + is_aim_available, + is_bnb_available, + is_clearml_available, + is_comet_ml_available, + is_cuda_available, + is_datasets_available, + is_deepspeed_available, + is_dvclive_available, + is_fp8_available, + is_fp16_available, + is_habana_gaudi1, + is_hpu_available, + is_import_timer_available, + is_matplotlib_available, + is_mlflow_available, + is_mlu_available, + is_mps_available, + is_musa_available, + is_npu_available, + is_pandas_available, + is_pippy_available, + is_pytest_available, + is_schedulefree_available, + is_sdaa_available, + is_swanlab_available, + is_tensorboard_available, + is_timm_available, + is_torch_version, + is_torch_xla_available, + is_torchao_available, + is_torchdata_stateful_dataloader_available, + is_torchvision_available, + is_trackio_available, + is_transformer_engine_available, + is_transformers_available, + is_triton_available, + is_wandb_available, + is_xpu_available, + str_to_bool, +) + + +def get_backend(): + if is_torch_xla_available(): + return "xla", torch.cuda.device_count(), torch.cuda.memory_allocated + elif is_cuda_available(): + return "cuda", torch.cuda.device_count(), torch.cuda.memory_allocated + elif is_mps_available(min_version="2.0"): + return "mps", 1, torch.mps.current_allocated_memory + elif is_mps_available(): + return "mps", 1, lambda: 0 + elif is_mlu_available(): + return "mlu", torch.mlu.device_count(), torch.mlu.memory_allocated + elif is_sdaa_available(): + return "sdaa", torch.sdaa.device_count(), torch.sdaa.memory_allocated + elif is_musa_available(): + return "musa", torch.musa.device_count(), torch.musa.memory_allocated + elif is_npu_available(): + return "npu", torch.npu.device_count(), torch.npu.memory_allocated + elif is_xpu_available(): + return "xpu", torch.xpu.device_count(), torch.xpu.memory_allocated + elif is_hpu_available(): + return "hpu", torch.hpu.device_count(), torch.hpu.memory_allocated + else: + return "cpu", 1, lambda: 0 + + +torch_device, device_count, memory_allocated_func = get_backend() + + +def get_launch_command(**kwargs) -> list: + """ + Wraps around `kwargs` to help simplify launching from `subprocess`. + + Example: + ```python + # returns ['accelerate', 'launch', '--num_processes=2', '--device_count=2'] + get_launch_command(num_processes=2, device_count=2) + ``` + """ + command = ["accelerate", "launch"] + for k, v in kwargs.items(): + if isinstance(v, bool) and v: + command.append(f"--{k}") + elif v is not None: + command.append(f"--{k}={v}") + return command + + +DEFAULT_LAUNCH_COMMAND = get_launch_command(num_processes=device_count, monitor_interval=0.1) + + +def parse_flag_from_env(key, default=False): + try: + value = os.environ[key] + except KeyError: + # KEY isn't set, default to `default`. + _value = default + else: + # KEY is set, convert it to True or False. + try: + _value = str_to_bool(value) + except ValueError: + # More values are supported, but let's keep the message simple. + raise ValueError(f"If set, {key} must be yes or no.") + return _value + + +_run_slow_tests = parse_flag_from_env("RUN_SLOW", default=False) + + +def skip(test_case): + "Decorator that skips a test unconditionally" + return unittest.skip("Test was skipped")(test_case) + + +def slow(test_case): + """ + Decorator marking a test as slow. Slow tests are skipped by default. Set the RUN_SLOW environment variable to a + truthy value to run them. + """ + return unittest.skipUnless(_run_slow_tests, "test is slow")(test_case) + + +def require_cpu(test_case): + """ + Decorator marking a test that must be only ran on the CPU. These tests are skipped when a GPU is available. + """ + return unittest.skipUnless(torch_device == "cpu", "test requires only a CPU")(test_case) + + +def require_non_cpu(test_case): + """ + Decorator marking a test that requires a hardware accelerator backend. These tests are skipped when there are no + hardware accelerator available. + """ + return unittest.skipUnless(torch_device != "cpu", "test requires a GPU")(test_case) + + +def require_cuda(test_case): + """ + Decorator marking a test that requires CUDA. These tests are skipped when there are no GPU available or when + TorchXLA is available. + """ + return unittest.skipUnless(is_cuda_available() and not is_torch_xla_available(), "test requires a GPU")(test_case) + + +def require_cuda_or_hpu(test_case): + """ + Decorator marking a test that requires CUDA or HPU. These tests are skipped when there are no GPU available or when + TorchXLA is available. + """ + return unittest.skipUnless( + (is_cuda_available() and not is_torch_xla_available()) or is_hpu_available(), "test requires a GPU or HPU" + )(test_case) + + +def require_xpu(test_case): + """ + Decorator marking a test that requires XPU. These tests are skipped when there are no XPU available. + """ + return unittest.skipUnless(is_xpu_available(), "test requires a XPU")(test_case) + + +def require_cuda_or_xpu(test_case): + """ + Decorator marking a test that requires CUDA or XPU. These tests are skipped when there are no GPU available or when + TorchXLA is available. + """ + cuda_condition = is_cuda_available() and not is_torch_xla_available() + xpu_condition = is_xpu_available() + return unittest.skipUnless(cuda_condition or xpu_condition, "test requires a CUDA GPU or XPU")(test_case) + + +def require_non_xpu(test_case): + """ + Decorator marking a test that should be skipped for XPU. + """ + return unittest.skipUnless(torch_device != "xpu", "test requires a non-XPU")(test_case) + + +def require_non_hpu(test_case): + """ + Decorator marking a test that should be skipped for HPU. + """ + return unittest.skipUnless(torch_device != "hpu", "test requires a non-HPU")(test_case) + + +def require_fp16(test_case): + """ + Decorator marking a test that requires FP16. These tests are skipped when FP16 is not supported. + """ + + return unittest.skipUnless(is_fp16_available(), "test requires FP16 support")(test_case) + + +def require_fp8(test_case): + """ + Decorator marking a test that requires FP8. These tests are skipped when FP8 is not supported. + """ + + # is_fp8_available only checks for libraries + # ideally it should check for device capability as well + fp8_is_available = is_fp8_available() + + if torch.cuda.is_available() and not check_cuda_fp8_capability(): + fp8_is_available = False + + if is_hpu_available() and is_habana_gaudi1(): + fp8_is_available = False + + return unittest.skipUnless(fp8_is_available, "test requires FP8 support")(test_case) + + +def require_fsdp2(test_case): + return unittest.skipUnless(is_torch_version(">=", "2.5.0"), "test requires FSDP2 (torch >= 2.5.0)")(test_case) + + +def require_mlu(test_case): + """ + Decorator marking a test that requires MLU. These tests are skipped when there are no MLU available. + """ + return unittest.skipUnless(is_mlu_available(), "test require a MLU")(test_case) + + +def require_sdaa(test_case): + """ + Decorator marking a test that requires SDAA. These tests are skipped when there are no SDAA available. + """ + return unittest.skipUnless(is_sdaa_available(), "test require a SDAA")(test_case) + + +def require_musa(test_case): + """ + Decorator marking a test that requires MUSA. These tests are skipped when there are no MUSA available. + """ + return unittest.skipUnless(is_musa_available(), "test require a MUSA")(test_case) + + +def require_npu(test_case): + """ + Decorator marking a test that requires NPU. These tests are skipped when there are no NPU available. + """ + return unittest.skipUnless(is_npu_available(), "test require a NPU")(test_case) + + +def require_mps(test_case): + """ + Decorator marking a test that requires MPS backend. These tests are skipped when torch doesn't support `mps` + backend. + """ + return unittest.skipUnless(is_mps_available(), "test requires a `mps` backend support in `torch`")(test_case) + + +def require_huggingface_suite(test_case): + """ + Decorator marking a test that requires transformers and datasets. These tests are skipped when they are not. + """ + return unittest.skipUnless( + is_transformers_available() and is_datasets_available(), + "test requires the Hugging Face suite", + )(test_case) + + +def require_transformers(test_case): + """ + Decorator marking a test that requires transformers. These tests are skipped when they are not. + """ + return unittest.skipUnless(is_transformers_available(), "test requires the transformers library")(test_case) + + +def require_timm(test_case): + """ + Decorator marking a test that requires timm. These tests are skipped when they are not. + """ + return unittest.skipUnless(is_timm_available(), "test requires the timm library")(test_case) + + +def require_torchvision(test_case): + """ + Decorator marking a test that requires torchvision. These tests are skipped when they are not. + """ + return unittest.skipUnless(is_torchvision_available(), "test requires the torchvision library")(test_case) + + +def require_triton(test_case): + """ + Decorator marking a test that requires triton. These tests are skipped when they are not. + """ + return unittest.skipUnless(is_triton_available(), "test requires the triton library")(test_case) + + +def require_schedulefree(test_case): + """ + Decorator marking a test that requires schedulefree. These tests are skipped when they are not. + """ + return unittest.skipUnless(is_schedulefree_available(), "test requires the schedulefree library")(test_case) + + +def require_bnb(test_case): + """ + Decorator marking a test that requires bitsandbytes. These tests are skipped when they are not. + """ + return unittest.skipUnless(is_bnb_available(), "test requires the bitsandbytes library")(test_case) + + +def require_tpu(test_case): + """ + Decorator marking a test that requires TPUs. These tests are skipped when there are no TPUs available. + """ + return unittest.skipUnless(is_torch_xla_available(check_is_tpu=True), "test requires TPU")(test_case) + + +def require_non_torch_xla(test_case): + """ + Decorator marking a test as requiring an environment without TorchXLA. These tests are skipped when TorchXLA is + available. + """ + return unittest.skipUnless(not is_torch_xla_available(), "test requires an env without TorchXLA")(test_case) + + +def require_single_device(test_case): + """ + Decorator marking a test that requires a single device. These tests are skipped when there is no hardware + accelerator available or number of devices is more than one. + """ + return unittest.skipUnless( + torch_device != "cpu" and device_count == 1, "test requires a single device accelerator" + )(test_case) + + +def require_single_gpu(test_case): + """ + Decorator marking a test that requires CUDA on a single GPU. These tests are skipped when there are no GPU + available or number of GPUs is more than one. + """ + return unittest.skipUnless(torch.cuda.device_count() == 1, "test requires a GPU")(test_case) + + +def require_single_xpu(test_case): + """ + Decorator marking a test that requires CUDA on a single XPU. These tests are skipped when there are no XPU + available or number of xPUs is more than one. + """ + return unittest.skipUnless(torch.xpu.device_count() == 1, "test requires a XPU")(test_case) + + +def require_multi_device(test_case): + """ + Decorator marking a test that requires a multi-device setup. These tests are skipped on a machine without multiple + devices. + """ + return unittest.skipUnless(device_count > 1, "test requires multiple hardware accelerators")(test_case) + + +def require_multi_gpu(test_case): + """ + Decorator marking a test that requires a multi-GPU setup. These tests are skipped on a machine without multiple + GPUs. + """ + return unittest.skipUnless(torch.cuda.device_count() > 1, "test requires multiple GPUs")(test_case) + + +def require_multi_xpu(test_case): + """ + Decorator marking a test that requires a multi-XPU setup. These tests are skipped on a machine without multiple + XPUs. + """ + return unittest.skipUnless(torch.xpu.device_count() > 1, "test requires multiple XPUs")(test_case) + + +def require_multi_gpu_or_xpu(test_case): + """ + Decorator marking a test that requires a multi-GPU setup. These tests are skipped on a machine without multiple + GPUs or XPUs. + """ + return unittest.skipUnless( + (is_cuda_available() or is_xpu_available()) and device_count > 1, "test requires multiple GPUs or XPUs" + )(test_case) + + +def require_deepspeed(test_case): + """ + Decorator marking a test that requires DeepSpeed installed. These tests are skipped when DeepSpeed isn't installed + """ + return unittest.skipUnless(is_deepspeed_available(), "test requires DeepSpeed")(test_case) + + +def require_tp(test_case): + """ + Decorator marking a test that requires TP installed. These tests are skipped when TP isn't installed + """ + return unittest.skipUnless( + is_torch_version(">=", "2.3.0") and compare_versions("transformers", ">=", "4.52.0"), + "test requires torch version >= 2.3.0 and transformers version >= 4.52.0", + )(test_case) + + +def require_torch_min_version(test_case=None, version=None): + """ + Decorator marking that a test requires a particular torch version to be tested. These tests are skipped when an + installed torch version is less than the required one. + """ + if test_case is None: + return partial(require_torch_min_version, version=version) + return unittest.skipUnless(is_torch_version(">=", version), f"test requires torch version >= {version}")(test_case) + + +def require_tensorboard(test_case): + """ + Decorator marking a test that requires tensorboard installed. These tests are skipped when tensorboard isn't + installed + """ + return unittest.skipUnless(is_tensorboard_available(), "test requires Tensorboard")(test_case) + + +def require_wandb(test_case): + """ + Decorator marking a test that requires wandb installed. These tests are skipped when wandb isn't installed + """ + return unittest.skipUnless(is_wandb_available(), "test requires wandb")(test_case) + + +def require_trackio(test_case): + """ + Decorator marking a test that requires trackio installed. These tests are skipped when trackio isn't installed + """ + return unittest.skipUnless(is_trackio_available(), "test requires trackio")(test_case) + + +def require_comet_ml(test_case): + """ + Decorator marking a test that requires comet_ml installed. These tests are skipped when comet_ml isn't installed + """ + return unittest.skipUnless(is_comet_ml_available(), "test requires comet_ml")(test_case) + + +def require_aim(test_case): + """ + Decorator marking a test that requires aim installed. These tests are skipped when aim isn't installed + """ + return unittest.skipUnless(is_aim_available(), "test requires aim")(test_case) + + +def require_clearml(test_case): + """ + Decorator marking a test that requires clearml installed. These tests are skipped when clearml isn't installed + """ + return unittest.skipUnless(is_clearml_available(), "test requires clearml")(test_case) + + +def require_dvclive(test_case): + """ + Decorator marking a test that requires dvclive installed. These tests are skipped when dvclive isn't installed + """ + return unittest.skipUnless(is_dvclive_available(), "test requires dvclive")(test_case) + + +def require_swanlab(test_case): + """ + Decorator marking a test that requires swanlab installed. These tests are skipped when swanlab isn't installed + """ + return unittest.skipUnless(is_swanlab_available(), "test requires swanlab")(test_case) + + +def require_pandas(test_case): + """ + Decorator marking a test that requires pandas installed. These tests are skipped when pandas isn't installed + """ + return unittest.skipUnless(is_pandas_available(), "test requires pandas")(test_case) + + +def require_mlflow(test_case): + """ + Decorator marking a test that requires mlflow installed. These tests are skipped when mlflow isn't installed + """ + return unittest.skipUnless(is_mlflow_available(), "test requires mlflow")(test_case) + + +def require_pippy(test_case): + """ + Decorator marking a test that requires pippy installed. These tests are skipped when pippy isn't installed It is + also checked if the test is running on a Gaudi1 device which doesn't support pippy. + """ + return unittest.skipUnless(is_pippy_available() and not is_habana_gaudi1(), "test requires pippy")(test_case) + + +def require_import_timer(test_case): + """ + Decorator marking a test that requires tuna interpreter installed. These tests are skipped when tuna isn't + installed + """ + return unittest.skipUnless(is_import_timer_available(), "test requires tuna interpreter")(test_case) + + +def require_transformer_engine(test_case): + """ + Decorator marking a test that requires transformers engine installed. These tests are skipped when transformers + engine isn't installed + """ + return unittest.skipUnless(is_transformer_engine_available(), "test requires transformers engine")(test_case) + + +def require_torchao(test_case): + """ + Decorator marking a test that requires torchao installed. These tests are skipped when torchao isn't installed + """ + return unittest.skipUnless(is_torchao_available(), "test requires torchao")(test_case) + + +def require_matplotlib(test_case): + """ + Decorator marking a test that requires matplotlib installed. These tests are skipped when matplotlib isn't + installed + """ + return unittest.skipUnless(is_matplotlib_available(), "test requires matplotlib")(test_case) + + +_atleast_one_tracker_available = ( + any([is_wandb_available(), is_tensorboard_available(), is_trackio_available(), is_swanlab_available()]) + and not is_comet_ml_available() +) + + +def require_trackers(test_case): + """ + Decorator marking that a test requires at least one tracking library installed. These tests are skipped when none + are installed + """ + return unittest.skipUnless( + _atleast_one_tracker_available, + "test requires at least one tracker to be available and for `comet_ml` to not be installed", + )(test_case) + + +def require_torchdata_stateful_dataloader(test_case): + """ + Decorator marking a test that requires torchdata.stateful_dataloader. + + These tests are skipped when torchdata with stateful_dataloader module isn't installed. + + """ + return unittest.skipUnless( + is_torchdata_stateful_dataloader_available(), "test requires torchdata.stateful_dataloader" + )(test_case) + + +def run_first(test_case): + """ + Decorator marking a test with order(1). When pytest-order plugin is installed, tests marked with this decorator are + garanteed to run first. + + This is especially useful in some test settings like on a Gaudi instance where a Gaudi device can only be used by a + single process at a time. So we make sure all tests that run in a subprocess are launched first, to avoid device + allocation conflicts. + + If pytest is not installed, test will be returned as is. + """ + + if is_pytest_available(): + import pytest + + return pytest.mark.order(1)(test_case) + return test_case + + +class TempDirTestCase(unittest.TestCase): + """ + A TestCase class that keeps a single `tempfile.TemporaryDirectory` open for the duration of the class, wipes its + data at the start of a test, and then destroyes it at the end of the TestCase. + + Useful for when a class or API requires a single constant folder throughout it's use, such as Weights and Biases + + The temporary directory location will be stored in `self.tmpdir` + """ + + clear_on_setup = True + + @classmethod + def setUpClass(cls): + "Creates a `tempfile.TemporaryDirectory` and stores it in `cls.tmpdir`" + cls.tmpdir = Path(tempfile.mkdtemp()) + + @classmethod + def tearDownClass(cls): + "Remove `cls.tmpdir` after test suite has finished" + if os.path.exists(cls.tmpdir): + shutil.rmtree(cls.tmpdir) + + def setUp(self): + "Destroy all contents in `self.tmpdir`, but not `self.tmpdir`" + if self.clear_on_setup: + for path in self.tmpdir.glob("**/*"): + if path.is_file(): + path.unlink() + elif path.is_dir(): + shutil.rmtree(path) + + +class AccelerateTestCase(unittest.TestCase): + """ + A TestCase class that will reset the accelerator state at the end of every test. Every test that checks or utilizes + the `AcceleratorState` class should inherit from this to avoid silent failures due to state being shared between + tests. + """ + + def tearDown(self): + super().tearDown() + # Reset the state of the AcceleratorState singleton. + AcceleratorState._reset_state(True) + + +class MockingTestCase(unittest.TestCase): + """ + A TestCase class designed to dynamically add various mockers that should be used in every test, mimicking the + behavior of a class-wide mock when defining one normally will not do. + + Useful when a mock requires specific information available only initialized after `TestCase.setUpClass`, such as + setting an environment variable with that information. + + The `add_mocks` function should be ran at the end of a `TestCase`'s `setUp` function, after a call to + `super().setUp()` such as: + ```python + def setUp(self): + super().setUp() + mocks = mock.patch.dict(os.environ, {"SOME_ENV_VAR", "SOME_VALUE"}) + self.add_mocks(mocks) + ``` + """ + + def add_mocks(self, mocks: Union[mock.Mock, list[mock.Mock]]): + """ + Add custom mocks for tests that should be repeated on each test. Should be called during + `MockingTestCase.setUp`, after `super().setUp()`. + + Args: + mocks (`mock.Mock` or list of `mock.Mock`): + Mocks that should be added to the `TestCase` after `TestCase.setUpClass` has been run + """ + self.mocks = mocks if isinstance(mocks, (tuple, list)) else [mocks] + for m in self.mocks: + m.start() + self.addCleanup(m.stop) + + +def are_the_same_tensors(tensor): + state = AcceleratorState() + tensor = tensor[None].clone().to(state.device) + tensors = gather(tensor).cpu() + tensor = tensor[0].cpu() + for i in range(tensors.shape[0]): + if not torch.equal(tensors[i], tensor): + return False + return True + + +class _RunOutput: + def __init__(self, returncode, stdout, stderr): + self.returncode = returncode + self.stdout = stdout + self.stderr = stderr + + +async def _read_stream(stream, callback): + while True: + line = await stream.readline() + if line: + callback(line) + else: + break + + +async def _stream_subprocess(cmd, env=None, stdin=None, timeout=None, quiet=False, echo=False) -> _RunOutput: + if echo: + print("\nRunning: ", " ".join(cmd)) + + p = await asyncio.create_subprocess_exec( + cmd[0], + *cmd[1:], + stdin=stdin, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + env=env, + ) + + # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe + # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait + # + # If it starts hanging, will need to switch to the following code. The problem is that no data + # will be seen until it's done and if it hangs for example there will be no debug info. + # out, err = await p.communicate() + # return _RunOutput(p.returncode, out, err) + + out = [] + err = [] + + def tee(line, sink, pipe, label=""): + line = line.decode("utf-8").rstrip() + sink.append(line) + if not quiet: + print(label, line, file=pipe) + + # XXX: the timeout doesn't seem to make any difference here + await asyncio.wait( + [ + asyncio.create_task(_read_stream(p.stdout, lambda l: tee(l, out, sys.stdout, label="stdout:"))), + asyncio.create_task(_read_stream(p.stderr, lambda l: tee(l, err, sys.stderr, label="stderr:"))), + ], + timeout=timeout, + ) + return _RunOutput(await p.wait(), out, err) + + +def execute_subprocess_async(cmd: list, env=None, stdin=None, timeout=180, quiet=False, echo=True) -> _RunOutput: + # Cast every path in `cmd` to a string + for i, c in enumerate(cmd): + if isinstance(c, Path): + cmd[i] = str(c) + loop = asyncio.get_event_loop() + result = loop.run_until_complete( + _stream_subprocess(cmd, env=env, stdin=stdin, timeout=timeout, quiet=quiet, echo=echo) + ) + + cmd_str = " ".join(cmd) + if result.returncode > 0: + stderr = "\n".join(result.stderr) + raise RuntimeError( + f"'{cmd_str}' failed with returncode {result.returncode}\n\n" + f"The combined stderr from workers follows:\n{stderr}" + ) + + return result + + +def pytest_xdist_worker_id(): + """ + Returns an int value of worker's numerical id under `pytest-xdist`'s concurrent workers `pytest -n N` regime, or 0 + if `-n 1` or `pytest-xdist` isn't being used. + """ + worker = os.environ.get("PYTEST_XDIST_WORKER", "gw0") + worker = re.sub(r"^gw", "", worker, 0, re.M) + return int(worker) + + +def get_torch_dist_unique_port(): + """ + Returns a port number that can be fed to `torch.distributed.launch`'s `--master_port` argument. + + Under `pytest-xdist` it adds a delta number based on a worker id so that concurrent tests don't try to use the same + port at once. + """ + port = 29500 + uniq_delta = pytest_xdist_worker_id() + return port + uniq_delta + + +class SubprocessCallException(Exception): + pass + + +def run_command(command: list[str], return_stdout=False, env=None): + """ + Runs `command` with `subprocess.check_output` and will potentially return the `stdout`. Will also properly capture + if an error occurred while running `command` + """ + # Cast every path in `command` to a string + for i, c in enumerate(command): + if isinstance(c, Path): + command[i] = str(c) + if env is None: + env = os.environ.copy() + try: + output = subprocess.check_output(command, stderr=subprocess.STDOUT, env=env) + if return_stdout: + if hasattr(output, "decode"): + output = output.decode("utf-8") + return output + except subprocess.CalledProcessError as e: + raise SubprocessCallException( + f"Command `{' '.join(command)}` failed with the following error:\n\n{e.output.decode()}" + ) from e + + +def path_in_accelerate_package(*components: str) -> Path: + """ + Get a path within the `accelerate` package's directory. + + Args: + *components: Components of the path to join after the package directory. + + Returns: + `Path`: The path to the requested file or directory. + """ + + accelerate_package_dir = Path(inspect.getfile(accelerate)).parent + return accelerate_package_dir.joinpath(*components) + + +@contextmanager +def assert_exception(exception_class: Exception, msg: str = None) -> bool: + """ + Context manager to assert that the right `Exception` class was raised. + + If `msg` is provided, will check that the message is contained in the raised exception. + """ + was_ran = False + try: + yield + was_ran = True + except Exception as e: + assert isinstance(e, exception_class), f"Expected exception of type {exception_class} but got {type(e)}" + if msg is not None: + assert msg in str(e), f"Expected message '{msg}' to be in exception but got '{str(e)}'" + if was_ran: + raise AssertionError(f"Expected exception of type {exception_class} but ran without issue.") + + +def capture_call_output(func, *args, **kwargs): + """ + Takes in a `func` with `args` and `kwargs` and returns the captured stdout as a string + """ + captured_output = io.StringIO() + original_stdout = sys.stdout + try: + sys.stdout = captured_output + func(*args, **kwargs) + except Exception as e: + raise e + finally: + sys.stdout = original_stdout + return captured_output.getvalue() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/training.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/training.py new file mode 100644 index 0000000000000000000000000000000000000000..e71896c1f98bf47093d772cc77d7f27ba30c7ee8 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/training.py @@ -0,0 +1,162 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import numpy as np +import torch +from torch.utils.data import DataLoader + +from accelerate.utils.dataclasses import DistributedType + + +class RegressionDataset: + def __init__(self, a=2, b=3, length=64, seed=None): + rng = np.random.default_rng(seed) + self.length = length + self.x = rng.normal(size=(length,)).astype(np.float32) + self.y = a * self.x + b + rng.normal(scale=0.1, size=(length,)).astype(np.float32) + + def __len__(self): + return self.length + + def __getitem__(self, i): + return {"x": self.x[i], "y": self.y[i]} + + +class RegressionModel4XPU(torch.nn.Module): + def __init__(self, a=0, b=0, double_output=False): + super().__init__() + self.a = torch.nn.Parameter(torch.tensor([2, 3]).float()) + self.b = torch.nn.Parameter(torch.tensor([2, 3]).float()) + self.first_batch = True + + def forward(self, x=None): + if self.first_batch: + print(f"Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}") + self.first_batch = False + return x * self.a[0] + self.b[0] + + +class RegressionModel(torch.nn.Module): + def __init__(self, a=0, b=0, double_output=False): + super().__init__() + self.a = torch.nn.Parameter(torch.tensor(a).float()) + self.b = torch.nn.Parameter(torch.tensor(b).float()) + self.first_batch = True + + def forward(self, x=None): + if self.first_batch: + print(f"Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}") + self.first_batch = False + return x * self.a + self.b + + +def mocked_dataloaders(accelerator, batch_size: int = 16): + from datasets import load_dataset + from transformers import AutoTokenizer + + tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") + data_files = {"train": "tests/test_samples/MRPC/train.csv", "validation": "tests/test_samples/MRPC/dev.csv"} + datasets = load_dataset("csv", data_files=data_files) + label_list = datasets["train"].unique("label") + + label_to_id = {v: i for i, v in enumerate(label_list)} + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer( + examples["sentence1"], examples["sentence2"], truncation=True, max_length=None, padding="max_length" + ) + if "label" in examples: + outputs["labels"] = [label_to_id[l] for l in examples["label"]] + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["sentence1", "sentence2", "label"], + ) + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + if accelerator.distributed_type == DistributedType.XLA: + return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt") + return tokenizer.pad(examples, padding="longest", return_tensors="pt") + + # Instantiate dataloaders. + train_dataloader = DataLoader(tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=2) + eval_dataloader = DataLoader(tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=1) + + return train_dataloader, eval_dataloader + + +def mocked_dataloaders_for_autoregressive_models(accelerator, batch_size: int = 16): + from datasets import load_dataset + from transformers import AutoTokenizer + + tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM-360M") + tokenizer.pad_token = tokenizer.eos_token + + data_files = {"train": "tests/test_samples/MRPC/train.csv", "validation": "tests/test_samples/MRPC/dev.csv"} + datasets = load_dataset("csv", data_files=data_files) + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], truncation=True, max_length=None, return_attention_mask=False) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + # starting with the main process first: + with accelerator.main_process_first(): + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["sentence1", "sentence2", "label"], + ) + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + max_length = ( + 128 + if accelerator.distributed_type == DistributedType.XLA + else max([len(e["input_ids"]) for e in examples]) + ) + # When using mixed precision we want round multiples of 8/16 + if accelerator.mixed_precision == "fp8": + pad_to_multiple_of = 16 + elif accelerator.mixed_precision != "no": + pad_to_multiple_of = 8 + else: + pad_to_multiple_of = None + + batch = tokenizer.pad( + examples, + padding="max_length", + max_length=max_length + 1, + pad_to_multiple_of=pad_to_multiple_of, + return_tensors="pt", + ) + + batch["labels"] = batch["input_ids"][:, 1:] + batch["input_ids"] = batch["input_ids"][:, :-1] + + batch["labels"] = torch.where(batch["labels"] == tokenizer.pad_token_id, -100, batch["labels"]) + + return batch + + # Instantiate dataloaders. + train_dataloader = DataLoader(tokenized_datasets["train"], shuffle=False, collate_fn=collate_fn, batch_size=2) + eval_dataloader = DataLoader(tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=1) + + return train_dataloader, eval_dataloader diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/tracking.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..29e0aece74eedabd6c7417c11609eb24aad8df50 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/tracking.py @@ -0,0 +1,1326 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Expectation: +# Provide a project dir name, then each type of logger gets stored in project/{`logging_dir`} + +import json +import os +import time +from functools import wraps +from typing import Any, Optional, Union + +import yaml +from packaging import version + +from .logging import get_logger +from .state import PartialState +from .utils import ( + LoggerType, + compare_versions, + is_aim_available, + is_clearml_available, + is_comet_ml_available, + is_dvclive_available, + is_mlflow_available, + is_swanlab_available, + is_tensorboard_available, + is_trackio_available, + is_wandb_available, + listify, +) + + +_available_trackers = [] + +if is_tensorboard_available(): + _available_trackers.append(LoggerType.TENSORBOARD) + +if is_wandb_available(): + _available_trackers.append(LoggerType.WANDB) + +if is_comet_ml_available(): + _available_trackers.append(LoggerType.COMETML) + +if is_aim_available(): + _available_trackers.append(LoggerType.AIM) + +if is_mlflow_available(): + _available_trackers.append(LoggerType.MLFLOW) + +if is_clearml_available(): + _available_trackers.append(LoggerType.CLEARML) + +if is_dvclive_available(): + _available_trackers.append(LoggerType.DVCLIVE) + +if is_swanlab_available(): + _available_trackers.append(LoggerType.SWANLAB) + +if is_trackio_available(): + _available_trackers.append(LoggerType.TRACKIO) + +logger = get_logger(__name__) + + +def on_main_process(function): + """ + Decorator to selectively run the decorated function on the main process only based on the `main_process_only` + attribute in a class. + + Checks at function execution rather than initialization time, not triggering the initialization of the + `PartialState`. + """ + + @wraps(function) + def execute_on_main_process(self, *args, **kwargs): + if getattr(self, "main_process_only", False): + return PartialState().on_main_process(function)(self, *args, **kwargs) + else: + return function(self, *args, **kwargs) + + return execute_on_main_process + + +def get_available_trackers(): + "Returns a list of all supported available trackers in the system" + return _available_trackers + + +class GeneralTracker: + """ + A base Tracker class to be used for all logging integration implementations. + + Each function should take in `**kwargs` that will automatically be passed in from a base dictionary provided to + [`Accelerator`]. + + Should implement `name`, `requires_logging_directory`, and `tracker` properties such that: + + `name` (`str`): String representation of the tracker class name, such as "TensorBoard" `requires_logging_directory` + (`bool`): Whether the logger requires a directory to store their logs. `tracker` (`object`): Should return internal + tracking mechanism used by a tracker class (such as the `run` for wandb) + + Implementations can also include a `main_process_only` (`bool`) attribute to toggle if relevent logging, init, and + other functions should occur on the main process or across all processes (by default will use `True`) + """ + + main_process_only = True + + def __init__(self, _blank=False): + if not _blank: + err = "" + if not hasattr(self, "name"): + err += "`name`" + if not hasattr(self, "requires_logging_directory"): + if len(err) > 0: + err += ", " + err += "`requires_logging_directory`" + + # as tracker is a @property that relies on post-init + if "tracker" not in dir(self): + if len(err) > 0: + err += ", " + err += "`tracker`" + if len(err) > 0: + raise NotImplementedError( + f"The implementation for this tracker class is missing the following " + f"required attributes. Please define them in the class definition: " + f"{err}" + ) + + def start(self): + """ + Lazy initialization of the tracker inside Accelerator to avoid initializing PartialState before + InitProcessGroupKwargs. + """ + pass + + def store_init_configuration(self, values: dict): + """ + Logs `values` as hyperparameters for the run. Implementations should use the experiment configuration + functionality of a tracking API. + + Args: + values (Dictionary `str` to `bool`, `str`, `float` or `int`): + Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`, + `str`, `float`, `int`, or `None`. + """ + pass + + def log(self, values: dict, step: Optional[int], **kwargs): + """ + Logs `values` to the current run. Base `log` implementations of a tracking API should go in here, along with + special behavior for the `step parameter. + + Args: + values (Dictionary `str` to `str`, `float`, or `int`): + Values to be logged as key-value pairs. The values need to have type `str`, `float`, or `int`. + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + """ + pass + + def finish(self): + """ + Should run any finalizing functions within the tracking API. If the API should not have one, just don't + overwrite that method. + """ + pass + + +class TensorBoardTracker(GeneralTracker): + """ + A `Tracker` class that supports `tensorboard`. Should be initialized at the start of your script. + + Args: + run_name (`str`): + The name of the experiment run + logging_dir (`str`, `os.PathLike`): + Location for TensorBoard logs to be stored. + **kwargs (additional keyword arguments, *optional*): + Additional key word arguments passed along to the `tensorboard.SummaryWriter.__init__` method. + """ + + name = "tensorboard" + requires_logging_directory = True + + def __init__(self, run_name: str, logging_dir: Union[str, os.PathLike], **kwargs): + super().__init__() + self.run_name = run_name + self.logging_dir_param = logging_dir + self.init_kwargs = kwargs + + @on_main_process + def start(self): + try: + from torch.utils import tensorboard + except ModuleNotFoundError: + import tensorboardX as tensorboard + self.logging_dir = os.path.join(self.logging_dir_param, self.run_name) + self.writer = tensorboard.SummaryWriter(self.logging_dir, **self.init_kwargs) + logger.debug(f"Initialized TensorBoard project {self.run_name} logging to {self.logging_dir}") + logger.debug( + "Make sure to log any initial configurations with `self.store_init_configuration` before training!" + ) + + @property + def tracker(self): + return self.writer + + @on_main_process + def store_init_configuration(self, values: dict): + """ + Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. Stores the + hyperparameters in a yaml file for future use. + + Args: + values (Dictionary `str` to `bool`, `str`, `float` or `int`): + Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`, + `str`, `float`, `int`, or `None`. + """ + self.writer.add_hparams(values, metric_dict={}) + self.writer.flush() + project_run_name = time.time() + dir_name = os.path.join(self.logging_dir, str(project_run_name)) + os.makedirs(dir_name, exist_ok=True) + with open(os.path.join(dir_name, "hparams.yml"), "w") as outfile: + try: + yaml.dump(values, outfile) + except yaml.representer.RepresenterError: + logger.error("Serialization to store hyperparameters failed") + raise + logger.debug("Stored initial configuration hyperparameters to TensorBoard and hparams yaml file") + + @on_main_process + def log(self, values: dict, step: Optional[int] = None, **kwargs): + """ + Logs `values` to the current run. + + Args: + values (Dictionary `str` to `str`, `float`, `int` or `dict` of `str` to `float`/`int`): + Values to be logged as key-value pairs. The values need to have type `str`, `float`, `int` or `dict` of + `str` to `float`/`int`. + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs: + Additional key word arguments passed along to either `SummaryWriter.add_scaler`, + `SummaryWriter.add_text`, or `SummaryWriter.add_scalers` method based on the contents of `values`. + """ + values = listify(values) + for k, v in values.items(): + if isinstance(v, (int, float)): + self.writer.add_scalar(k, v, global_step=step, **kwargs) + elif isinstance(v, str): + self.writer.add_text(k, v, global_step=step, **kwargs) + elif isinstance(v, dict): + self.writer.add_scalars(k, v, global_step=step, **kwargs) + self.writer.flush() + logger.debug("Successfully logged to TensorBoard") + + @on_main_process + def log_images(self, values: dict, step: Optional[int], **kwargs): + """ + Logs `images` to the current run. + + Args: + values (Dictionary `str` to `List` of `np.ndarray` or `PIL.Image`): + Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs: + Additional key word arguments passed along to the `SummaryWriter.add_image` method. + """ + for k, v in values.items(): + self.writer.add_images(k, v, global_step=step, **kwargs) + logger.debug("Successfully logged images to TensorBoard") + + @on_main_process + def finish(self): + """ + Closes `TensorBoard` writer + """ + self.writer.close() + logger.debug("TensorBoard writer closed") + + +class WandBTracker(GeneralTracker): + """ + A `Tracker` class that supports `wandb`. Should be initialized at the start of your script. + + Args: + run_name (`str`): + The name of the experiment run. + **kwargs (additional keyword arguments, *optional*): + Additional key word arguments passed along to the `wandb.init` method. + """ + + name = "wandb" + requires_logging_directory = False + main_process_only = False + + def __init__(self, run_name: str, **kwargs): + super().__init__() + self.run_name = run_name + self.init_kwargs = kwargs + + @on_main_process + def start(self): + import wandb + + self.run = wandb.init(project=self.run_name, **self.init_kwargs) + logger.debug(f"Initialized WandB project {self.run_name}") + logger.debug( + "Make sure to log any initial configurations with `self.store_init_configuration` before training!" + ) + + @property + def tracker(self): + return self.run + + @on_main_process + def store_init_configuration(self, values: dict): + """ + Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. + + Args: + values (Dictionary `str` to `bool`, `str`, `float` or `int`): + Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`, + `str`, `float`, `int`, or `None`. + """ + import wandb + + if os.environ.get("WANDB_MODE") == "offline": + # In offline mode, restart wandb with config included + if hasattr(self, "run") and self.run: + self.run.finish() + + init_kwargs = self.init_kwargs.copy() + init_kwargs["config"] = values + self.run = wandb.init(project=self.run_name, **init_kwargs) + else: + wandb.config.update(values, allow_val_change=True) + logger.debug("Stored initial configuration hyperparameters to WandB") + + @on_main_process + def log(self, values: dict, step: Optional[int] = None, **kwargs): + """ + Logs `values` to the current run. + + Args: + values (Dictionary `str` to `str`, `float`, `int` or `dict` of `str` to `float`/`int`): + Values to be logged as key-value pairs. The values need to have type `str`, `float`, `int` or `dict` of + `str` to `float`/`int`. + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs: + Additional key word arguments passed along to the `wandb.log` method. + """ + self.run.log(values, step=step, **kwargs) + logger.debug("Successfully logged to WandB") + + @on_main_process + def log_images(self, values: dict, step: Optional[int] = None, **kwargs): + """ + Logs `images` to the current run. + + Args: + values (Dictionary `str` to `List` of `np.ndarray` or `PIL.Image`): + Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs: + Additional key word arguments passed along to the `wandb.log` method. + """ + import wandb + + for k, v in values.items(): + self.log({k: [wandb.Image(image) for image in v]}, step=step, **kwargs) + logger.debug("Successfully logged images to WandB") + + @on_main_process + def log_table( + self, + table_name: str, + columns: list[str] = None, + data: list[list[Any]] = None, + dataframe: Any = None, + step: Optional[int] = None, + **kwargs, + ): + """ + Log a Table containing any object type (text, image, audio, video, molecule, html, etc). Can be defined either + with `columns` and `data` or with `dataframe`. + + Args: + table_name (`str`): + The name to give to the logged table on the wandb workspace + columns (list of `str`, *optional*): + The name of the columns on the table + data (List of List of Any data type, *optional*): + The data to be logged in the table + dataframe (Any data type, *optional*): + The data to be logged in the table + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + """ + import wandb + + values = {table_name: wandb.Table(columns=columns, data=data, dataframe=dataframe)} + self.log(values, step=step, **kwargs) + + @on_main_process + def finish(self): + """ + Closes `wandb` writer + """ + self.run.finish() + logger.debug("WandB run closed") + + +class TrackioTracker(GeneralTracker): + """ + A `Tracker` class that supports `trackio`. Should be initialized at the start of your script. + + Args: + run_name (`str`): + The name of the experiment run. Will be used as the `project` name when instantiating trackio. + **kwargs (additional keyword arguments, *optional*): + Additional key word arguments passed along to the `trackio.init` method. Refer to this + [init](https://github.com/gradio-app/trackio/blob/814809552310468b13f84f33764f1369b4e5136c/trackio/__init__.py#L22) + to see all supported key word arguments. + """ + + name = "trackio" + requires_logging_directory = False + main_process_only = False + + def __init__(self, run_name: str, **kwargs): + super().__init__() + self.run_name = run_name + self.init_kwargs = kwargs + + @on_main_process + def start(self): + import trackio + + self.run = trackio.init(project=self.run_name, **self.init_kwargs) + logger.debug(f"Initialized trackio project {self.run_name}") + logger.debug( + "Make sure to log any initial configurations with `self.store_init_configuration` before training!" + ) + + @property + def tracker(self): + return self.run + + @on_main_process + def store_init_configuration(self, values: dict): + """ + Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. + + Args: + values (Dictionary `str` to `bool`, `str`, `float` or `int`): + Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`, + `str`, `float`, `int`, or `None`. + """ + import trackio + + trackio.config.update(values, allow_val_change=True) + logger.debug("Stored initial configuration hyperparameters to trackio") + + @on_main_process + def log(self, values: dict, step: Optional[int] = None, **kwargs): + """ + Logs `values` to the current run. + + Args: + values (Dictionary `str` to `str`, `float`, `int` or `dict` of `str` to `float`/`int`): + Values to be logged as key-value pairs. The values need to have type `str`, `float`, `int` or `dict` of + `str` to `float`/`int`. + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs: + Additional key word arguments passed along to the `trackio.log` method. + """ + self.run.log(values, **kwargs) + logger.debug("Successfully logged to trackio") + + @on_main_process + def finish(self): + """ + Closes `trackio` run + """ + self.run.finish() + logger.debug("trackio run closed") + + +class CometMLTracker(GeneralTracker): + """ + A `Tracker` class that supports `comet_ml`. Should be initialized at the start of your script. + + API keys must be stored in a Comet config file. + + Note: + For `comet_ml` versions < 3.41.0, additional keyword arguments are passed to `comet_ml.Experiment` instead: + https://www.comet.com/docs/v2/api-and-sdk/python-sdk/reference/Experiment/#comet_ml.Experiment.__init__ + + Args: + run_name (`str`): + The name of the experiment run. + **kwargs (additional keyword arguments, *optional*): + Additional key word arguments passed along to the `comet_ml.start` method: + https://www.comet.com/docs/v2/api-and-sdk/python-sdk/reference/start/ + """ + + name = "comet_ml" + requires_logging_directory = False + + def __init__(self, run_name: str, **kwargs): + super().__init__() + self.run_name = run_name + self.init_kwargs = kwargs + + @on_main_process + def start(self): + import comet_ml + + comet_version = version.parse(comet_ml.__version__) + if compare_versions(comet_version, ">=", "3.41.0"): + self.writer = comet_ml.start(project_name=self.run_name, **self.init_kwargs) + else: + logger.info("Update `comet_ml` (>=3.41.0) for experiment reuse and offline support.") + self.writer = comet_ml.Experiment(project_name=self.run_name, **self.init_kwargs) + + logger.debug(f"Initialized CometML project {self.run_name}") + logger.debug( + "Make sure to log any initial configurations with `self.store_init_configuration` before training!" + ) + + @property + def tracker(self): + return self.writer + + @on_main_process + def store_init_configuration(self, values: dict): + """ + Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. + + Args: + values (Dictionary `str` to `bool`, `str`, `float` or `int`): + Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`, + `str`, `float`, `int`, or `None`. + """ + self.writer.log_parameters(values) + logger.debug("Stored initial configuration hyperparameters to Comet") + + @on_main_process + def log(self, values: dict, step: Optional[int] = None, **kwargs): + """ + Logs `values` to the current run. + + Args: + values (Dictionary `str` to `str`, `float`, `int` or `dict` of `str` to `float`/`int`): + Values to be logged as key-value pairs. The values need to have type `str`, `float`, `int` or `dict` of + `str` to `float`/`int`. + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs: + Additional key word arguments passed along to either `Experiment.log_metric`, `Experiment.log_other`, + or `Experiment.log_metrics` method based on the contents of `values`. + """ + if step is not None: + self.writer.set_step(step) + for k, v in values.items(): + if isinstance(v, (int, float)): + self.writer.log_metric(k, v, step=step, **kwargs) + elif isinstance(v, str): + self.writer.log_other(k, v, **kwargs) + elif isinstance(v, dict): + self.writer.log_metrics(v, step=step, **kwargs) + logger.debug("Successfully logged to Comet") + + @on_main_process + def finish(self): + """ + Flush `comet-ml` writer + """ + self.writer.end() + logger.debug("Comet run flushed") + + +class AimTracker(GeneralTracker): + """ + A `Tracker` class that supports `aim`. Should be initialized at the start of your script. + + Args: + run_name (`str`): + The name of the experiment run. + **kwargs (additional keyword arguments, *optional*): + Additional key word arguments passed along to the `Run.__init__` method. + """ + + name = "aim" + requires_logging_directory = True + + def __init__(self, run_name: str, logging_dir: Optional[Union[str, os.PathLike]] = ".", **kwargs): + super().__init__() + self.run_name = run_name + self.aim_repo_path = logging_dir + self.init_kwargs = kwargs + + @on_main_process + def start(self): + from aim import Run + + self.writer = Run(repo=self.aim_repo_path, **self.init_kwargs) + self.writer.name = self.run_name + logger.debug(f"Initialized Aim project {self.run_name}") + logger.debug( + "Make sure to log any initial configurations with `self.store_init_configuration` before training!" + ) + + @property + def tracker(self): + return self.writer + + @on_main_process + def store_init_configuration(self, values: dict): + """ + Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. + + Args: + values (`dict`): + Values to be stored as initial hyperparameters as key-value pairs. + """ + self.writer["hparams"] = values + + @on_main_process + def log(self, values: dict, step: Optional[int], **kwargs): + """ + Logs `values` to the current run. + + Args: + values (`dict`): + Values to be logged as key-value pairs. + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs: + Additional key word arguments passed along to the `Run.track` method. + """ + # Note: replace this with the dictionary support when merged + for key, value in values.items(): + self.writer.track(value, name=key, step=step, **kwargs) + + @on_main_process + def log_images(self, values: dict, step: Optional[int] = None, kwargs: Optional[dict[str, dict]] = None): + """ + Logs `images` to the current run. + + Args: + values (`Dict[str, Union[np.ndarray, PIL.Image, Tuple[np.ndarray, str], Tuple[PIL.Image, str]]]`): + Values to be logged as key-value pairs. The values need to have type `np.ndarray` or PIL.Image. If a + tuple is provided, the first element should be the image and the second element should be the caption. + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs (`Dict[str, dict]`): + Additional key word arguments passed along to the `Run.Image` and `Run.track` method specified by the + keys `aim_image` and `track`, respectively. + """ + import aim + + aim_image_kw = {} + track_kw = {} + + if kwargs is not None: + aim_image_kw = kwargs.get("aim_image", {}) + track_kw = kwargs.get("track", {}) + + for key, value in values.items(): + if isinstance(value, tuple): + img, caption = value + else: + img, caption = value, "" + aim_image = aim.Image(img, caption=caption, **aim_image_kw) + self.writer.track(aim_image, name=key, step=step, **track_kw) + + @on_main_process + def finish(self): + """ + Closes `aim` writer + """ + self.writer.close() + + +class MLflowTracker(GeneralTracker): + """ + A `Tracker` class that supports `mlflow`. Should be initialized at the start of your script. + + Args: + experiment_name (`str`, *optional*): + Name of the experiment. Environment variable MLFLOW_EXPERIMENT_NAME has priority over this argument. + logging_dir (`str` or `os.PathLike`, defaults to `"."`): + Location for mlflow logs to be stored. + run_id (`str`, *optional*): + If specified, get the run with the specified UUID and log parameters and metrics under that run. The run’s + end time is unset and its status is set to running, but the run’s other attributes (source_version, + source_type, etc.) are not changed. Environment variable MLFLOW_RUN_ID has priority over this argument. + tags (`Dict[str, str]`, *optional*): + An optional `dict` of `str` keys and values, or a `str` dump from a `dict`, to set as tags on the run. If a + run is being resumed, these tags are set on the resumed run. If a new run is being created, these tags are + set on the new run. Environment variable MLFLOW_TAGS has priority over this argument. + nested_run (`bool`, *optional*, defaults to `False`): + Controls whether run is nested in parent run. True creates a nested run. Environment variable + MLFLOW_NESTED_RUN has priority over this argument. + run_name (`str`, *optional*): + Name of new run (stored as a mlflow.runName tag). Used only when `run_id` is unspecified. + description (`str`, *optional*): + An optional string that populates the description box of the run. If a run is being resumed, the + description is set on the resumed run. If a new run is being created, the description is set on the new + run. + """ + + name = "mlflow" + requires_logging_directory = False + + def __init__( + self, + experiment_name: str = None, + logging_dir: Optional[Union[str, os.PathLike]] = None, + run_id: Optional[str] = None, + tags: Optional[Union[dict[str, Any], str]] = None, + nested_run: Optional[bool] = False, + run_name: Optional[str] = None, + description: Optional[str] = None, + ): + experiment_name = os.environ.get("MLFLOW_EXPERIMENT_NAME", experiment_name) + run_id = os.environ.get("MLFLOW_RUN_ID", run_id) + tags = os.environ.get("MLFLOW_TAGS", tags) + if isinstance(tags, str): + tags = json.loads(tags) + + nested_run = os.environ.get("MLFLOW_NESTED_RUN", nested_run) + + self.experiment_name = experiment_name + self.logging_dir = logging_dir + self.run_id = run_id + self.tags = tags + self.nested_run = nested_run + self.run_name = run_name + self.description = description + + @on_main_process + def start(self): + import mlflow + + exps = mlflow.search_experiments(filter_string=f"name = '{self.experiment_name}'") + if len(exps) > 0: + if len(exps) > 1: + logger.warning("Multiple experiments with the same name found. Using first one.") + experiment_id = exps[0].experiment_id + else: + experiment_id = mlflow.create_experiment( + name=self.experiment_name, + artifact_location=self.logging_dir, + tags=self.tags, + ) + + self.active_run = mlflow.start_run( + run_id=self.run_id, + experiment_id=experiment_id, + run_name=self.run_name, + nested=self.nested_run, + tags=self.tags, + description=self.description, + ) + + logger.debug(f"Initialized mlflow experiment {self.experiment_name}") + logger.debug( + "Make sure to log any initial configurations with `self.store_init_configuration` before training!" + ) + + @property + def tracker(self): + return self.active_run + + @on_main_process + def store_init_configuration(self, values: dict): + """ + Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. + + Args: + values (`dict`): + Values to be stored as initial hyperparameters as key-value pairs. + """ + import mlflow + + for name, value in list(values.items()): + # internally, all values are converted to str in MLflow + if len(str(value)) > mlflow.utils.validation.MAX_PARAM_VAL_LENGTH: + logger.warning_once( + f'Accelerate is attempting to log a value of "{value}" for key "{name}" as a parameter. MLflow\'s' + f" log_param() only accepts values no longer than {mlflow.utils.validation.MAX_PARAM_VAL_LENGTH} characters so we dropped this attribute." + ) + del values[name] + + values_list = list(values.items()) + + # MLflow cannot log more than 100 values in one go, so we have to split it + for i in range(0, len(values_list), mlflow.utils.validation.MAX_PARAMS_TAGS_PER_BATCH): + mlflow.log_params(dict(values_list[i : i + mlflow.utils.validation.MAX_PARAMS_TAGS_PER_BATCH])) + + logger.debug("Stored initial configuration hyperparameters to MLflow") + + @on_main_process + def log(self, values: dict, step: Optional[int]): + """ + Logs `values` to the current run. + + Args: + values (`dict`): + Values to be logged as key-value pairs. + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + """ + metrics = {} + for k, v in values.items(): + if isinstance(v, (int, float)): + metrics[k] = v + else: + logger.warning_once( + f'MLflowTracker is attempting to log a value of "{v}" of type {type(v)} for key "{k}" as a metric. ' + "MLflow's log_metric() only accepts float and int types so we dropped this attribute." + ) + import mlflow + + mlflow.log_metrics(metrics, step=step) + logger.debug("Successfully logged to mlflow") + + @on_main_process + def log_figure(self, figure: Any, artifact_file: str, **save_kwargs): + """ + Logs an figure to the current run. + + Args: + figure (Any): + The figure to be logged. + artifact_file (`str`, *optional*): + The run-relative artifact file path in posixpath format to which the image is saved. + If not provided, the image is saved to a default location. + **kwargs: + Additional keyword arguments passed to the underlying mlflow.log_image function. + """ + import mlflow + + mlflow.log_figure(figure=figure, artifact_file=artifact_file, **save_kwargs) + logger.debug("Successfully logged image to mlflow") + + @on_main_process + def log_artifacts(self, local_dir: str, artifact_path: Optional[str] = None): + """ + Logs an artifacts (all content of a dir) to the current run. + + local_dir (`str`): + Path to the directory to be logged as an artifact. + artifact_path (`str`, *optional*): + Directory within the run's artifact directory where the artifact will be logged. If omitted, the + artifact will be logged to the root of the run's artifact directory. The run step. If included, the + artifact will be affiliated with this step. + """ + import mlflow + + mlflow.log_artifacts(local_dir=local_dir, artifact_path=artifact_path) + logger.debug("Successfully logged artofact to mlflow") + + @on_main_process + def log_artifact(self, local_path: str, artifact_path: Optional[str] = None): + """ + Logs an artifact (file) to the current run. + + local_path (`str`): + Path to the file to be logged as an artifact. + artifact_path (`str`, *optional*): + Directory within the run's artifact directory where the artifact will be logged. If omitted, the + artifact will be logged to the root of the run's artifact directory. The run step. If included, the + artifact will be affiliated with this step. + """ + import mlflow + + mlflow.log_artifact(local_path=local_path, artifact_path=artifact_path) + logger.debug("Successfully logged artofact to mlflow") + + @on_main_process + def finish(self): + """ + End the active MLflow run. + """ + import mlflow + + mlflow.end_run() + + +class ClearMLTracker(GeneralTracker): + """ + A `Tracker` class that supports `clearml`. Should be initialized at the start of your script. + + Args: + run_name (`str`, *optional*): + Name of the experiment. Environment variables `CLEARML_PROJECT` and `CLEARML_TASK` have priority over this + argument. + **kwargs (additional keyword arguments, *optional*): + Kwargs passed along to the `Task.__init__` method. + """ + + name = "clearml" + requires_logging_directory = False + + def __init__(self, run_name: str = None, **kwargs): + super().__init__() + self.user_provided_run_name = run_name + self._initialized_externally = False + self.init_kwargs = kwargs + + @on_main_process + def start(self): + from clearml import Task + + current_task = Task.current_task() + if current_task: + self._initialized_externally = True + self.task = current_task + return + + task_init_args = {**self.init_kwargs} + task_init_args.setdefault("project_name", os.environ.get("CLEARML_PROJECT", self.user_provided_run_name)) + task_init_args.setdefault("task_name", os.environ.get("CLEARML_TASK", self.user_provided_run_name)) + self.task = Task.init(**task_init_args) + + @property + def tracker(self): + return self.task + + @on_main_process + def store_init_configuration(self, values: dict): + """ + Connect configuration dictionary to the Task object. Should be run at the beginning of your experiment. + + Args: + values (`dict`): + Values to be stored as initial hyperparameters as key-value pairs. + """ + return self.task.connect_configuration(values) + + @on_main_process + def log(self, values: dict[str, Union[int, float]], step: Optional[int] = None, **kwargs): + """ + Logs `values` dictionary to the current run. The dictionary keys must be strings. The dictionary values must be + ints or floats + + Args: + values (`Dict[str, Union[int, float]]`): + Values to be logged as key-value pairs. If the key starts with 'eval_'/'test_'/'train_', the value will + be reported under the 'eval'/'test'/'train' series and the respective prefix will be removed. + Otherwise, the value will be reported under the 'train' series, and no prefix will be removed. + step (`int`, *optional*): + If specified, the values will be reported as scalars, with the iteration number equal to `step`. + Otherwise they will be reported as single values. + kwargs: + Additional key word arguments passed along to the `clearml.Logger.report_single_value` or + `clearml.Logger.report_scalar` methods. + """ + clearml_logger = self.task.get_logger() + for k, v in values.items(): + if not isinstance(v, (int, float)): + logger.warning_once( + "Accelerator is attempting to log a value of " + f'"{v}" of type {type(v)} for key "{k}" as a scalar. ' + "This invocation of ClearML logger's report_scalar() " + "is incorrect so we dropped this attribute." + ) + continue + if step is None: + clearml_logger.report_single_value(name=k, value=v, **kwargs) + continue + title, series = ClearMLTracker._get_title_series(k) + clearml_logger.report_scalar(title=title, series=series, value=v, iteration=step, **kwargs) + + @on_main_process + def log_images(self, values: dict, step: Optional[int] = None, **kwargs): + """ + Logs `images` to the current run. + + Args: + values (`Dict[str, List[Union[np.ndarray, PIL.Image]]`): + Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs: + Additional key word arguments passed along to the `clearml.Logger.report_image` method. + """ + clearml_logger = self.task.get_logger() + for k, v in values.items(): + title, series = ClearMLTracker._get_title_series(k) + clearml_logger.report_image(title=title, series=series, iteration=step, image=v, **kwargs) + + @on_main_process + def log_table( + self, + table_name: str, + columns: list[str] = None, + data: list[list[Any]] = None, + dataframe: Any = None, + step: Optional[int] = None, + **kwargs, + ): + """ + Log a Table to the task. Can be defined eitherwith `columns` and `data` or with `dataframe`. + + Args: + table_name (`str`): + The name of the table + columns (list of `str`, *optional*): + The name of the columns on the table + data (List of List of Any data type, *optional*): + The data to be logged in the table. If `columns` is not specified, then the first entry in data will be + the name of the columns of the table + dataframe (Any data type, *optional*): + The data to be logged in the table + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs: + Additional key word arguments passed along to the `clearml.Logger.report_table` method. + """ + to_report = dataframe + if dataframe is None: + if data is None: + raise ValueError( + "`ClearMLTracker.log_table` requires that `data` to be supplied if `dataframe` is `None`" + ) + to_report = [columns] + data if columns else data + title, series = ClearMLTracker._get_title_series(table_name) + self.task.get_logger().report_table(title=title, series=series, table_plot=to_report, iteration=step, **kwargs) + + @on_main_process + def finish(self): + """ + Close the ClearML task. If the task was initialized externally (e.g. by manually calling `Task.init`), this + function is a noop + """ + if self.task and not self._initialized_externally: + self.task.close() + + @staticmethod + def _get_title_series(name): + for prefix in ["eval", "test", "train"]: + if name.startswith(prefix + "_"): + return name[len(prefix) + 1 :], prefix + return name, "train" + + +class DVCLiveTracker(GeneralTracker): + """ + A `Tracker` class that supports `dvclive`. Should be initialized at the start of your script. + + Args: + run_name (`str`, *optional*): + Ignored for dvclive. See `kwargs` instead. + kwargs: + Additional key word arguments passed along to [`dvclive.Live()`](https://dvc.org/doc/dvclive/live). + + Example: + + ```py + from accelerate import Accelerator + + accelerator = Accelerator(log_with="dvclive") + accelerator.init_trackers(project_name="my_project", init_kwargs={"dvclive": {"dir": "my_directory"}}) + ``` + """ + + name = "dvclive" + requires_logging_directory = False + + def __init__(self, run_name: Optional[str] = None, live: Optional[Any] = None, **kwargs): + super().__init__() + self.live = live + self.init_kwargs = kwargs + + @on_main_process + def start(self): + from dvclive import Live + + self.live = self.live if self.live is not None else Live(**self.init_kwargs) + + @property + def tracker(self): + return self.live + + @on_main_process + def store_init_configuration(self, values: dict): + """ + Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. Stores the + hyperparameters in a yaml file for future use. + + Args: + values (Dictionary `str` to `bool`, `str`, `float`, `int`, or a List or Dict of those types): + Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`, + `str`, `float`, or `int`. + """ + self.live.log_params(values) + + @on_main_process + def log(self, values: dict, step: Optional[int] = None, **kwargs): + """ + Logs `values` to the current run. + + Args: + values (Dictionary `str` to `str`, `float`, or `int`): + Values to be logged as key-value pairs. The values need to have type `str`, `float`, or `int`. + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs: + Additional key word arguments passed along to `dvclive.Live.log_metric()`. + """ + from dvclive.plots import Metric + + if step is not None: + self.live.step = step + for k, v in values.items(): + if Metric.could_log(v): + self.live.log_metric(k, v, **kwargs) + else: + logger.warning_once( + "Accelerator attempted to log a value of " + f'"{v}" of type {type(v)} for key "{k}" as a scalar. ' + "This invocation of DVCLive's Live.log_metric() " + "is incorrect so we dropped this attribute." + ) + self.live.next_step() + + @on_main_process + def finish(self): + """ + Closes `dvclive.Live()`. + """ + self.live.end() + + +class SwanLabTracker(GeneralTracker): + """ + A `Tracker` class that supports `swanlab`. Should be initialized at the start of your script. + + Args: + run_name (`str`): + The name of the experiment run. + **kwargs (additional keyword arguments, *optional*): + Additional key word arguments passed along to the `swanlab.init` method. + """ + + name = "swanlab" + requires_logging_directory = False + main_process_only = False + + def __init__(self, run_name: str, **kwargs): + super().__init__() + self.run_name = run_name + self.init_kwargs = kwargs + + @on_main_process + def start(self): + import swanlab + + self.run = swanlab.init(project=self.run_name, **self.init_kwargs) + swanlab.config["FRAMEWORK"] = "🤗Accelerate" # add accelerate logo in config + logger.debug(f"Initialized SwanLab project {self.run_name}") + logger.debug( + "Make sure to log any initial configurations with `self.store_init_configuration` before training!" + ) + + @property + def tracker(self): + return self.run + + @on_main_process + def store_init_configuration(self, values: dict): + """ + Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. + + Args: + values (Dictionary `str` to `bool`, `str`, `float` or `int`): + Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`, + `str`, `float`, `int`, or `None`. + """ + import swanlab + + swanlab.config.update(values, allow_val_change=True) + logger.debug("Stored initial configuration hyperparameters to SwanLab") + + @on_main_process + def log(self, values: dict, step: Optional[int] = None, **kwargs): + """ + Logs `values` to the current run. + + Args: + data : Dict[str, DataType] + Data must be a dict. The key must be a string with 0-9, a-z, A-Z, " ", "_", "-", "/". The value must be a + `float`, `float convertible object`, `int` or `swanlab.data.BaseType`. + step : int, optional + The step number of the current data, if not provided, it will be automatically incremented. + If step is duplicated, the data will be ignored. + kwargs: + Additional key word arguments passed along to the `swanlab.log` method. Likes: + print_to_console : bool, optional + Whether to print the data to the console, the default is False. + """ + self.run.log(values, step=step, **kwargs) + logger.debug("Successfully logged to SwanLab") + + @on_main_process + def log_images(self, values: dict, step: Optional[int] = None, **kwargs): + """ + Logs `images` to the current run. + + Args: + values (Dictionary `str` to `List` of `np.ndarray` or `PIL.Image`): + Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs: + Additional key word arguments passed along to the `swanlab.log` method. Likes: + print_to_console : bool, optional + Whether to print the data to the console, the default is False. + """ + import swanlab + + for k, v in values.items(): + self.log({k: [swanlab.Image(image) for image in v]}, step=step, **kwargs) + logger.debug("Successfully logged images to SwanLab") + + @on_main_process + def finish(self): + """ + Closes `swanlab` writer + """ + self.run.finish() + logger.debug("SwanLab run closed") + + +LOGGER_TYPE_TO_CLASS = { + "aim": AimTracker, + "comet_ml": CometMLTracker, + "mlflow": MLflowTracker, + "tensorboard": TensorBoardTracker, + "wandb": WandBTracker, + "clearml": ClearMLTracker, + "dvclive": DVCLiveTracker, + "swanlab": SwanLabTracker, + "trackio": TrackioTracker, +} + + +def filter_trackers( + log_with: list[Union[str, LoggerType, GeneralTracker]], + logging_dir: Union[str, os.PathLike] = None, +): + """ + Takes in a list of potential tracker types and checks that: + - The tracker wanted is available in that environment + - Filters out repeats of tracker types + - If `all` is in `log_with`, will return all trackers in the environment + - If a tracker requires a `logging_dir`, ensures that `logging_dir` is not `None` + + Args: + log_with (list of `str`, [`~utils.LoggerType`] or [`~tracking.GeneralTracker`], *optional*): + A list of loggers to be setup for experiment tracking. Should be one or several of: + + - `"all"` + - `"tensorboard"` + - `"wandb"` + - `"trackio"` + - `"aim"` + - `"comet_ml"` + - `"mlflow"` + - `"dvclive"` + - `"swanlab"` + If `"all"` is selected, will pick up all available trackers in the environment and initialize them. Can + also accept implementations of `GeneralTracker` for custom trackers, and can be combined with `"all"`. + logging_dir (`str`, `os.PathLike`, *optional*): + A path to a directory for storing logs of locally-compatible loggers. + """ + loggers = [] + if log_with is not None: + if not isinstance(log_with, (list, tuple)): + log_with = [log_with] + if "all" in log_with or LoggerType.ALL in log_with: + loggers = [o for o in log_with if issubclass(type(o), GeneralTracker)] + get_available_trackers() + else: + for log_type in log_with: + if log_type not in LoggerType and not issubclass(type(log_type), GeneralTracker): + raise ValueError(f"Unsupported logging capability: {log_type}. Choose between {LoggerType.list()}") + if issubclass(type(log_type), GeneralTracker): + loggers.append(log_type) + else: + log_type = LoggerType(log_type) + if log_type not in loggers: + if log_type in get_available_trackers(): + tracker_init = LOGGER_TYPE_TO_CLASS[str(log_type)] + if tracker_init.requires_logging_directory: + if logging_dir is None: + raise ValueError( + f"Logging with `{log_type}` requires a `logging_dir` to be passed in." + ) + loggers.append(log_type) + else: + logger.debug(f"Tried adding logger {log_type}, but package is unavailable in the system.") + + return loggers diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/__init__.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d051a8fb1a1ef96dd734c39b0bdd4740e657632f --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/__init__.py @@ -0,0 +1,303 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from ..parallelism_config import ParallelismConfig +from .ao import convert_model_to_fp8_ao, filter_first_and_last_linear_layers, has_ao_layers +from .constants import ( + MITA_PROFILING_AVAILABLE_PYTORCH_VERSION, + MODEL_NAME, + OPTIMIZER_NAME, + PROFILE_PATTERN_NAME, + RNG_STATE_NAME, + SAFE_MODEL_NAME, + SAFE_WEIGHTS_INDEX_NAME, + SAFE_WEIGHTS_NAME, + SAFE_WEIGHTS_PATTERN_NAME, + SAMPLER_NAME, + SCALER_NAME, + SCHEDULER_NAME, + TORCH_DISTRIBUTED_OPERATION_TYPES, + TORCH_LAUNCH_PARAMS, + WEIGHTS_INDEX_NAME, + WEIGHTS_NAME, + WEIGHTS_PATTERN_NAME, + XPU_PROFILING_AVAILABLE_PYTORCH_VERSION, +) +from .dataclasses import ( + AORecipeKwargs, + AutocastKwargs, + BnbQuantizationConfig, + ComputeEnvironment, + CustomDtype, + DataLoaderConfiguration, + DDPCommunicationHookType, + DeepSpeedPlugin, + DistributedDataParallelKwargs, + DistributedType, + DynamoBackend, + FP8RecipeKwargs, + FullyShardedDataParallelPlugin, + GradientAccumulationPlugin, + GradScalerKwargs, + InitProcessGroupKwargs, + KwargsHandler, + LoggerType, + MegatronLMPlugin, + MSAMPRecipeKwargs, + PrecisionType, + ProfileKwargs, + ProjectConfiguration, + RNGType, + SageMakerDistributedType, + TensorInformation, + TERecipeKwargs, + TorchContextParallelConfig, + TorchDynamoPlugin, + TorchTensorParallelConfig, + TorchTensorParallelPlugin, + add_model_config_to_megatron_parser, +) +from .environment import ( + are_libraries_initialized, + check_cuda_fp8_capability, + check_cuda_p2p_ib_support, + clear_environment, + convert_dict_to_env_variables, + get_cpu_distributed_information, + get_gpu_info, + get_int_from_env, + parse_choice_from_env, + parse_flag_from_env, + patch_environment, + purge_accelerate_environment, + set_numa_affinity, + str_to_bool, +) +from .imports import ( + deepspeed_required, + get_ccl_version, + is_4bit_bnb_available, + is_8bit_bnb_available, + is_aim_available, + is_bf16_available, + is_bitsandbytes_multi_backend_available, + is_bnb_available, + is_boto3_available, + is_ccl_available, + is_clearml_available, + is_comet_ml_available, + is_cuda_available, + is_datasets_available, + is_deepspeed_available, + is_dvclive_available, + is_fp8_available, + is_fp16_available, + is_habana_gaudi1, + is_hpu_available, + is_import_timer_available, + is_ipex_available, + is_lomo_available, + is_matplotlib_available, + is_megatron_lm_available, + is_mlflow_available, + is_mlu_available, + is_mps_available, + is_msamp_available, + is_musa_available, + is_npu_available, + is_pandas_available, + is_peft_available, + is_pippy_available, + is_pynvml_available, + is_pytest_available, + is_rich_available, + is_sagemaker_available, + is_schedulefree_available, + is_sdaa_available, + is_swanlab_available, + is_tensorboard_available, + is_timm_available, + is_torch_xla_available, + is_torchao_available, + is_torchdata_available, + is_torchdata_stateful_dataloader_available, + is_torchvision_available, + is_trackio_available, + is_transformer_engine_available, + is_transformers_available, + is_triton_available, + is_wandb_available, + is_weights_only_available, + is_xccl_available, + is_xpu_available, + torchao_required, +) +from .modeling import ( + align_module_device, + calculate_maximum_sizes, + check_device_map, + check_tied_parameters_in_config, + check_tied_parameters_on_same_device, + compute_module_sizes, + convert_file_size_to_int, + dtype_byte_size, + find_tied_parameters, + get_balanced_memory, + get_grad_scaler, + get_max_layer_size, + get_max_memory, + get_mixed_precision_context_manager, + has_offloaded_params, + id_tensor_storage, + infer_auto_device_map, + is_peft_model, + load_checkpoint_in_model, + load_offloaded_weights, + load_state_dict, + named_module_tensors, + retie_parameters, + set_module_tensor_to_device, +) +from .offload import ( + OffloadedWeightsLoader, + PrefixedDataset, + extract_submodules_state_dict, + load_offloaded_weight, + offload_state_dict, + offload_weight, + save_offload_index, +) +from .operations import ( + CannotPadNestedTensorWarning, + GatheredParameters, + broadcast, + broadcast_object_list, + concatenate, + convert_outputs_to_fp32, + convert_to_fp32, + copy_tensor_to_devices, + find_batch_size, + find_device, + gather, + gather_object, + get_data_structure, + honor_type, + ignorant_find_batch_size, + initialize_tensors, + is_namedtuple, + is_tensor_information, + is_torch_tensor, + listify, + pad_across_processes, + pad_input_tensors, + recursively_apply, + reduce, + send_to_device, + slice_tensors, +) +from .versions import compare_versions, is_torch_version + + +if is_deepspeed_available(): + from .deepspeed import ( + DeepSpeedEngineWrapper, + DeepSpeedOptimizerWrapper, + DeepSpeedSchedulerWrapper, + DummyOptim, + DummyScheduler, + HfDeepSpeedConfig, + get_active_deepspeed_plugin, + map_pytorch_optim_to_deepspeed, + ) + +from .bnb import has_4bit_bnb_layers, load_and_quantize_model +from .fsdp_utils import ( + disable_fsdp_ram_efficient_loading, + enable_fsdp_ram_efficient_loading, + ensure_weights_retied, + fsdp2_apply_ac, + fsdp2_canonicalize_names, + fsdp2_load_full_state_dict, + fsdp2_prepare_model, + fsdp2_switch_optimizer_parameters, + get_fsdp2_grad_scaler, + load_fsdp_model, + load_fsdp_optimizer, + merge_fsdp_weights, + save_fsdp_model, + save_fsdp_optimizer, +) +from .launch import ( + PrepareForLaunch, + _filter_args, + prepare_deepspeed_cmd_env, + prepare_multi_gpu_env, + prepare_sagemager_args_inputs, + prepare_simple_launcher_cmd_env, + prepare_tpu, +) + +# For docs +from .megatron_lm import ( + AbstractTrainStep, + BertTrainStep, + GPTTrainStep, + MegatronLMDummyDataLoader, + MegatronLMDummyScheduler, + T5TrainStep, + avg_losses_across_data_parallel_group, +) + + +if is_megatron_lm_available(): + from .megatron_lm import ( + MegatronEngine, + MegatronLMOptimizerWrapper, + MegatronLMSchedulerWrapper, + gather_across_data_parallel_groups, + ) + from .megatron_lm import initialize as megatron_lm_initialize + from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader + from .megatron_lm import prepare_model_optimizer_scheduler as megatron_lm_prepare_model_optimizer_scheduler + from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer + from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler +from .memory import find_executable_batch_size, release_memory +from .other import ( + check_os_kernel, + clean_state_dict_for_safetensors, + compile_regions, + compile_regions_deepspeed, + convert_bytes, + extract_model_from_parallel, + get_module_children_bottom_up, + get_pretty_name, + has_compiled_regions, + is_compiled_module, + is_port_in_use, + load, + merge_dicts, + model_has_dtensor, + recursive_getattr, + save, + wait_for_everyone, + write_basic_config, +) +from .random import set_seed, synchronize_rng_state, synchronize_rng_states +from .torch_xla import install_xla +from .tqdm import tqdm +from .transformer_engine import ( + apply_fp8_autowrap, + contextual_fp8_autocast, + convert_model, + has_transformer_engine_layers, +) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/ao.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/ao.py new file mode 100644 index 0000000000000000000000000000000000000000..73155615b768a01f709bb8e0857617ba58a6ec83 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/ao.py @@ -0,0 +1,140 @@ +# Copyright 2025 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Needed utilities for torchao FP8 training. +""" + +from functools import partial +from typing import TYPE_CHECKING, Callable, Optional + +import torch + +from .imports import is_torchao_available, torchao_required + + +if TYPE_CHECKING: + if is_torchao_available(): + from torchao.float8.float8_linear import Float8LinearConfig + + +def find_first_last_linear_layers(model: torch.nn.Module): + """ + Finds the first and last linear layer names in a model. + + This is needed during FP8 to avoid issues with instability by keeping the first and last layers unquantized. + + Ref: https://x.com/xariusrke/status/1826669142604141052 + """ + first_linear, last_linear = None, None + for name, module in model.named_modules(): + if isinstance(module, torch.nn.Linear): + if first_linear is None: + first_linear = name + last_linear = name + return first_linear, last_linear + + +def filter_linear_layers(module, fqn: str, layers_to_filter: list[str]) -> bool: + """ + A function which will check if `module` is: + - a `torch.nn.Linear` layer + - has in_features and out_features divisible by 16 + - is not part of `layers_to_filter` + + Args: + module (`torch.nn.Module`): + The module to check. + fqn (`str`): + The fully qualified name of the layer. + layers_to_filter (`List[str]`): + The list of layers to filter. + """ + if isinstance(module, torch.nn.Linear): + if module.in_features % 16 != 0 or module.out_features % 16 != 0: + return False + if fqn in layers_to_filter: + return False + return True + + +def filter_first_and_last_linear_layers(module, fqn: str) -> bool: + """ + A filter function which will filter out all linear layers except the first and last. + + + + For stability reasons, we skip the first and last linear layers Otherwise can lead to the model not training or + converging properly + + + + Args: + module (`torch.nn.Module`): + The module to check. + fqn (`str`): + The fully qualified name of the layer. + """ + first_linear, last_linear = find_first_last_linear_layers(module) + return filter_linear_layers(module, fqn, layers_to_filter=[first_linear, last_linear]) + + +@torchao_required +def has_ao_layers(model: torch.nn.Module): + from torchao.float8.float8_linear import Float8Linear + + for name, module in model.named_modules(): + if isinstance(module, Float8Linear): + return True + return False + + +@torchao_required +def convert_model_to_fp8_ao( + model: torch.nn.Module, + config: Optional["Float8LinearConfig"] = None, + module_filter_func: Optional[Callable] = filter_first_and_last_linear_layers, +): + """ + Converts all `nn.Linear` layers in the model (except the first and last) to torchao's `Float8Linear` layer inplace. + + Args: + model (`torch.nn.Module`): + The model to convert. + config (`torchao.float8.Float8LinearConfig`, *optional*): + The configuration for the FP8 training. Recommended to utilize + `torchao.float8.recipe_name_to_linear_config` to generate this. In general, the default config should be + sufficient (what is passed when set to `None`). + module_filter_func (`Callable`, *optional*, defaults to `filter_linear_layers`): + Optional function that must take in a module and layer name, and returns a boolean indicating whether the + module should be converted to FP8. Defaults to `filter_linear_layers`. See it for an example. + + Example: + + ```python + from accelerate.utils.ao import convert_model_to_fp8_ao + + model = MyModel() + model.to("cuda") + convert_to_float8_training(model) + + model.train() + ``` + """ + from torchao.float8 import convert_to_float8_training + + first_linear, last_linear = find_first_last_linear_layers(model) + if module_filter_func is None: + module_filter_func = partial(filter_linear_layers, layers_to_filter=[first_linear, last_linear]) + convert_to_float8_training(model, module_filter_fn=module_filter_func, config=config) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/bnb.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..af4aa541233d21193aa5b302ee37c0b57dae4926 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/bnb.py @@ -0,0 +1,469 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import logging +import os +from copy import deepcopy +from typing import Optional, Union + +import torch +import torch.nn as nn + +from accelerate.utils.imports import ( + is_4bit_bnb_available, + is_8bit_bnb_available, +) + +from ..big_modeling import dispatch_model, init_empty_weights +from .dataclasses import BnbQuantizationConfig +from .modeling import ( + find_tied_parameters, + get_balanced_memory, + infer_auto_device_map, + load_checkpoint_in_model, + offload_weight, + set_module_tensor_to_device, +) + + +logger = logging.getLogger(__name__) + + +def load_and_quantize_model( + model: torch.nn.Module, + bnb_quantization_config: BnbQuantizationConfig, + weights_location: Union[str, os.PathLike] = None, + device_map: Optional[dict[str, Union[int, str, torch.device]]] = None, + no_split_module_classes: Optional[list[str]] = None, + max_memory: Optional[dict[Union[int, str], Union[int, str]]] = None, + offload_folder: Optional[Union[str, os.PathLike]] = None, + offload_state_dict: bool = False, +): + """ + This function will quantize the input model with the associated config passed in `bnb_quantization_config`. If the + model is in the meta device, we will load and dispatch the weights according to the `device_map` passed. If the + model is already loaded, we will quantize the model and put the model on the GPU, + + Args: + model (`torch.nn.Module`): + Input model. The model can be already loaded or on the meta device + bnb_quantization_config (`BnbQuantizationConfig`): + The bitsandbytes quantization parameters + weights_location (`str` or `os.PathLike`): + The folder weights_location to load. It can be: + - a path to a file containing a whole model state dict + - a path to a `.json` file containing the index to a sharded checkpoint + - a path to a folder containing a unique `.index.json` file and the shards of a checkpoint. + - a path to a folder containing a unique pytorch_model.bin file. + device_map (`Dict[str, Union[int, str, torch.device]]`, *optional*): + A map that specifies where each submodule should go. It doesn't need to be refined to each parameter/buffer + name, once a given module name is inside, every submodule of it will be sent to the same device. + no_split_module_classes (`List[str]`, *optional*): + A list of layer class names that should never be split across device (for instance any layer that has a + residual connection). + max_memory (`Dict`, *optional*): + A dictionary device identifier to maximum memory. Will default to the maximum memory available if unset. + offload_folder (`str` or `os.PathLike`, *optional*): + If the `device_map` contains any value `"disk"`, the folder where we will offload weights. + offload_state_dict (`bool`, *optional*, defaults to `False`): + If `True`, will temporarily offload the CPU state dict on the hard drive to avoid getting out of CPU RAM if + the weight of the CPU state dict + the biggest shard does not fit. + + Returns: + `torch.nn.Module`: The quantized model + """ + + load_in_4bit = bnb_quantization_config.load_in_4bit + load_in_8bit = bnb_quantization_config.load_in_8bit + + if load_in_8bit and not is_8bit_bnb_available(): + raise ImportError( + "You have a version of `bitsandbytes` that is not compatible with 8bit quantization," + " make sure you have the latest version of `bitsandbytes` installed." + ) + if load_in_4bit and not is_4bit_bnb_available(): + raise ValueError( + "You have a version of `bitsandbytes` that is not compatible with 4bit quantization," + "make sure you have the latest version of `bitsandbytes` installed." + ) + + modules_on_cpu = [] + # custom device map + if isinstance(device_map, dict) and len(device_map.keys()) > 1: + modules_on_cpu = [key for key, value in device_map.items() if value in ["disk", "cpu"]] + + # We keep some modules such as the lm_head in their original dtype for numerical stability reasons + if bnb_quantization_config.skip_modules is None: + bnb_quantization_config.skip_modules = get_keys_to_not_convert(model) + + # add cpu modules to skip modules only for 4-bit modules + if load_in_4bit: + bnb_quantization_config.skip_modules.extend(modules_on_cpu) + modules_to_not_convert = bnb_quantization_config.skip_modules + + # We add the modules we want to keep in full precision + if bnb_quantization_config.keep_in_fp32_modules is None: + bnb_quantization_config.keep_in_fp32_modules = [] + keep_in_fp32_modules = bnb_quantization_config.keep_in_fp32_modules + modules_to_not_convert.extend(keep_in_fp32_modules) + + # compatibility with peft + model.is_loaded_in_4bit = load_in_4bit + model.is_loaded_in_8bit = load_in_8bit + + model_device = get_parameter_device(model) + if model_device.type != "meta": + # quantization of an already loaded model + logger.warning( + "It is not recommended to quantize a loaded model. " + "The model should be instantiated under the `init_empty_weights` context manager." + ) + model = replace_with_bnb_layers(model, bnb_quantization_config, modules_to_not_convert=modules_to_not_convert) + # convert param to the right dtype + dtype = bnb_quantization_config.torch_dtype + for name, param in model.state_dict().items(): + if any(module_to_keep_in_fp32 in name for module_to_keep_in_fp32 in keep_in_fp32_modules): + param.to(torch.float32) + if param.dtype != torch.float32: + name = name.replace(".weight", "").replace(".bias", "") + param = getattr(model, name, None) + if param is not None: + param.to(torch.float32) + elif torch.is_floating_point(param): + param.to(dtype) + if model_device.type == "cuda": + model.cuda(torch.cuda.current_device()) + torch.cuda.empty_cache() + elif torch.cuda.is_available(): + model.to(torch.cuda.current_device()) + elif torch.xpu.is_available(): + model.to(torch.xpu.current_device()) + else: + raise RuntimeError("No GPU or Intel XPU found. A GPU or Intel XPU is needed for quantization.") + logger.info( + f"The model device type is {model_device.type}. However, gpu or intel xpu is needed for quantization." + "We move the model to it." + ) + return model + + elif weights_location is None: + raise RuntimeError( + f"`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} " + ) + + else: + with init_empty_weights(): + model = replace_with_bnb_layers( + model, bnb_quantization_config, modules_to_not_convert=modules_to_not_convert + ) + device_map = get_quantized_model_device_map( + model, + bnb_quantization_config, + device_map, + max_memory=max_memory, + no_split_module_classes=no_split_module_classes, + ) + if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): + offload_state_dict = True + + offload = any(x in list(device_map.values()) for x in ["cpu", "disk"]) + + load_checkpoint_in_model( + model, + weights_location, + device_map, + dtype=bnb_quantization_config.torch_dtype, + offload_folder=offload_folder, + offload_state_dict=offload_state_dict, + keep_in_fp32_modules=bnb_quantization_config.keep_in_fp32_modules, + offload_8bit_bnb=load_in_8bit and offload, + ) + return dispatch_model(model, device_map=device_map, offload_dir=offload_folder) + + +def get_quantized_model_device_map( + model, bnb_quantization_config, device_map=None, max_memory=None, no_split_module_classes=None +): + if device_map is None: + if torch.cuda.is_available(): + device_map = {"": torch.cuda.current_device()} + elif torch.xpu.is_available(): + device_map = {"": torch.xpu.current_device()} + else: + raise RuntimeError("No GPU found. A GPU is needed for quantization.") + logger.info("The device_map was not initialized.Setting device_map to `{'':torch.cuda.current_device()}`.") + + if isinstance(device_map, str): + if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: + raise ValueError( + "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or " + "'sequential'." + ) + + special_dtypes = {} + special_dtypes.update( + { + name: bnb_quantization_config.torch_dtype + for name, _ in model.named_parameters() + if any(m in name for m in bnb_quantization_config.skip_modules) + } + ) + special_dtypes.update( + { + name: torch.float32 + for name, _ in model.named_parameters() + if any(m in name for m in bnb_quantization_config.keep_in_fp32_modules) + } + ) + + kwargs = {} + kwargs["special_dtypes"] = special_dtypes + kwargs["no_split_module_classes"] = no_split_module_classes + kwargs["dtype"] = bnb_quantization_config.target_dtype + + # get max_memory for each device. + if device_map != "sequential": + max_memory = get_balanced_memory( + model, + low_zero=(device_map == "balanced_low_0"), + max_memory=max_memory, + **kwargs, + ) + + kwargs["max_memory"] = max_memory + device_map = infer_auto_device_map(model, **kwargs) + + if isinstance(device_map, dict): + # check if don't have any quantized module on the cpu + modules_not_to_convert = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fp32_modules + + device_map_without_some_modules = { + key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert + } + for device in ["cpu", "disk"]: + if device in device_map_without_some_modules.values(): + if bnb_quantization_config.load_in_4bit: + raise ValueError( + """ + Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit + the quantized model. If you want to dispatch the model on the CPU or the disk while keeping + these modules in `torch_dtype`, you need to pass a custom `device_map` to + `load_and_quantize_model`. Check + https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk + for more details. + """ + ) + else: + logger.info( + "Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit" + ) + del device_map_without_some_modules + return device_map + + +def replace_with_bnb_layers(model, bnb_quantization_config, modules_to_not_convert=None, current_key_name=None): + """ + A helper function to replace all `torch.nn.Linear` modules by `bnb.nn.Linear8bit` modules or by `bnb.nn.Linear4bit` + modules from the `bitsandbytes`library. The function will be run recursively and replace `torch.nn.Linear` modules. + + Parameters: + model (`torch.nn.Module`): + Input model or `torch.nn.Module` as the function is run recursively. + modules_to_not_convert (`List[str]`): + Names of the modules to not quantize convert. In practice we keep the `lm_head` in full precision for + numerical stability reasons. + current_key_name (`List[str]`, *optional*): + An array to track the current key of the recursion. This is used to check whether the current key (part of + it) is not in the list of modules to not convert. + """ + + if modules_to_not_convert is None: + modules_to_not_convert = [] + + model, has_been_replaced = _replace_with_bnb_layers( + model, bnb_quantization_config, modules_to_not_convert, current_key_name + ) + if not has_been_replaced: + logger.warning( + "You are loading your model in 8bit or 4bit but no linear modules were found in your model." + " this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers." + " Please double check your model architecture, or submit an issue on github if you think this is" + " a bug." + ) + return model + + +def _replace_with_bnb_layers( + model, + bnb_quantization_config, + modules_to_not_convert=None, + current_key_name=None, +): + """ + Private method that wraps the recursion for module replacement. + + Returns the converted model and a boolean that indicates if the conversion has been successfull or not. + """ + # bitsandbytes will initialize CUDA on import, so it needs to be imported lazily + import bitsandbytes as bnb + + has_been_replaced = False + for name, module in model.named_children(): + if current_key_name is None: + current_key_name = [] + current_key_name.append(name) + if isinstance(module, nn.Linear) and name not in modules_to_not_convert: + # Check if the current key is not in the `modules_to_not_convert` + current_key_name_str = ".".join(current_key_name) + proceed = True + for key in modules_to_not_convert: + if ( + (key in current_key_name_str) and (key + "." in current_key_name_str) + ) or key == current_key_name_str: + proceed = False + break + if proceed: + # Load bnb module with empty weight and replace ``nn.Linear` module + if bnb_quantization_config.load_in_8bit: + bnb_module = bnb.nn.Linear8bitLt( + module.in_features, + module.out_features, + module.bias is not None, + has_fp16_weights=False, + threshold=bnb_quantization_config.llm_int8_threshold, + ) + elif bnb_quantization_config.load_in_4bit: + bnb_module = bnb.nn.Linear4bit( + module.in_features, + module.out_features, + module.bias is not None, + bnb_quantization_config.bnb_4bit_compute_dtype, + compress_statistics=bnb_quantization_config.bnb_4bit_use_double_quant, + quant_type=bnb_quantization_config.bnb_4bit_quant_type, + ) + else: + raise ValueError("load_in_8bit and load_in_4bit can't be both False") + bnb_module.weight.data = module.weight.data + if module.bias is not None: + bnb_module.bias.data = module.bias.data + bnb_module.requires_grad_(False) + setattr(model, name, bnb_module) + has_been_replaced = True + if len(list(module.children())) > 0: + _, _has_been_replaced = _replace_with_bnb_layers( + module, bnb_quantization_config, modules_to_not_convert, current_key_name + ) + has_been_replaced = has_been_replaced | _has_been_replaced + # Remove the last key for recursion + current_key_name.pop(-1) + return model, has_been_replaced + + +def get_keys_to_not_convert(model): + r""" + An utility function to get the key of the module to keep in full precision if any For example for CausalLM modules + we may want to keep the lm_head in full precision for numerical stability reasons. For other architectures, we want + to keep the tied weights of the model. The function will return a list of the keys of the modules to not convert in + int8. + + Parameters: + model (`torch.nn.Module`): + Input model + """ + # Create a copy of the model + with init_empty_weights(): + tied_model = deepcopy(model) # this has 0 cost since it is done inside `init_empty_weights` context manager` + + tied_params = find_tied_parameters(tied_model) + # For compatibility with Accelerate < 0.18 + if isinstance(tied_params, dict): + tied_keys = sum(list(tied_params.values()), []) + list(tied_params.keys()) + else: + tied_keys = sum(tied_params, []) + has_tied_params = len(tied_keys) > 0 + + # Check if it is a base model + is_base_model = False + if hasattr(model, "base_model_prefix"): + is_base_model = not hasattr(model, model.base_model_prefix) + + # Ignore this for base models (BertModel, GPT2Model, etc.) + if (not has_tied_params) and is_base_model: + return [] + + # otherwise they have an attached head + list_modules = list(model.named_children()) + list_last_module = [list_modules[-1][0]] + + # add last module together with tied weights + intersection = set(list_last_module) - set(tied_keys) + list_untouched = list(set(tied_keys)) + list(intersection) + + # remove ".weight" from the keys + names_to_remove = [".weight", ".bias"] + filtered_module_names = [] + for name in list_untouched: + for name_to_remove in names_to_remove: + if name_to_remove in name: + name = name.replace(name_to_remove, "") + filtered_module_names.append(name) + + return filtered_module_names + + +def has_4bit_bnb_layers(model): + """Check if we have `bnb.nn.Linear4bit` or `bnb.nn.Linear8bitLt` layers inside our model""" + # bitsandbytes will initialize CUDA on import, so it needs to be imported lazily + import bitsandbytes as bnb + + for m in model.modules(): + if isinstance(m, bnb.nn.Linear4bit): + return True + return False + + +def get_parameter_device(parameter: nn.Module): + return next(parameter.parameters()).device + + +def quantize_and_offload_8bit(model, param, param_name, new_dtype, offload_folder, offload_index, fp16_statistics): + # if it is not quantized, we quantize and offload the quantized weights and the SCB stats + if fp16_statistics is None: + set_module_tensor_to_device(model, param_name, 0, dtype=new_dtype, value=param) + tensor_name = param_name + module = model + if "." in tensor_name: + splits = tensor_name.split(".") + for split in splits[:-1]: + new_module = getattr(module, split) + if new_module is None: + raise ValueError(f"{module} has no attribute {split}.") + module = new_module + tensor_name = splits[-1] + # offload weights + module._parameters[tensor_name].requires_grad = False + offload_weight(module._parameters[tensor_name], param_name, offload_folder, index=offload_index) + if hasattr(module._parameters[tensor_name], "SCB"): + offload_weight( + module._parameters[tensor_name].SCB, + param_name.replace("weight", "SCB"), + offload_folder, + index=offload_index, + ) + else: + offload_weight(param, param_name, offload_folder, index=offload_index) + offload_weight(fp16_statistics, param_name.replace("weight", "SCB"), offload_folder, index=offload_index) + + set_module_tensor_to_device(model, param_name, "meta", dtype=new_dtype, value=torch.empty(*param.size())) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/constants.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..2e2be5434b240105b523044d53988ee498bf8605 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/constants.py @@ -0,0 +1,105 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import operator as op + +import torch + + +SCALER_NAME = "scaler.pt" +MODEL_NAME = "pytorch_model" +SAFE_MODEL_NAME = "model" +RNG_STATE_NAME = "random_states" +OPTIMIZER_NAME = "optimizer" +SCHEDULER_NAME = "scheduler" +SAMPLER_NAME = "sampler" +PROFILE_PATTERN_NAME = "profile_{suffix}.json" +WEIGHTS_NAME = f"{MODEL_NAME}.bin" +WEIGHTS_PATTERN_NAME = "pytorch_model{suffix}.bin" +WEIGHTS_INDEX_NAME = f"{WEIGHTS_NAME}.index.json" +SAFE_WEIGHTS_NAME = f"{SAFE_MODEL_NAME}.safetensors" +SAFE_WEIGHTS_PATTERN_NAME = "model{suffix}.safetensors" +SAFE_WEIGHTS_INDEX_NAME = f"{SAFE_WEIGHTS_NAME}.index.json" +SAGEMAKER_PYTORCH_VERSION = "1.10.2" +SAGEMAKER_PYTHON_VERSION = "py38" +SAGEMAKER_TRANSFORMERS_VERSION = "4.17.0" +SAGEMAKER_PARALLEL_EC2_INSTANCES = ["ml.p3.16xlarge", "ml.p3dn.24xlarge", "ml.p4dn.24xlarge"] +FSDP_SHARDING_STRATEGY = ["FULL_SHARD", "SHARD_GRAD_OP", "NO_SHARD", "HYBRID_SHARD", "HYBRID_SHARD_ZERO2"] +FSDP_AUTO_WRAP_POLICY = ["TRANSFORMER_BASED_WRAP", "SIZE_BASED_WRAP", "NO_WRAP"] +FSDP_BACKWARD_PREFETCH = ["BACKWARD_PRE", "BACKWARD_POST", "NO_PREFETCH"] +FSDP_STATE_DICT_TYPE = ["FULL_STATE_DICT", "LOCAL_STATE_DICT", "SHARDED_STATE_DICT"] +FSDP2_STATE_DICT_TYPE = ["SHARDED_STATE_DICT", "FULL_STATE_DICT"] +FSDP_PYTORCH_VERSION = ( + "2.1.0.a0+32f93b1" # Technically should be 2.1.0, but MS-AMP uses this specific prerelease in their Docker image. +) +FSDP2_PYTORCH_VERSION = "2.6.0" +FSDP_MODEL_NAME = "pytorch_model_fsdp" +DEEPSPEED_MULTINODE_LAUNCHERS = ["pdsh", "standard", "openmpi", "mvapich", "mpich", "nossh", "slurm"] +TORCH_DYNAMO_MODES = ["default", "reduce-overhead", "max-autotune"] +ELASTIC_LOG_LINE_PREFIX_TEMPLATE_PYTORCH_VERSION = "2.2.0" +XPU_PROFILING_AVAILABLE_PYTORCH_VERSION = "2.4.0" +MITA_PROFILING_AVAILABLE_PYTORCH_VERSION = "2.1.0" +BETA_TP_AVAILABLE_PYTORCH_VERSION = "2.3.0" + +BETA_TP_AVAILABLE_TRANSFORMERS_VERSION = "4.52.0" +BETA_CP_AVAILABLE_PYTORCH_VERSION = "2.6.0" + +STR_OPERATION_TO_FUNC = {">": op.gt, ">=": op.ge, "==": op.eq, "!=": op.ne, "<=": op.le, "<": op.lt} + +# These are the args for `torch.distributed.launch` for pytorch < 1.9 +TORCH_LAUNCH_PARAMS = [ + "nnodes", + "nproc_per_node", + "rdzv_backend", + "rdzv_endpoint", + "rdzv_id", + "rdzv_conf", + "standalone", + "max_restarts", + "monitor_interval", + "start_method", + "role", + "module", + "m", + "no_python", + "run_path", + "log_dir", + "r", + "redirects", + "t", + "tee", + "node_rank", + "master_addr", + "master_port", +] + +CUDA_DISTRIBUTED_TYPES = ["DEEPSPEED", "MULTI_GPU", "FSDP", "MEGATRON_LM", "TP"] +TORCH_DISTRIBUTED_OPERATION_TYPES = CUDA_DISTRIBUTED_TYPES + [ + "MULTI_NPU", + "MULTI_MLU", + "MULTI_SDAA", + "MULTI_MUSA", + "MULTI_XPU", + "MULTI_CPU", + "MULTI_HPU", +] +SUPPORTED_PYTORCH_LAYERS_FOR_UPCASTING = ( + torch.nn.Conv1d, + torch.nn.Conv2d, + torch.nn.Conv3d, + torch.nn.ConvTranspose1d, + torch.nn.ConvTranspose2d, + torch.nn.ConvTranspose3d, + torch.nn.Linear, +) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/dataclasses.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/dataclasses.py new file mode 100644 index 0000000000000000000000000000000000000000..d7d3c7b19fb435a6c39eb91c4bc7cb613774cc0e --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/dataclasses.py @@ -0,0 +1,2926 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +General namespace and dataclass related classes +""" + +import argparse +import copy +import enum +import functools +import logging +import os +import warnings +from collections.abc import Iterable +from contextlib import contextmanager +from dataclasses import dataclass, field +from datetime import timedelta +from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, Union, get_args + +import torch + +from .constants import ( + BETA_CP_AVAILABLE_PYTORCH_VERSION, + BETA_TP_AVAILABLE_PYTORCH_VERSION, + BETA_TP_AVAILABLE_TRANSFORMERS_VERSION, + FSDP2_PYTORCH_VERSION, + FSDP_AUTO_WRAP_POLICY, + FSDP_BACKWARD_PREFETCH, + FSDP_SHARDING_STRATEGY, + MITA_PROFILING_AVAILABLE_PYTORCH_VERSION, + XPU_PROFILING_AVAILABLE_PYTORCH_VERSION, +) +from .environment import parse_flag_from_env, str_to_bool +from .imports import ( + is_cuda_available, + is_hpu_available, + is_mlu_available, + is_msamp_available, + is_musa_available, + is_npu_available, + is_transformer_engine_available, + is_xpu_available, +) +from .versions import compare_versions, is_torch_version + + +if TYPE_CHECKING: + # Mock imports for type checking + from torchao.float8 import Float8LinearConfig + + +logger = logging.getLogger(__name__) + + +class KwargsHandler: + """ + Internal mixin that implements a `to_kwargs()` method for a dataclass. + """ + + def to_dict(self): + return copy.deepcopy(self.__dict__) + + def to_kwargs(self): + """ + Returns a dictionary containing the attributes with values different from the default of this class. + """ + # import clear_environment here to avoid circular import problem + from .environment import clear_environment + + with clear_environment(): + default_dict = self.__class__().to_dict() + this_dict = self.to_dict() + return {k: v for k, v in this_dict.items() if default_dict[k] != v} + + +class EnumWithContains(enum.EnumMeta): + "A metaclass that adds the ability to check if `self` contains an item with the `in` operator" + + def __contains__(cls, item): + try: + cls(item) + except ValueError: + return False + return True + + +class BaseEnum(enum.Enum, metaclass=EnumWithContains): + "An enum class that can get the value of an item with `str(Enum.key)`" + + def __str__(self): + return self.value + + @classmethod + def list(cls): + "Method to list all the possible items in `cls`" + return list(map(str, cls)) + + +@dataclass +class AutocastKwargs(KwargsHandler): + """ + Use this object in your [`Accelerator`] to customize how `torch.autocast` behaves. Please refer to the + documentation of this [context manager](https://pytorch.org/docs/stable/amp.html#torch.autocast) for more + information on each argument. + + Example: + + ```python + from accelerate import Accelerator + from accelerate.utils import AutocastKwargs + + kwargs = AutocastKwargs(cache_enabled=True) + accelerator = Accelerator(kwargs_handlers=[kwargs]) + ``` + """ + + enabled: bool = True + cache_enabled: bool = None + + +class DDPCommunicationHookType(BaseEnum): + """ + Represents a type of communication hook used in DDP. + + Values: + + - **NO** -- no communication hook + - **FP16** -- DDP communication hook to compress the gradients in FP16 + - **BF16** -- DDP communication hook to compress the gradients in BF16 + - **POWER_SGD** -- DDP communication hook to use PowerSGD + - **BATCHED_POWER_SGD** -- DDP communication hook to use batched PowerSGD + """ + + NO = "no" + FP16 = "fp16" + BF16 = "bf16" + POWER_SGD = "power_sgd" + BATCHED_POWER_SGD = "batched_power_sgd" + + +@dataclass +class DistributedDataParallelKwargs(KwargsHandler): + """ + Use this object in your [`Accelerator`] to customize how your model is wrapped in a + `torch.nn.parallel.DistributedDataParallel`. Please refer to the documentation of this + [wrapper](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html) for more + information on each argument. + + + + `gradient_as_bucket_view` is only available in PyTorch 1.7.0 and later versions. + + `static_graph` is only available in PyTorch 1.11.0 and later versions. + + + + Example: + + ```python + from accelerate import Accelerator + from accelerate.utils import DistributedDataParallelKwargs + + kwargs = DistributedDataParallelKwargs(find_unused_parameters=True) + accelerator = Accelerator(kwargs_handlers=[kwargs]) + ``` + """ + + dim: int = 0 + broadcast_buffers: bool = True + bucket_cap_mb: int = 25 + find_unused_parameters: bool = False + check_reduction: bool = False + gradient_as_bucket_view: bool = False + static_graph: bool = False + + comm_hook: DDPCommunicationHookType = DDPCommunicationHookType.NO + comm_wrapper: Literal[ + DDPCommunicationHookType.NO, + DDPCommunicationHookType.FP16, + DDPCommunicationHookType.BF16, + ] = DDPCommunicationHookType.NO + comm_state_option: dict = field(default_factory=dict) + + def to_dict(self, ignore_keys=("comm_hook", "comm_wrapper", "comm_state_option")): + return {k: v for k, v in super().to_dict().items() if k not in ignore_keys} + + def register_comm_hook(self, model): + from torch.distributed.algorithms.ddp_comm_hooks import ( + default_hooks, + powerSGD_hook, + ) + + hook_map: dict[DDPCommunicationHookType, Callable] = { + DDPCommunicationHookType.FP16: default_hooks.fp16_compress_hook, + DDPCommunicationHookType.BF16: default_hooks.bf16_compress_hook, + DDPCommunicationHookType.POWER_SGD: powerSGD_hook.powerSGD_hook, + DDPCommunicationHookType.BATCHED_POWER_SGD: powerSGD_hook.batched_powerSGD_hook, + } + + wrapper_map: dict[DDPCommunicationHookType, Callable] = { + DDPCommunicationHookType.FP16: default_hooks.fp16_compress_wrapper, + DDPCommunicationHookType.BF16: default_hooks.bf16_compress_wrapper, + } + + hook: Optional[Callable] = hook_map.get(self.comm_hook) + wrapper: Optional[Callable] = wrapper_map.get(self.comm_wrapper) + + if hook and wrapper: + hook = wrapper(hook) + + if hook: + state = ( + powerSGD_hook.PowerSGDState(None, **self.comm_state_option) + if self.comm_hook + in ( + DDPCommunicationHookType.POWER_SGD, + DDPCommunicationHookType.BATCHED_POWER_SGD, + ) + else None + ) + model.register_comm_hook( + state=state, + hook=hook, + ) + + +@dataclass +class GradScalerKwargs(KwargsHandler): + """ + Use this object in your [`Accelerator`] to customize the behavior of mixed precision, specifically how the + `torch.amp.GradScaler` or `torch.cuda.amp.GradScaler` used is created. Please refer to the documentation of this + [scaler](https://pytorch.org/docs/stable/amp.html?highlight=gradscaler) for more information on each argument. + + + + `torch.cuda.amp.GradScaler` is only available in PyTorch 1.5.0 and later versions, and `torch.amp.GradScaler` is + only available in PyTorch 2.4.0 and later versions. + + + + Example: + + ```python + from accelerate import Accelerator + from accelerate.utils import GradScalerKwargs + + kwargs = GradScalerKwargs(backoff_factor=0.25) + accelerator = Accelerator(kwargs_handlers=[kwargs]) + ``` + """ + + init_scale: float = 65536.0 + growth_factor: float = 2.0 + backoff_factor: float = 0.5 + growth_interval: int = 2000 + enabled: bool = True + + +@dataclass +class InitProcessGroupKwargs(KwargsHandler): + """ + Use this object in your [`Accelerator`] to customize the initialization of the distributed processes. Please refer + to the documentation of this + [method](https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group) for more + information on each argument. + + Note: If `timeout` is set to `None`, the default will be based upon how `backend` is set. + + ```python + from datetime import timedelta + from accelerate import Accelerator + from accelerate.utils import InitProcessGroupKwargs + + kwargs = InitProcessGroupKwargs(timeout=timedelta(seconds=800)) + accelerator = Accelerator(kwargs_handlers=[kwargs]) + ``` + """ + + backend: Optional[str] = "nccl" + init_method: Optional[str] = None + timeout: Optional[timedelta] = None + + def __post_init__(self): + if self.timeout is None: + seconds = 1800 if self.backend != "nccl" else 600 + self.timeout = timedelta(seconds=seconds) + + +# Literals +Backend = Literal["MSAMP", "TE"] +OptLevel = Literal["O1", "O2"] +FP8Format = Literal["HYBRID", "E4M3", "E5M2"] +AmaxComputeAlgorithm = Literal["max", "most_recent"] + + +# FP8 training recipe kwargs +@dataclass +class AORecipeKwargs(KwargsHandler): + """ + Use this object in your [`Accelerator`] to customize the initialization of the recipe for FP8 mixed precision + training with `torchao` FP8. + + Args: + config (`torchao.float8.Float8LinearConfig`, *optional*, default to `None`): + The configuration for the FP8 training. In general, the default config should be sufficient. + module_filter_func (`Callable`, *optional*, default to `None`): + Optional function that must take in a module and layer name, and returns a boolean indicating whether the + module should be converted to FP8. Defaults to `accelerate.utils.ao.filter_linear_layers`. See it for an + example. + """ + + config: Optional["Float8LinearConfig"] = None + module_filter_func: Optional[Callable] = None + + +@dataclass +class TERecipeKwargs(KwargsHandler): + """ + Use this object in your [`Accelerator`] to customize the initialization of the recipe for FP8 mixed precision + training with `transformer-engine`. + + + + For more information on the args, please refer to the API + [documentation](https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/api/common.html). + + + + ```python + from accelerate import Accelerator + from accelerate.utils import TERecipeKwargs + + kwargs = TERecipeKwargs(fp8_format="HYBRID") + accelerator = Accelerator(mixed_precision="fp8", kwargs_handlers=[kwargs]) + ``` + + Args: + use_autocast_during_eval (`bool`, *optional*, default to `False`): + Whether to use FP8 autocast during eval mode. Generally better metrics are found when this is `False`. + margin (`int`, *optional*, default to 0): + The margin to use for the gradient scaling. + interval (`int`, *optional*, default to 1): + The interval to use for how often the scaling factor is recomputed. + fp8_format (`str`, *optional*, default to "HYBRID"): + The format to use for the FP8 recipe. Must be one of `HYBRID`, `E4M3` or `E5M2`. (Generally `HYBRID` for + training, `E4M3` or `E5M2` for evaluation) + amax_history_len (`int`, *optional*, default to 1024): + The length of the history to use for the scaling factor computation + amax_compute_algo (`str`, *optional*, default to "most_recent"): + The algorithm to use for the scaling factor computation. Must be one of `max` or `most_recent`. + override_linear_precision (`tuple` of three `bool`, *optional*, default to `(False, False, False)`): + Whether or not to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision. + """ + + use_autocast_during_eval: bool = None + margin: int = None + interval: int = None + fp8_format: FP8Format = None + amax_history_len: int = None + amax_compute_algo: AmaxComputeAlgorithm = None + override_linear_precision: tuple[bool, bool, bool] = None + + def __post_init__(self): + env_prefix = "ACCELERATE_FP8_" + if not is_transformer_engine_available(): + raise ImportError("TransformerEngine is not available. Please install it or use a different backend.") + if self.use_autocast_during_eval is None: + self.use_autocast_during_eval = parse_flag_from_env(env_prefix + "USE_AUTOCAST_DURING_EVAL") + if self.margin is None: + self.margin = int(os.environ.get(env_prefix + "MARGIN", 0)) + if self.interval is None: + self.interval = int(os.environ.get(env_prefix + "INTERVAL", 1)) + if self.fp8_format is None: + self.fp8_format = os.environ.get(env_prefix + "FORMAT", "HYBRID") + self.fp8_format = self.fp8_format.upper() + if self.fp8_format not in get_args(FP8Format): + raise ValueError(f"`fp8_format` must be one of {' or '.join(get_args(FP8Format))}.") + if self.amax_compute_algo is None: + self.amax_compute_algo = os.environ.get(env_prefix + "AMAX_COMPUTE_ALGO", "most_recent") + self.amax_compute_algo = self.amax_compute_algo.lower() + if self.amax_compute_algo not in get_args(AmaxComputeAlgorithm): + raise ValueError(f"`amax_compute_algo` must be one of {' or '.join(get_args(AmaxComputeAlgorithm))}") + if self.amax_history_len is None: + self.amax_history_len = int(os.environ.get(env_prefix + "AMAX_HISTORY_LEN", 1024)) + if self.override_linear_precision is None: + fprop = parse_flag_from_env(env_prefix + "OVERRIDE_FPROP") + dgrad = parse_flag_from_env(env_prefix + "OVERRIDE_DGRAD") + wgrad = parse_flag_from_env(env_prefix + "OVERRIDE_WGRAD") + self.override_linear_precision = (fprop, dgrad, wgrad) + + +@dataclass +class MSAMPRecipeKwargs(KwargsHandler): + """ + Use this object in your [`Accelerator`] to customize the initialization of the recipe for FP8 mixed precision + training with `ms-amp`. + """ + + opt_level: OptLevel = None + + def __post_init__(self): + env_prefix = "ACCELERATE_FP8_" + if self.opt_level is None: + self.opt_level = os.environ.get(env_prefix + "OPT_LEVEL", "O2") + if self.opt_level not in get_args(OptLevel): + raise ValueError(f"`opt_level` must be one of {' or '.join(get_args(OptLevel))}") + + +@dataclass +class FP8RecipeKwargs(TERecipeKwargs, MSAMPRecipeKwargs): + """ + Deprecated. Please use one of the proper FP8 recipe kwargs classes such as `TERecipeKwargs` or `MSAMPRecipeKwargs` + instead. + """ + + backend: Backend = None + + def __post_init__(self): + env_prefix = "ACCELERATE_FP8_" + warnings.warn( + "FP8RecipeKwargs is deprecated and will be removed in Accelerate v2.0.0. " + "Please use one of the proper FP8 recipe kwargs classes such as TERecipeKwargs or MSAMPRecipeKwargs instead.", + FutureWarning, + ) + default_backend = "msamp" if is_msamp_available() else "te" + if self.backend is None: + self.backend = os.environ.get(env_prefix + "BACKEND", default_backend) + self.backend = self.backend.upper() + if self.backend not in get_args(Backend): + raise ValueError("`backend` must be 'MSAMP' or 'TE' (TransformerEngine) to use `FP8RecipeKwargs`.") + super().__post_init__() + + +# Literal +ProfilerActivity = Literal["cpu", "xpu", "mtia", "cuda", "hpu"] + + +@dataclass +class ProfileKwargs(KwargsHandler): + """ + Use this object in your [`Accelerator`] to customize the initialization of the profiler. Please refer to the + documentation of this [context manager](https://pytorch.org/docs/stable/profiler.html#torch.profiler.profile) for + more information on each argument. + + + + `torch.profiler` is only available in PyTorch 1.8.1 and later versions. + + + + Example: + + ```python + from accelerate import Accelerator + from accelerate.utils import ProfileKwargs + + kwargs = ProfileKwargs(activities=["cpu", "cuda"]) + accelerator = Accelerator(kwargs_handlers=[kwargs]) + ``` + + Args: + activities (`List[str]`, *optional*, default to `None`): + The list of activity groups to use in profiling. Must be one of `"cpu"`, `"xpu"`, `"mtia"`, "hpu" or + `"cuda"`. + schedule_option (`Dict[str, int]`, *optional*, default to `None`): + The schedule option to use for the profiler. Available keys are `wait`, `warmup`, `active`, `repeat` and + `skip_first`. The profiler will skip the first `skip_first` steps, then wait for `wait` steps, then do the + warmup for the next `warmup` steps, then do the active recording for the next `active` steps and then + repeat the cycle starting with `wait` steps. The optional number of cycles is specified with the `repeat` + parameter, the zero value means that the cycles will continue until the profiling is finished. + on_trace_ready (`Callable`, *optional*, default to `None`): + Callable that is called at each step when schedule returns `ProfilerAction.RECORD_AND_SAVE` during the + profiling. + record_shapes (`bool`, *optional*, default to `False`): + Save information about operator’s input shapes. + profile_memory (`bool`, *optional*, default to `False`): + Track tensor memory allocation/deallocation + with_stack (`bool`, *optional*, default to `False`): + Record source information (file and line number) for the ops. + with_flops (`bool`, *optional*, default to `False`): + Use formula to estimate the FLOPS of specific operators + with_modules (`bool`, *optional*, default to `False`): + Record module hierarchy (including function names) corresponding to the callstack of the op. + output_trace_dir (`str`, *optional*, default to `None`): + Exports the collected trace in Chrome JSON format. Chrome use 'chrome://tracing' view json file. Defaults + to None, which means profiling does not store json files. + """ + + activities: Optional[list[ProfilerActivity]] = None + schedule_option: Optional[dict[str, int]] = None + on_trace_ready: Optional[Callable] = None + record_shapes: bool = False + profile_memory: bool = False + with_stack: bool = False + with_flops: bool = False + with_modules: bool = False + output_trace_dir: Optional[str] = None + + def _get_profiler_activity(self, activity: ProfilerActivity) -> torch.profiler.ProfilerActivity: + """Get the profiler activity from the string. + + Args: + activity (str): The profiler activity name. + + Returns: + torch.profiler.ProfilerActivity: The profiler activity. + """ + + profiler_activity_map: dict[str, torch.profiler.ProfilerActivity] = { + "cpu": torch.profiler.ProfilerActivity.CPU, + "cuda": torch.profiler.ProfilerActivity.CUDA, + } + + if is_hpu_available(): + profiler_activity_map["hpu"] = torch.profiler.ProfilerActivity.HPU + + if is_torch_version(">=", XPU_PROFILING_AVAILABLE_PYTORCH_VERSION): + if torch.xpu.is_available(): + profiler_activity_map["xpu"] = torch.profiler.ProfilerActivity.XPU + + if is_torch_version(">=", MITA_PROFILING_AVAILABLE_PYTORCH_VERSION): + if torch.mtia.is_available(): + profiler_activity_map["mtia"] = torch.profiler.ProfilerActivity.MTIA + + if activity not in profiler_activity_map: + raise ValueError(f"Invalid profiler activity: {activity}. Must be one of {list(profiler_activity_map)}.") + return profiler_activity_map[activity] + + def build(self) -> torch.profiler.profile: + """ + Build a profiler object with the current configuration. + + Returns: + torch.profiler.profile: The profiler object. + """ + activities: Optional[list[ProfilerActivity]] = None + if self.activities is not None: + activities = [self._get_profiler_activity(activity) for activity in self.activities] + schedule: Optional[torch.profiler.schedule] = None + if self.schedule_option is not None: + schedule = torch.profiler.schedule(**self.schedule_option) + + return torch.profiler.profile( + activities=activities, + schedule=schedule, + on_trace_ready=self.on_trace_ready, + record_shapes=self.record_shapes, + profile_memory=self.profile_memory, + with_stack=self.with_stack, + with_flops=self.with_flops, + with_modules=self.with_modules, + ) + + +class DistributedType(str, enum.Enum): + """ + Represents a type of distributed environment. + + Values: + + - **NO** -- Not a distributed environment, just a single process. + - **MULTI_CPU** -- Distributed on multiple CPU nodes. + - **MULTI_GPU** -- Distributed on multiple GPUs. + - **MULTI_MLU** -- Distributed on multiple MLUs. + - **MULTI_SDAA** -- Distributed on multiple SDAAs. + - **MULTI_MUSA** -- Distributed on multiple MUSAs. + - **MULTI_NPU** -- Distributed on multiple NPUs. + - **MULTI_XPU** -- Distributed on multiple XPUs. + - **MULTI_HPU** -- Distributed on multiple HPUs. + - **DEEPSPEED** -- Using DeepSpeed. + - **XLA** -- Using TorchXLA. + """ + + # Subclassing str as well as Enum allows the `DistributedType` to be JSON-serializable out of the box. + NO = "NO" + MULTI_CPU = "MULTI_CPU" + MULTI_GPU = "MULTI_GPU" + MULTI_NPU = "MULTI_NPU" + MULTI_MLU = "MULTI_MLU" + MULTI_SDAA = "MULTI_SDAA" + MULTI_MUSA = "MULTI_MUSA" + MULTI_XPU = "MULTI_XPU" + DEEPSPEED = "DEEPSPEED" + FSDP = "FSDP" + XLA = "XLA" + MEGATRON_LM = "MEGATRON_LM" + MULTI_HPU = "MULTI_HPU" + + +class SageMakerDistributedType(str, enum.Enum): + """ + Represents a type of distributed environment. + + Values: + + - **NO** -- Not a distributed environment, just a single process. + - **DATA_PARALLEL** -- using sagemaker distributed data parallelism. + - **MODEL_PARALLEL** -- using sagemaker distributed model parallelism. + """ + + # Subclassing str as well as Enum allows the `SageMakerDistributedType` to be JSON-serializable out of the box. + NO = "NO" + DATA_PARALLEL = "DATA_PARALLEL" + MODEL_PARALLEL = "MODEL_PARALLEL" + + +class FP8BackendType(str, enum.Enum): + """ + Represents the backend used for FP8. + + Values: + + - **TE** -- using TransformerEngine. + - **MSAMP** -- using msamp. + """ + + # Subclassing str as well as Enum allows the `FP8BackendType` to be JSON-serializable out of the box. + NO = "NO" + TE = "TE" + MSAMP = "MSAMP" + AO = "AO" + + +class ComputeEnvironment(str, enum.Enum): + """ + Represents a type of the compute environment. + + Values: + + - **LOCAL_MACHINE** -- private/custom cluster hardware. + - **AMAZON_SAGEMAKER** -- Amazon SageMaker as compute environment. + """ + + # Subclassing str as well as Enum allows the `ComputeEnvironment` to be JSON-serializable out of the box. + LOCAL_MACHINE = "LOCAL_MACHINE" + AMAZON_SAGEMAKER = "AMAZON_SAGEMAKER" + + +class DynamoBackend(str, BaseEnum): + """ + Represents a dynamo backend (see https://pytorch.org/docs/stable/torch.compiler.html). + + Values: + + - **NO** -- Do not use torch dynamo. + - **EAGER** -- Uses PyTorch to run the extracted GraphModule. This is quite useful in debugging TorchDynamo + issues. + - **AOT_EAGER** -- Uses AotAutograd with no compiler, i.e, just using PyTorch eager for the AotAutograd's + extracted forward and backward graphs. This is useful for debugging, and unlikely to give speedups. + - **INDUCTOR** -- Uses TorchInductor backend with AotAutograd and cudagraphs by leveraging codegened Triton + kernels. [Read + more](https://dev-discuss.pytorch.org/t/torchinductor-a-pytorch-native-compiler-with-define-by-run-ir-and-symbolic-shapes/747) + - **AOT_TS_NVFUSER** -- nvFuser with AotAutograd/TorchScript. [Read + more](https://dev-discuss.pytorch.org/t/tracing-with-primitives-update-1-nvfuser-and-its-primitives/593) + - **NVPRIMS_NVFUSER** -- nvFuser with PrimTorch. [Read + more](https://dev-discuss.pytorch.org/t/tracing-with-primitives-update-1-nvfuser-and-its-primitives/593) + - **CUDAGRAPHS** -- cudagraphs with AotAutograd. [Read more](https://github.com/pytorch/torchdynamo/pull/757) + - **OFI** -- Uses Torchscript optimize_for_inference. Inference only. [Read + more](https://pytorch.org/docs/stable/generated/torch.jit.optimize_for_inference.html) + - **FX2TRT** -- Uses Nvidia TensorRT for inference optimizations. Inference only. [Read + more](https://github.com/pytorch/TensorRT/blob/master/docsrc/tutorials/getting_started_with_fx_path.rst) + - **ONNXRT** -- Uses ONNXRT for inference on CPU/GPU. Inference only. [Read more](https://onnxruntime.ai/) + - **TENSORRT** -- Uses ONNXRT to run TensorRT for inference optimizations. [Read + more](https://github.com/onnx/onnx-tensorrt) + - **AOT_TORCHXLA_TRACE_ONCE** -- Uses Pytorch/XLA with TorchDynamo optimization, for training. [Read + more](https://github.com/pytorch/xla/blob/r2.0/docs/dynamo.md) + - **TORCHXLA_TRACE_ONCE** -- Uses Pytorch/XLA with TorchDynamo optimization, for inference. [Read + more](https://github.com/pytorch/xla/blob/r2.0/docs/dynamo.md) + - **IPEX** -- Uses IPEX for inference on CPU. Inference only. [Read + more](https://github.com/intel/intel-extension-for-pytorch). + - **TVM** -- Uses Apach TVM for inference optimizations. [Read more](https://tvm.apache.org/) + - **HPU_BACKEND** -- Uses HPU backend for inference optimizations. + + """ + + # Subclassing str as well as Enum allows the `SageMakerDistributedType` to be JSON-serializable out of the box. + NO = "NO" + EAGER = "EAGER" + AOT_EAGER = "AOT_EAGER" + INDUCTOR = "INDUCTOR" + AOT_TS_NVFUSER = "AOT_TS_NVFUSER" + NVPRIMS_NVFUSER = "NVPRIMS_NVFUSER" + CUDAGRAPHS = "CUDAGRAPHS" + OFI = "OFI" + FX2TRT = "FX2TRT" + ONNXRT = "ONNXRT" + TENSORRT = "TENSORRT" + AOT_TORCHXLA_TRACE_ONCE = "AOT_TORCHXLA_TRACE_ONCE" + TORCHXLA_TRACE_ONCE = "TORCHXLA_TRACE_ONCE" + IPEX = "IPEX" + TVM = "TVM" + HPU_BACKEND = "HPU_BACKEND" + + +class LoggerType(BaseEnum): + """Represents a type of supported experiment tracker + + Values: + + - **ALL** -- all available trackers in the environment that are supported + - **TENSORBOARD** -- TensorBoard as an experiment tracker + - **WANDB** -- wandb as an experiment tracker + - **TRACKIO** -- trackio as an experiment tracker + - **COMETML** -- comet_ml as an experiment tracker + - **MLFLOW** -- mlflow as an experiment tracker + - **CLEARML** -- clearml as an experiment tracker + - **DVCLIVE** -- dvclive as an experiment tracker + - **SWANLAB** -- swanlab as an experiment tracker + """ + + ALL = "all" + AIM = "aim" + TENSORBOARD = "tensorboard" + WANDB = "wandb" + TRACKIO = "trackio" + COMETML = "comet_ml" + MLFLOW = "mlflow" + CLEARML = "clearml" + DVCLIVE = "dvclive" + SWANLAB = "swanlab" + + +class PrecisionType(str, BaseEnum): + """Represents a type of precision used on floating point values + + Values: + + - **NO** -- using full precision (FP32) + - **FP16** -- using half precision + - **BF16** -- using brain floating point precision + """ + + NO = "no" + FP8 = "fp8" + FP16 = "fp16" + BF16 = "bf16" + + +class RNGType(BaseEnum): + TORCH = "torch" + CUDA = "cuda" + MLU = "mlu" + SDAA = "sdaa" + MUSA = "musa" + NPU = "npu" + XLA = "xla" + XPU = "xpu" + HPU = "hpu" + GENERATOR = "generator" + + +class CustomDtype(enum.Enum): + r""" + An enum that contains multiple custom dtypes that can be used for `infer_auto_device_map`. + """ + + FP8 = "fp8" + INT4 = "int4" + INT2 = "int2" + + +# data classes + + +@dataclass +class TensorInformation: + shape: torch.Size + dtype: torch.dtype + + +@dataclass +class DataLoaderConfiguration: + """ + Configuration for dataloader-related items when calling `accelerator.prepare`. + + Args: + split_batches (`bool`, defaults to `False`): + Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. If + `True`, the actual batch size used will be the same on any kind of distributed processes, but it must be a + round multiple of `num_processes` you are using. If `False`, actual batch size used will be the one set in + your script multiplied by the number of processes. + dispatch_batches (`bool`, defaults to `None`): + If set to `True`, the dataloader prepared by the Accelerator is only iterated through on the main process + and then the batches are split and broadcast to each process. Will default to `True` for `DataLoader` whose + underlying dataset is an `IterableDataset`, `False` otherwise. + even_batches (`bool`, defaults to `True`): + If set to `True`, in cases where the total batch size across all processes does not exactly divide the + dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among + all workers. + use_seedable_sampler (`bool`, defaults to `False`): + Whether or not use a fully seedable random sampler ([`data_loader.SeedableRandomSampler`]). Ensures + training results are fully reproducable using a different sampling technique. While seed-to-seed results + may differ, on average the differences are neglible when using multiple different seeds to compare. Should + also be ran with [`~utils.set_seed`] for the best results. + data_seed (`int`, defaults to `None`): + The seed to use for the underlying generator when using `use_seedable_sampler`. If `None`, the generator + will use the current default seed from torch. + non_blocking (`bool`, defaults to `False`): + If set to `True`, the dataloader prepared by the Accelerator will utilize non-blocking host-to-device + transfers, allowing for better overlap between dataloader communication and computation. Recommended that + the prepared dataloader has `pin_memory` set to `True` to work properly. + use_stateful_dataloader (`bool`, defaults to `False`): + If set to `True`, the dataloader prepared by the Accelerator will be backed by + [torchdata.StatefulDataLoader](https://github.com/pytorch/data/tree/main/torchdata/stateful_dataloader). + This requires `torchdata` version 0.8.0 or higher that supports StatefulDataLoader to be installed. + """ + + split_batches: bool = field( + default=False, + metadata={ + "help": "Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. If" + " `True` the actual batch size used will be the same on any kind of distributed processes, but it must be a" + " round multiple of the `num_processes` you are using. If `False`, actual batch size used will be the one set" + " in your script multiplied by the number of processes." + }, + ) + dispatch_batches: bool = field( + default=None, + metadata={ + "help": "If set to `True`, the dataloader prepared by the Accelerator is only iterated through on the main process" + " and then the batches are split and broadcast to each process. Will default to `True` for `DataLoader` whose" + " underlying dataset is an `IterableDataset`, `False` otherwise." + }, + ) + even_batches: bool = field( + default=True, + metadata={ + "help": "If set to `True`, in cases where the total batch size across all processes does not exactly divide the" + " dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among" + " all workers." + }, + ) + use_seedable_sampler: bool = field( + default=False, + metadata={ + "help": "Whether or not use a fully seedable random sampler ([`data_loader.SeedableRandomSampler`])." + "Ensures training results are fully reproducable using a different sampling technique. " + "While seed-to-seed results may differ, on average the differences are neglible when using" + "multiple different seeds to compare. Should also be ran with [`~utils.set_seed`] for the best results." + }, + ) + data_seed: int = field( + default=None, + metadata={ + "help": "The seed to use for the underlying generator when using `use_seedable_sampler`. If `None`, the generator" + " will use the current default seed from torch." + }, + ) + non_blocking: bool = field( + default=False, + metadata={ + "help": "If set to `True`, the dataloader prepared by the Accelerator will utilize non-blocking host-to-device" + " transfers, allowing for better overlap between dataloader communication and computation. Recommended that the" + " prepared dataloader has `pin_memory` set to `True` to work properly." + }, + ) + use_stateful_dataloader: bool = field( + default=False, + metadata={ + "help": "If set to `True`, the dataloader prepared by the Accelerator will be backed by " + "[torchdata.StatefulDataLoader](https://github.com/pytorch/data/tree/main/torchdata/stateful_dataloader). This requires `torchdata` version 0.8.0 or higher that supports StatefulDataLoader to be installed." + }, + ) + + +@dataclass +class ProjectConfiguration: + """ + Configuration for the Accelerator object based on inner-project needs. + + Args: + project_dir (`str`, defaults to `None`): + A path to a directory for storing data. + logging_dir (`str`, defaults to `None`): + A path to a directory for storing logs of locally-compatible loggers. If None, defaults to `project_dir`. + automatic_checkpoint_naming (`bool`, defaults to `False`): + Whether saved states should be automatically iteratively named. + total_limit (`int`, defaults to `None`): + The maximum number of total saved states to keep. + iteration (`int`, defaults to `0`): + The current save iteration. + save_on_each_node (`bool`, defaults to `False`): + When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on + the main one. + """ + + project_dir: str = field(default=None, metadata={"help": "A path to a directory for storing data."}) + logging_dir: str = field( + default=None, + metadata={ + "help": "A path to a directory for storing logs of locally-compatible loggers. If None, defaults to `project_dir`." + }, + ) + automatic_checkpoint_naming: bool = field( + default=False, + metadata={"help": "Whether saved states should be automatically iteratively named."}, + ) + + total_limit: int = field( + default=None, + metadata={"help": "The maximum number of total saved states to keep."}, + ) + + iteration: int = field( + default=0, + metadata={"help": "The current save iteration."}, + ) + + save_on_each_node: bool = field( + default=False, + metadata={ + "help": ( + "When doing multi-node distributed training, whether to save models and checkpoints on each node, or" + " only on the main one" + ) + }, + ) + + def set_directories(self, project_dir: str = None): + "Sets `self.project_dir` and `self.logging_dir` to the appropriate values." + self.project_dir = project_dir + if self.logging_dir is None: + self.logging_dir = project_dir + + def __post_init__(self): + self.set_directories(self.project_dir) + + +@dataclass +class GradientAccumulationPlugin(KwargsHandler): + """ + A plugin to configure gradient accumulation behavior. You can only pass one of `gradient_accumulation_plugin` or + `gradient_accumulation_steps` to [`Accelerator`]. Passing both raises an error. + + Parameters: + num_steps (`int`): + The number of steps to accumulate gradients for. + adjust_scheduler (`bool`, *optional*, defaults to `True`): + Whether to adjust the scheduler steps to account for the number of steps being accumulated. Should be + `True` if the used scheduler was not adjusted for gradient accumulation. + sync_with_dataloader (`bool`, *optional*, defaults to `True`): + Whether to synchronize setting the gradients when at the end of the dataloader. + sync_each_batch (`bool`, *optional*): + Whether to synchronize setting the gradients at each data batch. Seting to `True` may reduce memory + requirements when using gradient accumulation with distributed training, at expense of speed. + + Example: + + ```python + from accelerate.utils import GradientAccumulationPlugin + + gradient_accumulation_plugin = GradientAccumulationPlugin(num_steps=2) + accelerator = Accelerator(gradient_accumulation_plugin=gradient_accumulation_plugin) + ``` + """ + + num_steps: int = field( + default=None, + metadata={"help": "The number of steps to accumulate gradients for."}, + ) + adjust_scheduler: bool = field( + default=True, + metadata={ + "help": "Whether to adjust the scheduler steps to account for the number of steps being accumulated. Should be `True` if the used scheduler was not adjusted for gradient accumulation." + }, + ) + sync_with_dataloader: bool = field( + default=True, + metadata={ + "help": "Whether to synchronize setting the gradients when at the end of the dataloader. Should only be set to `False` if you know what you're doing." + }, + ) + sync_each_batch: bool = field( + default=False, + metadata={ + "help": "Whether to synchronize setting the gradients at each data batch. Setting to `True` may reduce memory requirements when using gradient accumulation with distributed training, at expense of speed." + }, + ) + + +@dataclass +class TorchDynamoPlugin(KwargsHandler): + """ + This plugin is used to compile a model with PyTorch 2.0 + + Args: + backend (`DynamoBackend`, defaults to `None`): + A valid Dynamo backend. See https://pytorch.org/docs/stable/torch.compiler.html for more details. + mode (`str`, defaults to `None`): + Possible options are 'default', 'reduce-overhead' or 'max-autotune'. + fullgraph (`bool`, defaults to `None`): + Whether it is ok to break model into several subgraphs. + dynamic (`bool`, defaults to `None`): + Whether to use dynamic shape for tracing. + options (`Any`, defaults to `None`): + A dictionary of options to pass to the backend. + disable (`bool`, defaults to `False`): + Turn torch.compile() into a no-op for testing + use_regional_compilation (`bool`, defaults to `None`): + Use it to reduce the cold start compilation time of torch.compile() by targeting repeated blocks of the + same class and compiling them sequentially to hit the compiler's cache. For example, in `GPT2LMHeadModel`, + the repeated block/class is `GPT2Block`, and can be accessed as `model.transformer.h[0]`. The rest of the + model (e.g model.lm_head) is compiled separately. + """ + + backend: DynamoBackend = field( + default=None, + metadata={"help": f"Possible options are {[b.value.lower() for b in DynamoBackend]}"}, + ) + mode: str = field( + default=None, + metadata={"help": "Possible options are 'default', 'reduce-overhead' or 'max-autotune'"}, + ) + fullgraph: bool = field( + default=None, + metadata={"help": "Whether it is ok to break model into several subgraphs"}, + ) + dynamic: bool = field(default=None, metadata={"help": "Whether to use dynamic shape for tracing"}) + options: Any = field( + default=None, + metadata={"help": "A dictionary of options to pass to the backend."}, + ) + disable: bool = field( + default=False, + metadata={"help": "Turn torch.compile() into a no-op for testing"}, + ) + + use_regional_compilation: bool = field( + default=None, + metadata={ + "help": ( + # https://pytorch.org/tutorials/recipes/regional_compilation.html + "Use it to reduce the cold start compilation time of torch.compile() by targeting repeated " + "blocks of the same class and compiling them sequentially to hit the compiler's cache. For " + "example, in `GPT2LMHeadModel`, the repeated block/class is `GPT2Block`, and can be accessed " + "as `model.transformer.h[0]`. The rest of the model (e.g model.lm_head) is compiled separately." + ) + }, + ) + + def __post_init__(self): + prefix = "ACCELERATE_DYNAMO_" + if self.backend is None: + self.backend = os.environ.get(prefix + "BACKEND", "no") + self.backend = DynamoBackend(self.backend.upper()) + + if self.mode is None: + self.mode = os.environ.get(prefix + "MODE", "default") + if self.fullgraph is None: + self.fullgraph = str_to_bool(os.environ.get(prefix + "USE_FULLGRAPH", "False")) == 1 + if self.use_regional_compilation is None: + self.use_regional_compilation = ( + str_to_bool(os.environ.get(prefix + "USE_REGIONAL_COMPILATION", "False")) == 1 + ) + + if self.dynamic is None and os.environ.get(prefix + "USE_DYNAMIC", None) is not None: + self.dynamic = str_to_bool(os.environ.get(prefix + "USE_DYNAMIC", "False")) == 1 + + def to_dict(self): + dynamo_config = copy.deepcopy(self.__dict__) + dynamo_config["backend"] = dynamo_config["backend"].value.lower() + return dynamo_config + + def to_kwargs(self): + kwargs = super().to_kwargs() + kwargs.pop("use_regional_compilation", None) + return kwargs + + +@dataclass +class DeepSpeedPlugin: + """ + This plugin is used to integrate DeepSpeed. + + Args: + hf_ds_config (`Any`, defaults to `None`): + Path to DeepSpeed config file or dict or an object of class `accelerate.utils.deepspeed.HfDeepSpeedConfig`. + gradient_accumulation_steps (`int`, defaults to `None`): + Number of steps to accumulate gradients before updating optimizer states. If not set, will use the value + from the `Accelerator` directly. + gradient_clipping (`float`, defaults to `None`): + Enable gradient clipping with value. + zero_stage (`int`, defaults to `None`): + Possible options are 0, 1, 2, 3. Default will be taken from environment variable. + is_train_batch_min (`bool`, defaults to `True`): + If both train & eval dataloaders are specified, this will decide the `train_batch_size`. + offload_optimizer_device (`str`, defaults to `None`): + Possible options are none|cpu|nvme. Only applicable with ZeRO Stages 2 and 3. + offload_param_device (`str`, defaults to `None`): + Possible options are none|cpu|nvme. Only applicable with ZeRO Stage 3. + offload_optimizer_nvme_path (`str`, defaults to `None`): + Possible options are /nvme|/local_nvme. Only applicable with ZeRO Stage 3. + offload_param_nvme_path (`str`, defaults to `None`): + Possible options are /nvme|/local_nvme. Only applicable with ZeRO Stage 3. + zero3_init_flag (`bool`, defaults to `None`): + Flag to indicate whether to save 16-bit model. Only applicable with ZeRO Stage-3. + zero3_save_16bit_model (`bool`, defaults to `None`): + Flag to indicate whether to save 16-bit model. Only applicable with ZeRO Stage-3. + transformer_moe_cls_names (`str`, defaults to `None`): + Comma-separated list of Transformers MoE layer class names (case-sensitive). For example, + `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention`, `JetMoEBlock`, etc. + enable_msamp (`bool`, defaults to `None`): + Flag to indicate whether to enable MS-AMP backend for FP8 training. + msasmp_opt_level (`Optional[Literal["O1", "O2"]]`, defaults to `None`): + Optimization level for MS-AMP (defaults to 'O1'). Only applicable if `enable_msamp` is True. Should be one + of ['O1' or 'O2']. + """ + + hf_ds_config: Any = field( + default=None, + metadata={ + "help": "path to DeepSpeed config file or dict or an object of class `accelerate.utils.deepspeed.HfDeepSpeedConfig`." + }, + ) + gradient_accumulation_steps: int = field( + default=None, + metadata={ + "help": "Number of steps to accumulate gradients before updating optimizer states. If not set, will use the value from the `Accelerator` directly." + }, + ) + gradient_clipping: float = field(default=None, metadata={"help": "Enable gradient clipping with value"}) + zero_stage: int = field( + default=None, + metadata={"help": "Possible options are 0,1,2,3; Default will be taken from environment variable"}, + ) + is_train_batch_min: bool = field( + default=True, + metadata={"help": "If both train & eval dataloaders are specified, this will decide the train_batch_size"}, + ) + offload_optimizer_device: str = field( + default=None, + metadata={"help": "Possible options are none|cpu|nvme. Only applicable with ZeRO Stages 2 and 3."}, + ) + offload_param_device: str = field( + default=None, + metadata={"help": "Possible options are none|cpu|nvme. Only applicable with ZeRO Stage 3."}, + ) + offload_optimizer_nvme_path: str = field( + default=None, + metadata={"help": "Possible options are /nvme|/local_nvme. Only applicable with ZeRO Stage 3."}, + ) + offload_param_nvme_path: str = field( + default=None, + metadata={"help": "Possible options are /nvme|/local_nvme. Only applicable with ZeRO Stage 3."}, + ) + zero3_init_flag: bool = field( + default=None, + metadata={ + "help": "Flag to indicate whether to enable `deepspeed.zero.Init` for constructing massive models." + "Only applicable with ZeRO Stage-3." + }, + ) + zero3_save_16bit_model: bool = field( + default=None, + metadata={"help": "Flag to indicate whether to save 16-bit model. Only applicable with ZeRO Stage-3."}, + ) + transformer_moe_cls_names: str = field( + default=None, + metadata={ + "help": "comma-separated list of transformers MoE layer class names (case-sensitive), e.g : " + " `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ..." + }, + ) + enable_msamp: bool = field( + default=None, + metadata={"help": "Flag to indicate whether to enable MS-AMP backend for FP8 training."}, + ) + msamp_opt_level: Optional[Literal["O1", "O2"]] = field( + default=None, + metadata={ + "help": "Optimization level for MS-AMP (defaults to 'O1'). Only applicable if `enable_msamp` is True. Should be one of ['O1' or 'O2']." + }, + ) + + def __post_init__(self): + from .deepspeed import HfDeepSpeedConfig + + if self.gradient_accumulation_steps is None: + gas = os.environ.get("ACCELERATE_GRADIENT_ACCUMULATION_STEPS", "auto") + self.gradient_accumulation_steps = int(gas) if gas.isdigit() else gas + + if self.gradient_clipping is None: + gradient_clipping = os.environ.get("ACCELERATE_GRADIENT_CLIPPING", "auto") + self.gradient_clipping = gradient_clipping if gradient_clipping == "auto" else float(gradient_clipping) + + if self.zero_stage is None: + self.zero_stage = int(os.environ.get("ACCELERATE_DEEPSPEED_ZERO_STAGE", 2)) + + if self.offload_optimizer_device is None: + self.offload_optimizer_device = os.environ.get("ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_DEVICE", "none") + + if self.offload_param_device is None: + self.offload_param_device = os.environ.get("ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_DEVICE", "none") + + if self.offload_optimizer_nvme_path is None: + self.offload_optimizer_nvme_path = os.environ.get( + "ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_NVME_PATH", "none" + ) + + if self.offload_param_nvme_path is None: + self.offload_param_nvme_path = os.environ.get("ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_NVME_PATH", "none") + + if self.zero3_save_16bit_model is None: + self.zero3_save_16bit_model = ( + os.environ.get("ACCELERATE_DEEPSPEED_ZERO3_SAVE_16BIT_MODEL", "false").lower() == "true" + ) + if self.enable_msamp is None: + self.enable_msamp = os.environ.get("ACCELERATE_FP8_BACKEND", None) == "MSAMP" + + if self.msamp_opt_level is None: + self.msamp_opt_level = os.environ.get("ACCELERATE_FP8_OPT_LEVEL", "O1") + + if self.hf_ds_config is None: + self.hf_ds_config = os.environ.get("ACCELERATE_DEEPSPEED_CONFIG_FILE", "none") + if ( + isinstance(self.hf_ds_config, dict) + or (isinstance(self.hf_ds_config, str) and self.hf_ds_config != "none") + or isinstance(self.hf_ds_config, HfDeepSpeedConfig) + ): + if not isinstance(self.hf_ds_config, HfDeepSpeedConfig): + self.hf_ds_config = HfDeepSpeedConfig(self.hf_ds_config) + if "gradient_accumulation_steps" not in self.hf_ds_config.config: + self.hf_ds_config.config["gradient_accumulation_steps"] = 1 + if "zero_optimization" not in self.hf_ds_config.config: + raise ValueError("Please specify the ZeRO optimization config in the DeepSpeed config.") + + self._deepspeed_config_checks() + plugin_to_config_mapping = { + "gradient_accumulation_steps": "gradient_accumulation_steps", + "gradient_clipping": "gradient_clipping", + "zero_stage": "zero_optimization.stage", + "offload_optimizer_device": "zero_optimization.offload_optimizer.device", + "offload_param_device": "zero_optimization.offload_param.device", + "offload_param_nvme_path": "zero_optimization.offload_param.nvme_path", + "offload_optimizer_nvme_path": "zero_optimization.offload_optimizer.nvme_path", + "zero3_save_16bit_model": "zero_optimization.stage3_gather_16bit_weights_on_model_save", + } + kwargs = {v: getattr(self, k) for k, v in plugin_to_config_mapping.items() if getattr(self, k) is not None} + for key in kwargs.keys(): + self.fill_match(key, **kwargs, must_match=False) + self.hf_ds_config.set_stage_and_offload() + + # filling the missing values in the class attributes from the DeepSpeed config + # when using the DeepSpeed config file. + for key, value in plugin_to_config_mapping.items(): + config_value = self.hf_ds_config.get_value(value) + if config_value is not None and config_value != "auto": + setattr(self, key, config_value) + else: + config = { + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "gradient_accumulation_steps": self.gradient_accumulation_steps, + "zero_optimization": { + "stage": self.zero_stage, + "offload_optimizer": { + "device": self.offload_optimizer_device, + "nvme_path": ( + self.offload_optimizer_nvme_path if self.offload_optimizer_device == "nvme" else None + ), + }, + "offload_param": { + "device": self.offload_param_device, + "nvme_path": (self.offload_param_nvme_path if self.offload_param_device == "nvme" else None), + }, + "stage3_gather_16bit_weights_on_model_save": self.zero3_save_16bit_model, + }, + } + if self.gradient_clipping: + config["gradient_clipping"] = self.gradient_clipping + self.hf_ds_config = HfDeepSpeedConfig(config) + + self.deepspeed_config = self.hf_ds_config.config + self.deepspeed_config["steps_per_print"] = float("inf") # this will stop deepspeed from logging @ stdout + if self.zero3_init_flag is None: + self.zero3_init_flag = ( + str_to_bool( + os.environ.get( + "ACCELERATE_DEEPSPEED_ZERO3_INIT", + str(self.hf_ds_config.is_zero3()), + ) + ) + == 1 + ) + if self.zero3_init_flag and not self.hf_ds_config.is_zero3(): + warnings.warn("DeepSpeed Zero3 Init flag is only applicable for ZeRO Stage 3. Setting it to False.") + self.zero3_init_flag = False + # NOTE: Set to False by default, will be set to `True` automatically if it's the first plugin passed + # to the `Accelerator`'s `deepspeed_plugin` param, *or* `AcceleratorState().enable_deepspeed_plugin(plugin_key)` is manually called + self._set_selected(False) + + # Ignore if it's already set + if self.enable_msamp and "msamp" not in self.deepspeed_config: + if self.zero_stage == 3: + raise NotImplementedError( + "MS-AMP is not supported for ZeRO Stage 3. Please use ZeRO Stage 0, 1, or 2 instead." + ) + if self.msamp_opt_level not in ["O1", "O2"]: + raise ValueError("Invalid optimization level for MS-AMP. Please use one of ['O1' or'O2'].") + self.deepspeed_config["msamp"] = { + "enabled": True, + "opt_level": self.msamp_opt_level, + } + + def fill_match(self, ds_key_long, mismatches=None, must_match=True, **kwargs): + mismatches = [] if mismatches is None else mismatches + config, ds_key = self.hf_ds_config.find_config_node(ds_key_long) + if config is None: + return + + if config.get(ds_key) == "auto": + if ds_key_long in kwargs: + config[ds_key] = kwargs[ds_key_long] + return + else: + raise ValueError( + f"`{ds_key_long}` not found in kwargs. " + f"Please specify `{ds_key_long}` without `auto` (set to correct value) in the DeepSpeed config file or " + "pass it in kwargs." + ) + + if not must_match: + return + + ds_val = config.get(ds_key) + if ds_val is not None and ds_key_long in kwargs: + if ds_val != kwargs[ds_key_long]: + mismatches.append(f"- ds {ds_key_long}={ds_val} vs arg {ds_key_long}={kwargs[ds_key_long]}") + + def is_auto(self, ds_key_long): + val = self.hf_ds_config.get_value(ds_key_long) + if val is None: + return False + else: + return val == "auto" + + def get_value(self, ds_key_long, default=None): + return self.hf_ds_config.get_value(ds_key_long, default) + + def deepspeed_config_process(self, prefix="", mismatches=None, config=None, must_match=True, **kwargs): + """Process the DeepSpeed config with the values from the kwargs.""" + mismatches = [] if mismatches is None else mismatches + if config is None: + config = self.deepspeed_config + for key, value in config.items(): + if isinstance(value, dict): + self.deepspeed_config_process( + prefix=prefix + key + ".", + mismatches=mismatches, + config=value, + must_match=must_match, + **kwargs, + ) + else: + self.fill_match(prefix + key, mismatches, must_match=must_match, **kwargs) + if len(mismatches) > 0 and prefix == "": + mismatches_msg = "\n".join(mismatches) + raise ValueError( + "Please correct the following DeepSpeed config values that mismatch kwargs " + f" values:\n{mismatches_msg}\nThe easiest method is to set these DeepSpeed config values to 'auto'." + ) + + def set_mixed_precision(self, mixed_precision): + ds_config = self.deepspeed_config + kwargs = { + "fp16.enabled": mixed_precision == "fp16", + # When training in fp8, we still rely on bf16 autocast for the core mixed precision + "bf16.enabled": mixed_precision in ("bf16", "fp8"), + } + if mixed_precision == "fp16": + if "fp16" not in ds_config: + ds_config["fp16"] = {"enabled": True, "auto_cast": True} + elif mixed_precision in ("bf16", "fp8"): + if "bf16" not in ds_config: + ds_config["bf16"] = {"enabled": True} + + if mixed_precision == "fp8" and self.enable_msamp: + if "msamp" not in ds_config: + ds_config["msamp"] = { + "enabled": True, + "opt_level": self.msamp_opt_level, + } + + if mixed_precision != "no": + diff_dtype = "bf16" if mixed_precision == "fp16" else "fp16" + if str(ds_config.get(diff_dtype, {}).get("enabled", "False")).lower() == "true": + raise ValueError( + f"`--mixed_precision` arg cannot be set to `{mixed_precision}` when `{diff_dtype}` is set in the DeepSpeed config file." + ) + for dtype in ["fp16", "bf16"]: + if dtype not in ds_config: + ds_config[dtype] = {"enabled": False} + self.fill_match("fp16.enabled", must_match=False, **kwargs) + self.fill_match("bf16.enabled", must_match=False, **kwargs) + + def set_deepspeed_weakref(self): + from .imports import is_transformers_available + + ds_config = copy.deepcopy(self.deepspeed_config) + if self.zero3_init_flag: + if not is_transformers_available(): + raise Exception( + "When `zero3_init_flag` is set, it requires Transformers to be installed. " + "Please run `pip install transformers`." + ) + if "gradient_accumulation_steps" not in ds_config or ds_config["gradient_accumulation_steps"] == "auto": + ds_config["gradient_accumulation_steps"] = 1 + if "train_micro_batch_size_per_gpu" not in ds_config or ds_config["train_micro_batch_size_per_gpu"] == "auto": + ds_config["train_micro_batch_size_per_gpu"] = 1 + if ds_config.get("train_batch_size", None) == "auto": + del ds_config["train_batch_size"] + + if compare_versions("transformers", "<", "4.46"): + from transformers.deepspeed import ( + HfDeepSpeedConfig, + unset_hf_deepspeed_config, + ) + else: + from transformers.integrations import ( + HfDeepSpeedConfig, + unset_hf_deepspeed_config, + ) + + unset_hf_deepspeed_config() + self.dschf = HfDeepSpeedConfig(ds_config) # keep this object alive # noqa + + def is_zero3_init_enabled(self): + return self.zero3_init_flag + + @contextmanager + def zero3_init_context_manager(self, enable=False): + old = self.zero3_init_flag + if old == enable: + yield + else: + self.zero3_init_flag = enable + self.dschf = None + self.set_deepspeed_weakref() + yield + self.zero3_init_flag = old + self.dschf = None + self.set_deepspeed_weakref() + + def _deepspeed_config_checks(self): + env_variable_names_to_ignore = [ + "ACCELERATE_GRADIENT_ACCUMULATION_STEPS", + "ACCELERATE_GRADIENT_CLIPPING", + "ACCELERATE_DEEPSPEED_ZERO_STAGE", + "ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_DEVICE", + "ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_DEVICE", + "ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_NVME_PATH", + "ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_NVME_PATH", + "ACCELERATE_DEEPSPEED_ZERO3_SAVE_16BIT_MODEL", + "ACCELERATE_MIXED_PRECISION", + ] + env_variable_names_to_ignore = [ + name.replace("ACCELERATE_", "").replace("DEEPSPEED_", "").lower() for name in env_variable_names_to_ignore + ] + + deepspeed_fields_from_accelerate_config = os.environ.get("ACCELERATE_CONFIG_DS_FIELDS", "").split(",") + + if any(name in env_variable_names_to_ignore for name in deepspeed_fields_from_accelerate_config): + raise ValueError( + f"When using `deepspeed_config_file`, the following accelerate config variables will be ignored: {env_variable_names_to_ignore}.\n" + "Please specify them appropriately in the DeepSpeed config file.\n" + "If you are using an accelerate config file, remove others config variables mentioned in the above specified list.\n" + "The easiest method is to create a new config following the questionnaire via `accelerate config`.\n" + "It will only ask for the necessary config variables when using `deepspeed_config_file`." + ) + + def set_moe_leaf_modules(self, model): + if self.transformer_moe_cls_names is None: + self.transformer_moe_cls_names = os.environ.get("ACCELERATE_DEEPSPEED_MOE_LAYER_CLS_NAMES", None) + if self.transformer_moe_cls_names is not None: + if compare_versions("deepspeed", "<", "0.14.0"): + raise ImportError("DeepSpeed version must be >= 0.14.0 to use MOE support. Please update DeepSpeed.") + from deepspeed.utils import set_z3_leaf_modules + + class_names = self.transformer_moe_cls_names.split(",") + transformer_moe_cls = [] + for layer_class in class_names: + transformer_cls = get_module_class_from_name(model, layer_class) + if transformer_cls is None: + raise Exception( + f"Could not find a transformer layer class called '{layer_class}' to wrap in the model." + ) + else: + transformer_moe_cls.append(transformer_cls) + set_z3_leaf_modules(model, transformer_moe_cls) # z3_leaf + + def select(self, _from_accelerator_state: bool = False): + """ + Sets the HfDeepSpeedWeakref to use the current deepspeed plugin configuration + """ + if not _from_accelerator_state: + raise ValueError( + "A `DeepSpeedPlugin` object must be enabled manually by calling `AcceleratorState().enable_deepspeed_plugin(plugin_key)`." + ) + self.set_deepspeed_weakref() + self._set_selected(True) + + def _unselect(self): + self._set_selected(False) + + def _set_selected(self, value: bool): + """ + Private setter for the 'enabled' attribute. + """ + self._selected = value + + @property + def selected(self): + return self._selected + + @selected.setter + def selected(self, value): + raise NotImplementedError( + "'enabled' can only be set through calling 'AcceleratorState().enable_deepspeed_plugin(key)'." + ) + + +@dataclass +class FullyShardedDataParallelPlugin: + """ + This plugin is used to enable fully sharded data parallelism. + + Args: + fsdp_version (`int`, defaults to `1`): + The version of FSDP to use. Defaults to 1. If set to 2, launcher expects the config to be converted to + FSDP2 format. + sharding_strategy (`Union[str, torch.distributed.fsdp.ShardingStrategy]`, defaults to `'FULL_SHARD'`): + Sharding strategy to use. Should be either a `str` or an instance of + `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy`. Is deprecated in favor of + `reshard_after_forward`. + reshard_after_forward (`Union[str, torch.distributed.fsdp.ShardingStrategy, bool]`, defaults to `'FULL_SHARD'` for `fsdp_version=1` and `True` for `fsdp_version=2`): + Sharding strategy to use. Should be a bool if `fsdp_version` is set to 2 else a `str` or an instance of + `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy`. + backward_prefetch (`Union[str, torch.distributed.fsdp.BackwardPrefetch]`, defaults to `'NO_PREFETCH'`): + Backward prefetch strategy to use. Should be either a `str` or an instance of + `torch.distributed.fsdp.fully_sharded_data_parallel.BackwardPrefetch`. + mixed_precision_policy (`Optional[Union[dict, torch.distributed.fsdp.MixedPrecision, torch.distributed.fsdp.MixedPrecisionPolicy]]`, defaults to `None`): + A config to enable mixed precision training with FullyShardedDataParallel. If passing in a `dict`, it + should have the following keys: `param_dtype`, `reduce_dtype`, and `buffer_dtype`, can be an instance of + `torch.distributed.fsdp.MixedPrecisionPolicy` if `fsdp_version` is set to 2. + auto_wrap_policy (`Optional(Union[Callable, Literal["transformer_based_wrap", "size_based_wrap", "no_wrap"]]), defaults to `NO_WRAP`): + A callable or string specifying a policy to recursively wrap layers with FSDP. If a string, it must be one + of `transformer_based_wrap`, `size_based_wrap`, or `no_wrap`. See + `torch.distributed.fsdp.wrap.size_based_wrap_policy` for a direction on what it should look like. + cpu_offload (`Union[bool, torch.distributed.fsdp.CPUOffload, torch.distributed.fsdp.CPUOffloadPolicy]`, defaults to `False`): + Whether to offload parameters to CPU. Should be either a `bool` or an instance of + `torch.distributed.fsdp.fully_sharded_data_parallel.CPUOffload` or + `torch.distributed.fsdp.fully_sharded_data_parallel.CPUOffloadPolicy` if `fsdp_version` is set to 2. + ignored_modules (`Optional[Union[Iterable[torch.nn.Module], str]]`, defaults to `None`): + A list of modules to ignore when wrapping with FSDP. When passing a string, will match the modules by name + using regex fullmatch. + state_dict_type (`Union[str, torch.distributed.fsdp.StateDictType]`, defaults to `'FULL_STATE_DICT'`): + State dict type to use. If a string, it must be one of `full_state_dict`, `local_state_dict`, or + `sharded_state_dict`. + state_dict_config (`Optional[Union[torch.distributed.fsdp.FullStateDictConfig, torch.distributed.fsdp.ShardedStateDictConfig]`, defaults to `None`): + State dict config to use. Is determined based on the `state_dict_type` if not passed in. + optim_state_dict_config (`Optional[Union[torch.distributed.fsdp.FullOptimStateDictConfig, torch.distributed.fsdp.ShardedOptimStateDictConfig]`, defaults to `None`): + Optim state dict config to use. Is determined based on the `state_dict_type` if not passed in. + limit_all_gathers (`bool`, defaults to `True`): + Whether to have FSDP explicitly synchronizes the CPU thread to prevent too many in-flight all-gathers. This + bool only affects the sharded strategies that schedule all-gathers. Enabling this can help lower the number + of CUDA malloc retries. + use_orig_params (`bool`, defaults to `False`): + Whether to use the original parameters for the optimizer. + param_init_fn (`Optional[Callable[[torch.nn.Module], None]`, defaults to `None`): + A `Callable[torch.nn.Module] -> None` that specifies how modules that are currently on the meta device + should be initialized onto an actual device. Only applicable when `sync_module_states` is `True`. By + default is a `lambda` which calls `to_empty` on the module. + sync_module_states (`bool`, defaults to `False`): + Whether each individually wrapped FSDP unit should broadcast module parameters from rank 0 to ensure they + are the same across all ranks after initialization. Defaults to `False` unless `cpu_ram_efficient_loading` + is `True`, then will be forcibly enabled. + forward_prefetch (`bool`, defaults to `False`): + Whether to have FSDP explicitly prefetches the next upcoming all-gather while executing in the forward + pass. only use with Static graphs. + activation_checkpointing (`bool`, defaults to `False`): + A technique to reduce memory usage by clearing activations of certain layers and recomputing them during a + backward pass. Effectively, this trades extra computation time for reduced memory usage. + cpu_ram_efficient_loading (`bool`, defaults to `None`): + If True, only the first process loads the pretrained model checkoint while all other processes have empty + weights. Only applicable for Transformers. When using this, `sync_module_states` needs to be `True`. + transformer_cls_names_to_wrap (`Optional[List[str]]`, defaults to `None`): + A list of transformer layer class names to wrap. Only applicable when `auto_wrap_policy` is + `transformer_based_wrap`. + min_num_params (`Optional[int]`, defaults to `None`): + The minimum number of parameters a module must have to be wrapped. Only applicable when `auto_wrap_policy` + is `size_based_wrap`. + """ + + fsdp_version: int = field( + default=None, + metadata={ + "help": "The version of FSDP to use. Defaults to 1. If set to 2, launcher expects the config to be converted to FSDP2 format." + }, + ) + + sharding_strategy: Union[str, "torch.distributed.fsdp.ShardingStrategy"] = field( + default=None, + metadata={ + "help": "Sharding strategy to use. Should be either a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy`. Defaults to 'FULL_SHARD'. Is deprecated in favor of `reshard_after_forward` " + }, + ) + + reshard_after_forward: Union[str, "torch.distributed.fsdp.ShardingStrategy", bool] = field( + default=None, + metadata={ + "help": "Sharding strategy to use. Should be a bool if `fsdp_version` is set to 2 else a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy`. Defaults to 'FULL_SHARD'" + }, + ) + backward_prefetch: Optional[Union[str, "torch.distributed.fsdp.BackwardPrefetch"]] = field( + default=None, + metadata={ + "help": "Backward prefetch strategy to use. Should be either a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.BackwardPrefetch`. Defaults to 'NO_PREFETCH'. This becomes obsolete in FSDP2." + }, + ) + mixed_precision_policy: Optional[ + Union[ + dict, + "torch.distributed.fsdp.MixedPrecision", + "torch.distributed.fsdp.MixedPrecisionPolicy", + ] + ] = field( + default=None, + metadata={ + "help": "A config to enable mixed precision training with FullyShardedDataParallel. " + "If passing in a `dict`, it should have the following keys: `param_dtype`, `reduce_dtype`, and `buffer_dtype`." + "Can also be an instance of `torch.distributed.fsdp.MixedPrecisionPolicy` if `fsdp_version` is set to 2." + }, + ) + auto_wrap_policy: Optional[Union[Callable, Literal["transformer_based_wrap", "size_based_wrap", "no_wrap"]]] = ( + field( + default=None, + metadata={ + "help": "A callable or string specifying a policy to recursively wrap layers with FSDP. If a string, it must be one of `transformer_based_wrap`, `size_based_wrap`, or `no_wrap`. " + "Defaults to `NO_WRAP`. See `torch.distributed.fsdp.wrap.size_based_wrap_policy` for a direction on what it should look like" + }, + ) + ) + cpu_offload: Union[ + bool, + "torch.distributed.fsdp.CPUOffload", + "torch.distributed.fsdp.CPUOffloadPolicy", + ] = field( + default=None, + metadata={ + "help": "Whether to offload parameters to CPU. Should be either a `bool` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.CPUOffload` or `torch.distributed.fsdp.fully_sharded_data_parallel.CPUOffloadPolicy` if `fsdp_version` is set to 2. Defaults to `False`" + }, + ) + ignored_modules: Optional[Union[Iterable[torch.nn.Module], str]] = field( + default=None, + metadata={"help": "A list of modules to ignore when wrapping with FSDP."}, + ) + + state_dict_type: Union[str, "torch.distributed.fsdp.StateDictType"] = field( + default=None, + metadata={ + "help": "State dict type to use. If a string, it must be one of `full_state_dict`, `local_state_dict`, or `sharded_state_dict`. Defaults to `FULL_STATE_DICT`" + }, + ) + state_dict_config: Optional[ + Union[ + "torch.distributed.fsdp.FullStateDictConfig", + "torch.distributed.fsdp.ShardedStateDictConfig", + ] + ] = field( + default=None, + metadata={"help": "State dict config to use. Is determined based on the `state_dict_type` if not passed in."}, + ) + optim_state_dict_config: Optional[ + Union[ + "torch.distributed.fsdp.FullOptimStateDictConfig", + "torch.distributed.fsdp.ShardedOptimStateDictConfig", + ] + ] = field( + default=None, + metadata={ + "help": "Optim state dict config to use. Is determined based on the `state_dict_type` if not passed in." + }, + ) + limit_all_gathers: bool = field( + default=True, + metadata={ + "help": "Whether to have FSDP explicitly synchronizes the CPU thread to prevent " + "too many in-flight all-gathers. This bool only affects the sharded strategies that schedule all-gathers. " + "Enabling this can help lower the number of CUDA malloc retries." + }, + ) + use_orig_params: Optional[bool] = field( + default=None, + metadata={ + "help": "Whether to use the original parameters for the optimizer. Defaults to `False`. This becomes obsolete in FSDP2." + }, + ) + param_init_fn: Optional[Callable[[torch.nn.Module], None]] = field( + default=None, + metadata={ + "help": "A Callable[torch.nn.Module] -> None that specifies how modules " + "that are currently on the meta device should be initialized onto an actual device. " + "Only applicable when `sync_module_states` is `True`. By default is a `lambda` which calls `to_empty` on the module." + }, + ) + sync_module_states: Optional[bool] = field( + default=None, + metadata={ + "help": "Whether each individually wrapped FSDP unit should broadcast module parameters from rank 0 " + "to ensure they are the same across all ranks after initialization. Defaults to `False` unless " + "`cpu_ram_efficient_loading` is `True`, then will be forcibly enabled. This becomes obsolete in FSDP2." + }, + ) + forward_prefetch: bool = field( + default=None, + metadata={ + "help": "Whether to have FSDP explicitly prefetches the next upcoming " + "all-gather while executing in the forward pass. only use with Static graphs. Defaults to `False`" + }, + ) + activation_checkpointing: bool = field( + default=None, + metadata={ + "help": "A technique to reduce memory usage by clearing activations of " + "certain layers and recomputing them during a backward pass. Effectively, this trades extra computation time " + "for reduced memory usage. Defaults to `False`" + }, + ) + cpu_ram_efficient_loading: bool = field( + default=None, + metadata={ + "help": "If True, only the first process loads the pretrained model checkoint while all other processes have empty weights. " + "Only applicable for 🤗 Transformers. When using this, `sync_module_states` needs to be `True`. Defaults to `False`." + }, + ) + transformer_cls_names_to_wrap: Optional[list[str]] = field( + default=None, + metadata={ + "help": "A list of transformer layer class names to wrap. Only applicable when `auto_wrap_policy` is `transformer_based_wrap`." + }, + ) + min_num_params: Optional[int] = field( + default=None, + metadata={ + "help": "The minimum number of parameters a module must have to be wrapped. Only applicable when `auto_wrap_policy` is `size_based_wrap`." + }, + ) + + def __post_init__(self): + from torch.distributed.fsdp import BackwardPrefetch, ShardingStrategy + + _fsdp2_warnings = set() + + env_prefix = "FSDP_" + # Strategy: By default we should always assume that values are passed in, else we check the environment variables + if self.fsdp_version is None: + self.fsdp_version = int(os.environ.get(env_prefix + "VERSION", "1")) + + if self.fsdp_version == 2: + if not is_torch_version(">=", FSDP2_PYTORCH_VERSION): + raise ImportError(f"FSDP2 requires PyTorch >= {FSDP2_PYTORCH_VERSION}") + + if self.sharding_strategy is not None: + # We cannot properly detect all of the cases, as by default `args.fsdp_sharding_strategy` is set to `fully_shard` + # Therefore we issue a warning only if the user has explicitly set it inside their plugin + _fsdp2_warnings.add( + "sharding_strategy is deprecated in favor of reshard_after_forward. " + "This will be removed in a future version of Accelerate." + ) + if self.fsdp_version == 1: + if self.sharding_strategy is None: + self.sharding_strategy = os.environ.get(env_prefix + "SHARDING_STRATEGY", "FULL_SHARD") + if isinstance(self.sharding_strategy, str): + if self.sharding_strategy.upper() in FSDP_SHARDING_STRATEGY: + self.sharding_strategy = FSDP_SHARDING_STRATEGY.index(self.sharding_strategy.upper()) + 1 + if isinstance(self.sharding_strategy, int) or self.sharding_strategy.isdigit(): + self.sharding_strategy = ShardingStrategy(int(self.sharding_strategy)) + else: + self.sharding_strategy = ShardingStrategy[self.sharding_strategy.upper()] + + # Fallback to `reshard_after_forward` in FSDP1 if `sharding_strategy` is not set + if self.reshard_after_forward is None and self.sharding_strategy is None: + reshard_after_forward = os.environ.get( + env_prefix + "RESHARD_AFTER_FORWARD", + "true" if self.fsdp_version == 2 else "FULL_SHARD", + ) + if self.fsdp_version == 2: + self.reshard_after_forward = str_to_bool(reshard_after_forward.lower(), to_bool=True) + else: + self.reshard_after_forward = reshard_after_forward + if isinstance(self.reshard_after_forward, str): + if self.fsdp_version == 2: + self.reshard_after_forward = str_to_bool(self.reshard_after_forward.lower(), to_bool=True) + else: + # We need to remap based on custom enum values for user readability + if self.reshard_after_forward.upper() in FSDP_SHARDING_STRATEGY: + self.reshard_after_forward = FSDP_SHARDING_STRATEGY.index(self.reshard_after_forward.upper()) + 1 + if isinstance(self.reshard_after_forward, int) or self.reshard_after_forward.isdigit(): + self.reshard_after_forward = ShardingStrategy(int(self.reshard_after_forward)) + else: + self.reshard_after_forward = ShardingStrategy[self.reshard_after_forward.upper()] + + if self.fsdp_version == 2 and not isinstance(self.reshard_after_forward, bool): + raise ValueError( + f"reshard_after_forward set to {self.reshard_after_forward}. This is not supported with FSDP2, please set to a `bool`" + ) + if self.fsdp_version == 1 and isinstance(self.reshard_after_forward, bool): + raise ValueError( + f"reshard_after_forward set to {self.reshard_after_forward}. This is not supported with FSDP1, please set to a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy`" + ) + + if self.cpu_offload is None: + self.cpu_offload = str_to_bool(os.environ.get(env_prefix + "OFFLOAD_PARAMS", "False")) == 1 + + self.set_cpu_offload() # abstracted away to hide imports due to version checks + self.validate_cpu_offload() + + if self.backward_prefetch is None: + self.backward_prefetch = os.environ.get(env_prefix + "BACKWARD_PREFETCH", None) + if isinstance(self.backward_prefetch, str) and self.backward_prefetch.upper() == "NO_PREFETCH": + self.backward_prefetch = None + if self.backward_prefetch is not None and not isinstance(self.backward_prefetch, BackwardPrefetch): + if isinstance(self.backward_prefetch, str) and self.backward_prefetch.upper() in FSDP_BACKWARD_PREFETCH: + self.backward_prefetch = FSDP_BACKWARD_PREFETCH.index(self.backward_prefetch.upper()) + 1 + if isinstance(self.backward_prefetch, int) or self.backward_prefetch.isdigit(): + self.backward_prefetch = BackwardPrefetch(int(self.backward_prefetch)) + else: + self.backward_prefetch = BackwardPrefetch[self.backward_prefetch.upper()] + if self.fsdp_version == 2 and self.backward_prefetch is not None: + _fsdp2_warnings.add("backward_prefetch is not supported in FSDP2. Setting backward prefetch to None.") + self.backward_prefetch = None + + self.set_state_dict_type() + + if self.auto_wrap_policy is None: + self.auto_wrap_policy = os.environ.get(env_prefix + "AUTO_WRAP_POLICY", "NO_WRAP") + if isinstance(self.auto_wrap_policy, str): + if self.auto_wrap_policy.upper() not in FSDP_AUTO_WRAP_POLICY: + raise ValueError( + f"Invalid auto wrap policy: {self.auto_wrap_policy}. Must be one of {FSDP_AUTO_WRAP_POLICY}" + ) + from torch.distributed.fsdp.wrap import ( + size_based_auto_wrap_policy, + transformer_auto_wrap_policy, + ) + + if self.auto_wrap_policy.upper() == "TRANSFORMER_BASED_WRAP": + self.auto_wrap_policy = transformer_auto_wrap_policy + if self.transformer_cls_names_to_wrap is None: + self.transformer_cls_names_to_wrap = os.environ.get(env_prefix + "TRANSFORMER_CLS_TO_WRAP", None) + if isinstance(self.transformer_cls_names_to_wrap, str): + self.transformer_cls_names_to_wrap = self.transformer_cls_names_to_wrap.split(",") + elif self.auto_wrap_policy.upper() == "SIZE_BASED_WRAP": + self.auto_wrap_policy = size_based_auto_wrap_policy + if self.min_num_params is None: + self.min_num_params = int(os.environ.get(env_prefix + "MIN_NUM_PARAMS", 0)) + elif not isinstance(self.min_num_params, int): + raise ValueError( + f"`min_num_params` must be an integer. Got {self.min_num_params} of type {type(self.min_num_params)}" + ) + elif self.auto_wrap_policy.upper() == "NO_WRAP": + self.auto_wrap_policy = None + + if self.use_orig_params is None and self.fsdp_version == 1: + self.use_orig_params = str_to_bool(os.environ.get(env_prefix + "USE_ORIG_PARAMS", "False")) == 1 + if self.fsdp_version == 2 and self.use_orig_params is not None: + _fsdp2_warnings.add("use_orig_params is obsolete in FSDP2, as FSDP2 always uses the original parameters.") + self.use_orig_params = None + + if self.sync_module_states is None and self.fsdp_version == 1: + self.sync_module_states = str_to_bool(os.environ.get(env_prefix + "SYNC_MODULE_STATES", "False")) == 1 + if self.fsdp_version == 2 and self.sync_module_states is not None: + _fsdp2_warnings.add( + "sync_module_states is obsolete in FSDP2, as it is not needed anymore." + "Setting sync_module_states to None." + ) + self.sync_module_states = None + + if self.forward_prefetch is None and self.fsdp_version == 1: + self.forward_prefetch = str_to_bool(os.environ.get(env_prefix + "FORWARD_PREFETCH", "False")) == 1 + if self.fsdp_version == 2 and self.forward_prefetch is not None: + raise ValueError("forward_prefetch is not yet implemented in FSDP2, set to None or use `fsdp_version=1`") + + if self.activation_checkpointing is None: + self.activation_checkpointing = ( + str_to_bool(os.environ.get(env_prefix + "ACTIVATION_CHECKPOINTING", "False")) == 1 + ) + + if self.ignored_modules is None: + self.ignored_modules = os.environ.get(env_prefix + "IGNORED_MODULES", None) + + if self.cpu_ram_efficient_loading is None: + self.cpu_ram_efficient_loading = ( + str_to_bool(os.environ.get(env_prefix + "CPU_RAM_EFFICIENT_LOADING", "False")) == 1 + ) + # There's no need to specify sync_module_states in FSDP2 + if self.fsdp_version == 1 and self.cpu_ram_efficient_loading and not self.sync_module_states: + warnings.warn( + "sync_module_states cannot be False since efficient cpu ram loading enabled. " + "Setting sync_module_states to True." + ) + self.sync_module_states = True + + if self.cpu_ram_efficient_loading != bool( + str_to_bool(os.environ.get(env_prefix + "CPU_RAM_EFFICIENT_LOADING", "False")) + ): + env_var = env_prefix + "CPU_RAM_EFFICIENT_LOADING" + warnings.warn( + f"The `cpu_ram_efficient_loading` flag for `FullyShardedDataParallelPlugin` does not match the environment variable {env_var}. " + "Setting environment variable to match `cpu_ram_efficient_loading`." + ) + os.environ[env_var] = str(self.cpu_ram_efficient_loading) + + if isinstance(self.mixed_precision_policy, dict): + self.set_mixed_precision(self.mixed_precision_policy) + if self.mixed_precision_policy is not None: + self.validate_mixed_precision_policy() + + if self.sync_module_states: + if is_npu_available(): + device = torch.npu.current_device() + elif is_mlu_available(): + device = torch.mlu.current_device() + elif is_musa_available(): + device = torch.musa.current_device() + elif is_cuda_available(): + device = torch.cuda.current_device() + elif is_xpu_available(): + device = torch.xpu.current_device() + elif is_hpu_available(): + device = torch.hpu.current_device() + else: + raise RuntimeError( + "There are currently no available devices found, must be one of 'XPU', 'CUDA', 'MLU', 'NPU', 'MUSA', or 'HPU'." + ) + # Create a function that will be used to initialize the parameters of the model + # when using `sync_module_states` + self.param_init_fn = lambda x: x.to_empty(device=device, recurse=False) + + # Single warning for all deprecation warnings due to FSDP2 conversion + if _fsdp2_warnings: + logger.warning("Multiple deprecation warnings due to FSDP2 conversion:\n".join(_fsdp2_warnings)) + + def set_state_dict_type(self, state_dict_type=None): + """ + Set the state dict config based on the `StateDictType`. + """ + from torch.distributed.fsdp.fully_sharded_data_parallel import ( + FullOptimStateDictConfig, + FullStateDictConfig, + ShardedOptimStateDictConfig, + ShardedStateDictConfig, + StateDictType, + ) + + # Override the state_dict_type if provided, typical use case: + # user trains with sharded, but final save is with full + if state_dict_type is not None: + self.state_dict_type = state_dict_type + + if self.state_dict_type is None: + self.state_dict_type = os.environ.get( + "FSDP_STATE_DICT_TYPE", + "FULL_STATE_DICT" if self.fsdp_version == 1 else "SHARDED_STATE_DICT", + ) + if isinstance(self.state_dict_type, str): + if self.state_dict_type.isdigit(): + self.state_dict_type = StateDictType(int(self.state_dict_type)) + else: + self.state_dict_type = StateDictType[self.state_dict_type.upper()] + + if self.state_dict_type == StateDictType.FULL_STATE_DICT: + if self.state_dict_config is None: + self.state_dict_config = FullStateDictConfig(offload_to_cpu=True, rank0_only=True) + if self.optim_state_dict_config is None: + self.optim_state_dict_config = FullOptimStateDictConfig(offload_to_cpu=True, rank0_only=True) + elif self.state_dict_type == StateDictType.SHARDED_STATE_DICT: + if self.state_dict_config is None: + self.state_dict_config = ShardedStateDictConfig(offload_to_cpu=True) + if self.optim_state_dict_config is None: + self.optim_state_dict_config = ShardedOptimStateDictConfig(offload_to_cpu=True) + + if self.fsdp_version == 2 and self.state_dict_type == StateDictType.LOCAL_STATE_DICT: + raise ValueError( + "FSDP2 does not support LOCAL_STATE_DICT. " + "Please set `fsdp_state_dict_type` to `SHARDED_STATE_DICT` or `FULL_STATE_DICT`." + ) + + def set_auto_wrap_policy(self, model): + """ + Given `model`, creates an `auto_wrap_policy` baesd on the passed in policy and if we can use the + `transformer_cls_to_wrap` + """ + from torch.distributed.fsdp.wrap import ( + size_based_auto_wrap_policy, + transformer_auto_wrap_policy, + ) + + # First base off of `_no_split_modules` + no_split_modules = getattr(model, "_no_split_modules", None) + default_transformer_cls_names_to_wrap = list(no_split_modules) if no_split_modules is not None else [] + if self.auto_wrap_policy == transformer_auto_wrap_policy: + if self.transformer_cls_names_to_wrap is None: + self.transformer_cls_names_to_wrap = default_transformer_cls_names_to_wrap + transformer_cls_to_wrap = set() + for layer_class in self.transformer_cls_names_to_wrap: + transformer_cls = get_module_class_from_name(model, layer_class) + if transformer_cls is None: + raise ValueError(f"Could not find the transformer layer class {layer_class} in the model.") + transformer_cls_to_wrap.add(transformer_cls) + # Finally we set the auto_wrap_policy to a callable + self.auto_wrap_policy = functools.partial( + self.auto_wrap_policy, transformer_layer_cls=transformer_cls_to_wrap + ) + + elif self.auto_wrap_policy == size_based_auto_wrap_policy: + # If zero, we silently ignore it. + if self.min_num_params > 0: + self.auto_wrap_policy = functools.partial(self.auto_wrap_policy, min_num_params=self.min_num_params) + else: + self.auto_wrap_policy = None + + def set_mixed_precision(self, mixed_precision, buffer_autocast=False, override=False): + "Sets the mixed precision policy for FSDP" + mixed_precision_mapping = { + "fp8": torch.bfloat16, + "fp16": torch.float16, + "bf16": torch.bfloat16, + "fp32": torch.float32, + } + dtype = mixed_precision + if isinstance(mixed_precision, str): + dtype = mixed_precision_mapping.get(mixed_precision, None) + if dtype is None: + raise ValueError( + f"Invalid mixed precision: {mixed_precision}. Must be one of {list(mixed_precision_mapping.keys())}" + ) + elif isinstance(mixed_precision, torch.dtype) and mixed_precision not in mixed_precision_mapping.values(): + raise ValueError( + f"Invalid mixed precision: {mixed_precision}. Must be one of {list(mixed_precision_mapping.values())}" + ) + + buffer_type = torch.float32 if buffer_autocast else dtype + + if self.fsdp_version == 1: + from torch.distributed.fsdp import MixedPrecision + elif self.fsdp_version == 2: + from torch.distributed.fsdp import MixedPrecisionPolicy as MixedPrecision + + if override or self.mixed_precision_policy is None: + dtype_args = {"param_dtype": dtype, "reduce_dtype": dtype} + if self.fsdp_version == 1: + dtype_args["buffer_dtype"] = buffer_type + else: + dtype_args["output_dtype"] = dtype + # TODO(s1ro1): `cast_forward_inputs` for FSDP2? + self.mixed_precision_policy = MixedPrecision(**dtype_args) + elif isinstance(self.mixed_precision_policy, dict): + # Check for incompatible types + valid_keys = ["param_dtype", "reduce_dtype"] + ( + ["buffer_dtype"] if self.fsdp_version == 1 else ["output_dtype"] + ) + missing_keys = [k for k in valid_keys if k not in self.mixed_precision_policy] + invalid_values = [ + k for k, v in self.mixed_precision_policy.items() if v not in mixed_precision_mapping.values() + ] + if missing_keys or invalid_values: + raise ValueError( + f"Invalid mixed precision policy: {self.mixed_precision_policy}. " + f"Must be a `dict` with keys {valid_keys}." + f"Values must be one of {list(mixed_precision_mapping.values())}" + ) + self.mixed_precision_policy = MixedPrecision(**self.mixed_precision_policy) + + def validate_mixed_precision_policy(self): + """ + Validates the mixed precision policy, abstracted away to not bring in the imports if not needed. + """ + if self.fsdp_version == 2: + from torch.distributed.fsdp import MixedPrecisionPolicy as MixedPrecision + else: + from torch.distributed.fsdp import MixedPrecision + + if not isinstance(self.mixed_precision_policy, MixedPrecision): + required_type = ( + "`torch.distributed.fsdp.MixedPrecisionPolicy`" + if self.fsdp_version == 2 + else "`torch.distributed.fsdp.MixedPrecision`" + ) + raise ValueError(f"mixed_precision_policy must be an instance of {required_type}.") + + def set_cpu_offload(self): + if self.fsdp_version == 2: + from torch.distributed.fsdp import CPUOffloadPolicy, OffloadPolicy + else: + from torch.distributed.fsdp import CPUOffload + + if isinstance(self.cpu_offload, bool): + if self.fsdp_version == 2: + if not self.cpu_offload: + self.cpu_offload = OffloadPolicy() + else: + self.cpu_offload = CPUOffloadPolicy() + else: + self.cpu_offload = CPUOffload(offload_params=self.cpu_offload) + + def validate_cpu_offload(self): + if self.fsdp_version == 2: + from torch.distributed.fsdp import OffloadPolicy + else: + from torch.distributed.fsdp import CPUOffload + + if self.fsdp_version == 2 and not isinstance(self.cpu_offload, OffloadPolicy): + raise ValueError( + f"`cpu_offload` must be an instance of `torch.distributed.fsdp.OffloadPolicy` in FSDP2, got {self.cpu_offload}" + ) + if self.fsdp_version == 1 and not isinstance(self.cpu_offload, CPUOffload): + raise ValueError( + f"`cpu_offload` must be an instance of `torch.distributed.fsdp.CPUOffload` in FSDP1, got {self.cpu_offload}" + ) + + +@dataclass +class TorchTensorParallelPlugin: + """ + This plugin is used to enable tensor parallelism using PyTorch >= 2.0. + """ + + tp_size: int = field( + default=1, + metadata={"help": "tensor parallel size will be used in the device mesh preparation"}, + ) + + # torch_device_mesh is of type "torch.distributed.DeviceMesh" + torch_device_mesh: Optional["torch.distributed.DeviceMesh"] = field(default=None) + + +@dataclass +class TorchContextParallelConfig: + """ + This class holds the configuration for context parallelism in PyTorch. + """ + + cp_comm_strategy: Optional[str] = field( + default=None, + metadata={ + "help": "Communication strategy for context parallelism. Can be one of 'allgather' or 'alltoall'. Defaults to 'allgather'." + }, + ) + + def __post_init__(self): + if not is_torch_version(">=", BETA_CP_AVAILABLE_PYTORCH_VERSION): + raise ValueError( + f"Context parallelism is only available in PyTorch {BETA_CP_AVAILABLE_PYTORCH_VERSION} and later versions. " + "Please upgrade your PyTorch version." + ) + if self.cp_comm_strategy is None: + self.cp_comm_strategy = os.environ.get("PARALLELISM_CONFIG_CP_COMM_STRATEGY", "allgather") + if self.cp_comm_strategy not in ["allgather", "alltoall"]: + raise ValueError( + f"Invalid cp_comm_strategy: {self.cp_comm_strategy}. Must be one of 'allgather' or 'alltoall'." + ) + + +@dataclass +class TorchTensorParallelConfig: + """ + Use this object in your [`Accelerator`] to customize your torch tensor parallelism. + """ + + enable_async_tp: bool = False + + def __post_init__(self): + if not is_torch_version(">=", BETA_TP_AVAILABLE_PYTORCH_VERSION): + raise ValueError( + f"Torch tensor parallelism is only available in PyTorch {BETA_TP_AVAILABLE_PYTORCH_VERSION} and later versions. " + "Please upgrade your PyTorch version." + ) + + if not compare_versions("transformers", ">=", BETA_TP_AVAILABLE_TRANSFORMERS_VERSION): + raise ValueError(f"TP requires transformers >= {BETA_TP_AVAILABLE_TRANSFORMERS_VERSION}") + + if self.enable_async_tp: + warnings.warn("Async tensor parallelism is currently not supported, ignoring this option.") + + +@dataclass +class MegatronLMPlugin: + """ + Plugin for Megatron-LM to enable tensor, pipeline, sequence and data parallelism. Also to enable selective + activation recomputation and optimized fused kernels. + + Args: + tp_degree (`int`, defaults to `None`): + Tensor parallelism degree. + pp_degree (`int`, defaults to `None`): + Pipeline parallelism degree. + num_micro_batches (`int`, defaults to `None`): + Number of micro-batches. + gradient_clipping (`float`, defaults to `None`): + Gradient clipping value based on global L2 Norm (0 to disable). + sequence_parallelism (`bool`, defaults to `None`): + Enable sequence parallelism. + recompute_activations (`bool`, defaults to `None`): + Enable selective activation recomputation. + use_distributed_optimizr (`bool`, defaults to `None`): + Enable distributed optimizer. + pipeline_model_parallel_split_rank (`int`, defaults to `None`): + Rank where encoder and decoder should be split. + num_layers_per_virtual_pipeline_stage (`int`, defaults to `None`): + Number of layers per virtual pipeline stage. + is_train_batch_min (`str`, defaults to `True`): + If both tran & eval dataloaders are specified, this will decide the `micro_batch_size`. + train_iters (`int`, defaults to `None`): + Total number of samples to train over all training runs. Note that either train-iters or train-samples + should be provided when using `MegatronLMDummyScheduler`. + train_samples (`int`, defaults to `None`): + Total number of samples to train over all training runs. Note that either train-iters or train-samples + should be provided when using `MegatronLMDummyScheduler`. + weight_decay_incr_style (`str`, defaults to `'constant'`): + Weight decay increment function. choices=["constant", "linear", "cosine"]. + start_weight_decay (`float`, defaults to `None`): + Initial weight decay coefficient for L2 regularization. + end_weight_decay (`float`, defaults to `None`): + End of run weight decay coefficient for L2 regularization. + lr_decay_style (`str`, defaults to `'linear'`): + Learning rate decay function. choices=['constant', 'linear', 'cosine']. + lr_decay_iters (`int`, defaults to `None`): + Number of iterations for learning rate decay. If None defaults to `train_iters`. + lr_decay_samples (`int`, defaults to `None`): + Number of samples for learning rate decay. If None defaults to `train_samples`. + lr_warmup_iters (`int`, defaults to `None`): + Number of iterations to linearly warmup learning rate over. + lr_warmup_samples (`int`, defaults to `None`): + Number of samples to linearly warmup learning rate over. + lr_warmup_fraction (`float`, defaults to `None`): + Fraction of lr-warmup-(iters/samples) to linearly warmup learning rate over. + min_lr (`float`, defaults to `0`): + Minumum value for learning rate. The scheduler clip values below this threshold. + consumed_samples (`List`, defaults to `None`): + Number of samples consumed in the same order as the dataloaders to `accelerator.prepare` call. + no_wd_decay_cond (`Optional`, defaults to `None`): + Condition to disable weight decay. + scale_lr_cond (`Optional`, defaults to `None`): + Condition to scale learning rate. + lr_mult (`float`, defaults to `1.0`): + Learning rate multiplier. + megatron_dataset_flag (`bool`, defaults to `False`): + Whether the format of dataset follows Megatron-LM Indexed/Cached/MemoryMapped format. + seq_length (`int`, defaults to `None`): + Maximum sequence length to process. + encoder_seq_length (`int`, defaults to `None`): + Maximum sequence length to process for the encoder. + decoder_seq_length (`int`, defaults to `None`): + Maximum sequence length to process for the decoder. + tensorboard_dir (`str`, defaults to `None`): + Path to save tensorboard logs. + set_all_logging_options (`bool`, defaults to `False`): + Whether to set all logging options. + eval_iters (`int`, defaults to `100`): + Number of iterations to run for evaluation validation/test for. + eval_interval (`int`, defaults to `1000`): + Interval between running evaluation on validation set. + return_logits (`bool`, defaults to `False`): + Whether to return logits from the model. + custom_train_step_class (`Optional`, defaults to `None`): + Custom train step class. + custom_train_step_kwargs (`Optional`, defaults to `None`): + Custom train step kwargs. + custom_model_provider_function (`Optional`, defaults to `None`): + Custom model provider function. + custom_prepare_model_function (`Optional`, defaults to `None`): + Custom prepare model function. + custom_megatron_datasets_provider_function (`Optional`, defaults to `None`): + Custom megatron train_valid_test datasets provider function. + custom_get_batch_function (`Optional`, defaults to `None`): + Custom get batch function. + custom_loss_function (`Optional`, defaults to `None`): + Custom loss function. + other_megatron_args (`Optional`, defaults to `None`): + Other Megatron-LM arguments. Please refer Megatron-LM. + """ + + tp_degree: int = field(default=None, metadata={"help": "tensor parallelism degree."}) + pp_degree: int = field(default=None, metadata={"help": "pipeline parallelism degree."}) + num_micro_batches: int = field(default=None, metadata={"help": "number of micro-batches."}) + gradient_clipping: float = field( + default=None, + metadata={"help": "gradient clipping value based on global L2 Norm (0 to disable)"}, + ) + sequence_parallelism: bool = field( + default=None, + metadata={"help": "enable sequence parallelism"}, + ) + recompute_activations: bool = field( + default=None, + metadata={"help": "enable selective activation recomputation"}, + ) + use_distributed_optimizer: bool = field( + default=None, + metadata={"help": "enable distributed optimizer"}, + ) + pipeline_model_parallel_split_rank: int = field( + default=None, + metadata={"help": "Rank where encoder and decoder should be split."}, + ) + num_layers_per_virtual_pipeline_stage: int = field( + default=None, metadata={"help": "Number of layers per virtual pipeline stage."} + ) + is_train_batch_min: str = field( + default=True, + metadata={"help": "If both train & eval dataloaders are specified, this will decide the micro_batch_size"}, + ) + train_iters: int = field( + default=None, + metadata={ + "help": "Total number of iterations to train over all training runs. " + "Note that either train-iters or train-samples should be provided when using `MegatronLMDummyScheduler`" + }, + ) + train_samples: int = field( + default=None, + metadata={ + "help": "Total number of samples to train over all training runs. " + "Note that either train-iters or train-samples should be provided when using `MegatronLMDummyScheduler`" + }, + ) + weight_decay_incr_style: str = field( + default="constant", + metadata={"help": 'Weight decay increment function. choices=["constant", "linear", "cosine"]. '}, + ) + start_weight_decay: float = field( + default=None, + metadata={"help": "Initial weight decay coefficient for L2 regularization."}, + ) + end_weight_decay: float = field( + default=None, + metadata={"help": "End of run weight decay coefficient for L2 regularization."}, + ) + lr_decay_style: str = field( + default="linear", + metadata={"help": "Learning rate decay function. choices=['constant', 'linear', 'cosine']."}, + ) + lr_decay_iters: int = field( + default=None, + metadata={"help": "Number of iterations for learning rate decay. If None defaults to `train_iters`."}, + ) + lr_decay_samples: int = field( + default=None, + metadata={"help": "Number of samples for learning rate decay. If None defaults to `train_samples`."}, + ) + lr_warmup_iters: int = field( + default=None, + metadata={"help": "number of iterations to linearly warmup learning rate over."}, + ) + lr_warmup_samples: int = field( + default=None, + metadata={"help": "number of samples to linearly warmup learning rate over."}, + ) + lr_warmup_fraction: float = field( + default=None, + metadata={"help": "fraction of lr-warmup-(iters/samples) to linearly warmup learning rate over."}, + ) + min_lr: float = field( + default=0, + metadata={"help": "Minumum value for learning rate. The scheduler clip values below this threshold."}, + ) + consumed_samples: list[int] = field( + default=None, + metadata={ + "help": "Number of samples consumed in the same order as the dataloaders to `accelerator.prepare` call." + }, + ) + no_wd_decay_cond: Optional[Callable] = field(default=None, metadata={"help": "Condition to disable weight decay."}) + scale_lr_cond: Optional[Callable] = field(default=None, metadata={"help": "Condition to scale learning rate."}) + lr_mult: float = field(default=1.0, metadata={"help": "Learning rate multiplier."}) + megatron_dataset_flag: bool = field( + default=False, + metadata={"help": "Whether the format of dataset follows Megatron-LM Indexed/Cached/MemoryMapped format."}, + ) + seq_length: int = field( + default=None, + metadata={"help": "Maximum sequence length to process."}, + ) + encoder_seq_length: int = field( + default=None, + metadata={"help": "Maximum sequence length to process for the encoder."}, + ) + decoder_seq_length: int = field( + default=None, + metadata={"help": "Maximum sequence length to process for the decoder."}, + ) + tensorboard_dir: str = field( + default=None, + metadata={"help": "Path to save tensorboard logs."}, + ) + set_all_logging_options: bool = field( + default=False, + metadata={"help": "Whether to set all logging options."}, + ) + eval_iters: int = field( + default=100, + metadata={"help": "Number of iterations to run for evaluation validation/test for."}, + ) + eval_interval: int = field( + default=1000, + metadata={"help": "Interval between running evaluation on validation set."}, + ) + return_logits: bool = field( + default=False, + metadata={"help": "Whether to return logits from the model."}, + ) + + # custom train step args + custom_train_step_class: Optional[Any] = field( + default=None, + metadata={"help": "Custom train step class."}, + ) + custom_train_step_kwargs: Optional[dict[str, Any]] = field( + default=None, + metadata={"help": "Custom train step kwargs."}, + ) + + # custom model args + custom_model_provider_function: Optional[Callable] = field( + default=None, + metadata={"help": "Custom model provider function."}, + ) + custom_prepare_model_function: Optional[Callable] = field( + default=None, + metadata={"help": "Custom prepare model function."}, + ) + custom_megatron_datasets_provider_function: Optional[Callable] = field( + default=None, + metadata={"help": "Custom megatron train_valid_test datasets provider function."}, + ) + custom_get_batch_function: Optional[Callable] = field( + default=None, + metadata={"help": "Custom get batch function."}, + ) + custom_loss_function: Optional[Callable] = field( + default=None, + metadata={"help": "Custom loss function."}, + ) + + # remaining args such as enabling Alibi/ROPE positional embeddings, + # wandb logging, Multi-Query Attention, etc. + other_megatron_args: Optional[dict[str, Any]] = field( + default=None, + metadata={"help": "Other Megatron-LM arguments. Please refer Megatron-LM"}, + ) + + def __post_init__(self): + prefix = "MEGATRON_LM_" + if self.tp_degree is None: + self.tp_degree = int(os.environ.get(prefix + "TP_DEGREE", 1)) + if self.pp_degree is None: + self.pp_degree = int(os.environ.get(prefix + "PP_DEGREE", 1)) + if self.num_micro_batches is None: + self.num_micro_batches = int(os.environ.get(prefix + "NUM_MICRO_BATCHES", 1)) + if self.gradient_clipping is None: + self.gradient_clipping = float(os.environ.get(prefix + "GRADIENT_CLIPPING", 1.0)) + if self.recompute_activations is None: + self.recompute_activations = str_to_bool(os.environ.get(prefix + "RECOMPUTE_ACTIVATIONS", "False")) == 1 + if self.use_distributed_optimizer is None: + self.use_distributed_optimizer = ( + str_to_bool(os.environ.get(prefix + "USE_DISTRIBUTED_OPTIMIZER", "False")) == 1 + ) + if self.sequence_parallelism is None: + self.sequence_parallelism = str_to_bool(os.environ.get(prefix + "SEQUENCE_PARALLELISM", "False")) == 1 + + if self.pp_degree > 1 or self.use_distributed_optimizer: + self.DDP_impl = "local" + else: + self.DDP_impl = "torch" + + if self.consumed_samples is not None: + if len(self.consumed_samples) == 1: + self.consumed_samples.extend([0, 0]) + elif len(self.consumed_samples) == 2: + self.consumed_samples.append(0) + + self.megatron_lm_default_args = { + "tensor_model_parallel_size": self.tp_degree, + "pipeline_model_parallel_size": self.pp_degree, + "pipeline_model_parallel_split_rank": self.pipeline_model_parallel_split_rank, + "num_layers_per_virtual_pipeline_stage": self.num_layers_per_virtual_pipeline_stage, + "DDP_impl": self.DDP_impl, + "use_distributed_optimizer": self.use_distributed_optimizer, + "sequence_parallel": self.sequence_parallelism, + "clip_grad": self.gradient_clipping, + "num_micro_batches": self.num_micro_batches, + "consumed_samples": self.consumed_samples, + "no_wd_decay_cond": self.no_wd_decay_cond, + "scale_lr_cond": self.scale_lr_cond, + "lr_mult": self.lr_mult, + "megatron_dataset_flag": self.megatron_dataset_flag, + "eval_iters": self.eval_iters, + "eval_interval": self.eval_interval, + } + if self.recompute_activations: + self.megatron_lm_default_args["recompute_granularity"] = "selective" + if self.tensorboard_dir is not None: + self.megatron_lm_default_args["tensorboard_dir"] = self.tensorboard_dir + if self.set_all_logging_options: + self.set_tensorboard_logging_options() + if self.other_megatron_args is not None: + self.megatron_lm_default_args.update(self.other_megatron_args) + + def set_network_size_args(self, model, batch_data=None): + model_config_type = model.config.model_type.lower() + for model_type in MODEL_CONFIGS_TO_MEGATRON_PARSERS.keys(): + if model_type in model_config_type: + MODEL_CONFIGS_TO_MEGATRON_PARSERS[model_type](self, model, batch_data) + return + raise ValueError( + f"Accelerate Megatron-LM integration not supports {model_config_type} model. " + "You can add your own model config parser." + ) + + def set_mixed_precision(self, mixed_precision): + if mixed_precision == "fp16": + self.megatron_lm_default_args["fp16"] = True + elif mixed_precision == "bf16": + self.megatron_lm_default_args["bf16"] = True + self.DDP_impl = "local" + self.megatron_lm_default_args["DDP_impl"] = self.DDP_impl + + def set_training_args(self, micro_batch_size, dp_degree): + self.data_parallel_size = dp_degree + self.micro_batch_size = micro_batch_size + self.global_batch_size = dp_degree * micro_batch_size * self.num_micro_batches + self.megatron_lm_default_args["data_parallel_size"] = self.data_parallel_size + self.megatron_lm_default_args["micro_batch_size"] = self.micro_batch_size + self.megatron_lm_default_args["global_batch_size"] = self.global_batch_size + + def set_optimizer_type(self, optimizer): + optimizer_name = optimizer.__class__.__name__.lower() + if "adam" in optimizer_name: + self.megatron_lm_default_args["optimizer"] = "adam" + self.megatron_lm_default_args["adam_beta1"] = optimizer.defaults["betas"][0] + self.megatron_lm_default_args["adam_beta2"] = optimizer.defaults["betas"][1] + self.megatron_lm_default_args["adam_eps"] = optimizer.defaults["eps"] + elif "sgd" in optimizer_name: + self.megatron_lm_default_args["optimizer"] = "sgd" + self.megatron_lm_default_args["sgd_momentum"] = optimizer.defaults["momentum"] + else: + raise ValueError(f"Optimizer {optimizer_name} is not supported by Megatron-LM") + + self.megatron_lm_default_args["lr"] = optimizer.defaults["lr"] + self.megatron_lm_default_args["weight_decay"] = optimizer.defaults["weight_decay"] + + def set_scheduler_args(self, scheduler): + if self.train_iters is None: + self.train_iters = scheduler.total_num_steps // self.megatron_lm_default_args["data_parallel_size"] + if self.train_samples is not None: + self.train_samples = None + warnings.warn( + "Ignoring `train_samples` as `train_iters` based on scheduler is being used for training." + ) + if self.lr_warmup_iters is None: + self.lr_warmup_iters = scheduler.warmup_num_steps // self.megatron_lm_default_args["data_parallel_size"] + if self.lr_warmup_samples is not None: + warnings.warn( + "Ignoring `lr_warmup_samples` as `lr_warmup_iters` based on scheduler is being used for training." + ) + self.lr_warmup_samples = 0 + + self.megatron_lm_default_args["train_iters"] = self.train_iters + self.megatron_lm_default_args["lr_warmup_iters"] = self.lr_warmup_iters + self.megatron_lm_default_args["train_samples"] = self.train_samples + self.megatron_lm_default_args["lr_warmup_samples"] = self.lr_warmup_samples + self.megatron_lm_default_args["lr_decay_iters"] = self.lr_decay_iters + self.megatron_lm_default_args["lr_decay_samples"] = self.lr_decay_samples + self.megatron_lm_default_args["lr_warmup_fraction"] = self.lr_warmup_fraction + self.megatron_lm_default_args["lr_decay_style"] = self.lr_decay_style + self.megatron_lm_default_args["weight_decay_incr_style"] = self.weight_decay_incr_style + self.megatron_lm_default_args["start_weight_decay"] = self.start_weight_decay + self.megatron_lm_default_args["end_weight_decay"] = self.end_weight_decay + self.megatron_lm_default_args["min_lr"] = self.min_lr + + def set_tensorboard_logging_options(self): + from megatron.training.arguments import _add_logging_args + + parser = argparse.ArgumentParser() + parser = _add_logging_args(parser) + logging_args = parser.parse_known_args() + self.dataset_args = vars(logging_args[0]) + for key, value in self.dataset_args.items(): + if key.startswith("log_"): + self.megatron_lm_default_args[key] = True + elif key.startswith("no_log_"): + self.megatron_lm_default_args[key.replace("no_", "")] = True + + +MODEL_CONFIGS_TO_MEGATRON_PARSERS = {} + + +def add_model_config_to_megatron_parser(model_type: str): + def add_model_config_parser_helper(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + + MODEL_CONFIGS_TO_MEGATRON_PARSERS[model_type] = func + return wrapper + + return add_model_config_parser_helper + + +@add_model_config_to_megatron_parser("megatron-bert") +def parse_bert_config(megatron_lm_plugin, model, batch_data): + model_type_name = "bert" + num_layers = model.config.num_hidden_layers + hidden_size = model.config.hidden_size + num_attention_heads = model.config.num_attention_heads + max_position_embeddings = model.config.max_position_embeddings + num_labels = model.config.num_labels + orig_vocab_size = model.config.vocab_size + pretraining_flag = False + if "maskedlm" in model.__class__.__name__.lower(): + pretraining_flag = True + if megatron_lm_plugin.seq_length is not None: + if megatron_lm_plugin.encoder_seq_length is not None: + warnings.warn("Both `seq_length` and `encoder_seq_length` are set. Using `encoder_seq_length`.") + megatron_lm_plugin.seq_length = megatron_lm_plugin.encoder_seq_length + elif megatron_lm_plugin.encoder_seq_length is not None: + megatron_lm_plugin.seq_length = megatron_lm_plugin.encoder_seq_length + elif batch_data is not None: + megatron_lm_plugin.seq_length = batch_data["input_ids"].shape[1] + else: + megatron_lm_plugin.seq_length = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["seq_length"] = megatron_lm_plugin.seq_length + megatron_lm_plugin.megatron_lm_default_args["model_type_name"] = model_type_name + megatron_lm_plugin.megatron_lm_default_args["num_layers"] = num_layers + megatron_lm_plugin.megatron_lm_default_args["hidden_size"] = hidden_size + megatron_lm_plugin.megatron_lm_default_args["num_attention_heads"] = num_attention_heads + megatron_lm_plugin.megatron_lm_default_args["max_position_embeddings"] = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["pretraining_flag"] = pretraining_flag + megatron_lm_plugin.megatron_lm_default_args["orig_vocab_size"] = orig_vocab_size + megatron_lm_plugin.megatron_lm_default_args["model_return_dict"] = model.config.return_dict + megatron_lm_plugin.megatron_lm_default_args["num_labels"] = num_labels + + +@add_model_config_to_megatron_parser("gpt2") +def parse_gpt2_config(megatron_lm_plugin, model, batch_data): + model_type_name = "gpt" + num_layers = model.config.n_layer + hidden_size = model.config.n_embd + num_attention_heads = model.config.n_head + max_position_embeddings = model.config.n_positions + orig_vocab_size = model.config.vocab_size + pretraining_flag = True + if megatron_lm_plugin.seq_length is not None: + if megatron_lm_plugin.decoder_seq_length is not None: + warnings.warn("Both `seq_length` and `decoder_seq_length` are set. Using `decoder_seq_length`.") + megatron_lm_plugin.seq_length = megatron_lm_plugin.decoder_seq_length + elif megatron_lm_plugin.decoder_seq_length is not None: + megatron_lm_plugin.seq_length = megatron_lm_plugin.decoder_seq_length + elif batch_data is not None: + megatron_lm_plugin.seq_length = batch_data["input_ids"].shape[1] + else: + megatron_lm_plugin.seq_length = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["seq_length"] = megatron_lm_plugin.seq_length + megatron_lm_plugin.megatron_lm_default_args["return_logits"] = megatron_lm_plugin.return_logits + megatron_lm_plugin.megatron_lm_default_args["tokenizer_type"] = "GPT2BPETokenizer" + megatron_lm_plugin.megatron_lm_default_args["model_type_name"] = model_type_name + megatron_lm_plugin.megatron_lm_default_args["num_layers"] = num_layers + megatron_lm_plugin.megatron_lm_default_args["hidden_size"] = hidden_size + megatron_lm_plugin.megatron_lm_default_args["num_attention_heads"] = num_attention_heads + megatron_lm_plugin.megatron_lm_default_args["max_position_embeddings"] = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["pretraining_flag"] = pretraining_flag + megatron_lm_plugin.megatron_lm_default_args["orig_vocab_size"] = orig_vocab_size + megatron_lm_plugin.megatron_lm_default_args["model_return_dict"] = model.config.return_dict + + +@add_model_config_to_megatron_parser("t5") +def parse_t5_config(megatron_lm_plugin, model, batch_data): + model_type_name = "t5" + num_layers = model.config.num_layers + hidden_size = model.config.d_model + num_attention_heads = model.config.num_heads + max_position_embeddings = model.config.n_positions if hasattr(model.config, "n_positions") else 1024 + orig_vocab_size = model.config.vocab_size + pretraining_flag = True + if megatron_lm_plugin.encoder_seq_length is None: + if batch_data is not None: + megatron_lm_plugin.encoder_seq_length = batch_data["input_ids"].shape[1] + else: + megatron_lm_plugin.encoder_seq_length = max_position_embeddings + if megatron_lm_plugin.decoder_seq_length is None: + if batch_data is not None: + megatron_lm_plugin.decoder_seq_length = batch_data["labels"].shape[1] + else: + megatron_lm_plugin.decoder_seq_length = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["encoder_seq_length"] = megatron_lm_plugin.encoder_seq_length + megatron_lm_plugin.megatron_lm_default_args["decoder_seq_length"] = megatron_lm_plugin.decoder_seq_length + megatron_lm_plugin.megatron_lm_default_args["model_type_name"] = model_type_name + megatron_lm_plugin.megatron_lm_default_args["num_layers"] = num_layers + megatron_lm_plugin.megatron_lm_default_args["hidden_size"] = hidden_size + megatron_lm_plugin.megatron_lm_default_args["num_attention_heads"] = num_attention_heads + megatron_lm_plugin.megatron_lm_default_args["max_position_embeddings"] = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["pretraining_flag"] = pretraining_flag + megatron_lm_plugin.megatron_lm_default_args["orig_vocab_size"] = orig_vocab_size + megatron_lm_plugin.megatron_lm_default_args["model_return_dict"] = model.config.return_dict + + +@add_model_config_to_megatron_parser("llama") +def parse_llama_config(megatron_lm_plugin, model, batch_data): + model_type_name = "gpt" + num_layers = model.config.num_hidden_layers + pretraining_flag = True + hidden_size = model.config.hidden_size + num_attention_heads = model.config.num_attention_heads + orig_vocab_size = model.config.vocab_size + + max_position_embeddings = model.config.max_position_embeddings + seq_length = getattr(model.config, "max_sequence_length", None) + if megatron_lm_plugin.seq_length is None: + if seq_length is not None: + megatron_lm_plugin.seq_length = seq_length + elif megatron_lm_plugin.decoder_seq_length is not None: + megatron_lm_plugin.seq_length = megatron_lm_plugin.decoder_seq_length + elif batch_data is not None: + megatron_lm_plugin.seq_length = batch_data["input_ids"].shape[1] + else: + megatron_lm_plugin.seq_length = max_position_embeddings + + megatron_lm_plugin.megatron_lm_default_args["return_logits"] = megatron_lm_plugin.return_logits + megatron_lm_plugin.megatron_lm_default_args["tokenizer_type"] = "Llama2Tokenizer" + megatron_lm_plugin.megatron_lm_default_args["model_type_name"] = model_type_name + megatron_lm_plugin.megatron_lm_default_args["num_layers"] = num_layers + megatron_lm_plugin.megatron_lm_default_args["pretraining_flag"] = pretraining_flag + megatron_lm_plugin.megatron_lm_default_args["hidden_size"] = hidden_size + megatron_lm_plugin.megatron_lm_default_args["num_attention_heads"] = num_attention_heads + megatron_lm_plugin.megatron_lm_default_args["orig_vocab_size"] = orig_vocab_size + megatron_lm_plugin.megatron_lm_default_args["max_position_embeddings"] = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["seq_length"] = megatron_lm_plugin.seq_length + megatron_lm_plugin.megatron_lm_default_args["model_return_dict"] = model.config.return_dict + + +@dataclass +class BnbQuantizationConfig: + """ + A plugin to enable BitsAndBytes 4bit and 8bit quantization + + Args: + load_in_8bit (`bool`, defaults to `False`): + Enable 8bit quantization. + llm_int8_threshold (`float`, defaults to `6.0`): + Value of the outliner threshold. Only relevant when `load_in_8bit=True`. + load_in_4_bit (`bool`, defaults to `False`): + Enable 4bit quantization. + bnb_4bit_quant_type (`str`, defaults to `fp4`): + Set the quantization data type in the `bnb.nn.Linear4Bit` layers. Options are {'fp4','np4'}. + bnb_4bit_use_double_quant (`bool`, defaults to `False`): + Enable nested quantization where the quantization constants from the first quantization are quantized + again. + bnb_4bit_compute_dtype (`bool`, defaults to `fp16`): + This sets the computational type which might be different than the input time. For example, inputs might be + fp32, but computation can be set to bf16 for speedups. Options are {'fp32','fp16','bf16'}. + torch_dtype (`torch.dtype`, defaults to `None`): + This sets the dtype of the remaining non quantized layers. `bitsandbytes` library suggests to set the value + to `torch.float16` for 8 bit model and use the same dtype as the compute dtype for 4 bit model. + skip_modules (`List[str]`, defaults to `None`): + An explicit list of the modules that we don't quantize. The dtype of these modules will be `torch_dtype`. + keep_in_fp32_modules (`List`, defaults to `None`): + An explicit list of the modules that we don't quantize. We keep them in `torch.float32`. + """ + + load_in_8bit: bool = field(default=False, metadata={"help": "enable 8bit quantization."}) + + llm_int8_threshold: float = field( + default=6.0, + metadata={"help": "value of the outliner threshold. only relevant when load_in_8bit=True"}, + ) + + load_in_4bit: bool = field(default=False, metadata={"help": "enable 4bit quantization."}) + + bnb_4bit_quant_type: str = field( + default="fp4", + metadata={ + "help": "set the quantization data type in the `bnb.nn.Linear4Bit` layers. Options are {'fp4','nf4'}." + }, + ) + + bnb_4bit_use_double_quant: bool = field( + default=False, + metadata={ + "help": "enable nested quantization where the quantization constants from the first quantization are quantized again." + }, + ) + + bnb_4bit_compute_dtype: str = field( + default="fp16", + metadata={ + "help": "This sets the computational type which might be different than the input time. For example, inputs might be " + "fp32, but computation can be set to bf16 for speedups. Options are {'fp32','fp16','bf16'}." + }, + ) + + torch_dtype: torch.dtype = field( + default=None, + metadata={ + "help": "this sets the dtype of the remaining non quantized layers. `bitsandbytes` library suggests to set the value" + "to `torch.float16` for 8 bit model and use the same dtype as the compute dtype for 4 bit model " + }, + ) + + skip_modules: list[str] = field( + default=None, + metadata={ + "help": "an explicit list of the modules that we don't quantize. The dtype of these modules will be `torch_dtype`." + }, + ) + + keep_in_fp32_modules: list[str] = field( + default=None, + metadata={"help": "an explicit list of the modules that we don't quantize. We keep them in `torch.float32`."}, + ) + + def __post_init__(self): + """ + Safety checker that arguments are correct - also replaces some NoneType arguments with their default values. + """ + if not isinstance(self.load_in_8bit, bool): + raise ValueError("load_in_8bit must be a boolean") + + if not isinstance(self.load_in_4bit, bool): + raise ValueError("load_in_4bit must be a boolean") + + if self.load_in_4bit and self.load_in_8bit: + raise ValueError("load_in_4bit and load_in_8bit can't be both True") + + if not self.load_in_4bit and not self.load_in_8bit: + raise ValueError("load_in_4bit and load_in_8bit can't be both False") + + if not isinstance(self.llm_int8_threshold, (int, float)): + raise ValueError("llm_int8_threshold must be a float or an int") + + if not isinstance(self.bnb_4bit_quant_type, str): + raise ValueError("bnb_4bit_quant_type must be a string") + elif self.bnb_4bit_quant_type not in ["fp4", "nf4"]: + raise ValueError(f"bnb_4bit_quant_type must be in ['fp4','nf4'] but found {self.bnb_4bit_quant_type}") + + if not isinstance(self.bnb_4bit_use_double_quant, bool): + raise ValueError("bnb_4bit_use_double_quant must be a boolean") + + if isinstance(self.bnb_4bit_compute_dtype, str): + if self.bnb_4bit_compute_dtype == "fp32": + self.bnb_4bit_compute_dtype = torch.float32 + elif self.bnb_4bit_compute_dtype == "fp16": + self.bnb_4bit_compute_dtype = torch.float16 + elif self.bnb_4bit_compute_dtype == "bf16": + self.bnb_4bit_compute_dtype = torch.bfloat16 + else: + raise ValueError( + f"bnb_4bit_compute_dtype must be in ['fp32','fp16','bf16'] but found {self.bnb_4bit_compute_dtype}" + ) + elif not isinstance(self.bnb_4bit_compute_dtype, torch.dtype): + raise ValueError("bnb_4bit_compute_dtype must be a string or a torch.dtype") + + if self.skip_modules is not None and not isinstance(self.skip_modules, list): + raise ValueError("skip_modules must be a list of strings") + + if self.keep_in_fp32_modules is not None and not isinstance(self.keep_in_fp32_modules, list): + raise ValueError("keep_in_fp_32_modules must be a list of strings") + + if self.load_in_4bit: + self.target_dtype = CustomDtype.INT4 + + if self.load_in_8bit: + self.target_dtype = torch.int8 + + if self.load_in_4bit and self.llm_int8_threshold != 6.0: + warnings.warn("llm_int8_threshold can only be used for model loaded in 8bit") + + if isinstance(self.torch_dtype, str): + if self.torch_dtype == "fp32": + self.torch_dtype = torch.float32 + elif self.torch_dtype == "fp16": + self.torch_dtype = torch.float16 + elif self.torch_dtype == "bf16": + self.torch_dtype = torch.bfloat16 + else: + raise ValueError(f"torch_dtype must be in ['fp32','fp16','bf16'] but found {self.torch_dtype}") + if self.load_in_8bit and self.torch_dtype is None: + self.torch_dtype = torch.float16 + + if self.load_in_4bit and self.torch_dtype is None: + self.torch_dtype = self.bnb_4bit_compute_dtype + + if not isinstance(self.torch_dtype, torch.dtype): + raise ValueError("torch_dtype must be a torch.dtype") + + +def get_module_class_from_name(module, name): + """ + Gets a class from a module by its name. + + Args: + module (`torch.nn.Module`): The module to get the class from. + name (`str`): The name of the class. + """ + modules_children = list(module.children()) + if module.__class__.__name__ == name: + return module.__class__ + elif len(modules_children) == 0: + return + else: + for child_module in modules_children: + module_class = get_module_class_from_name(child_module, name) + if module_class is not None: + return module_class diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/deepspeed.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/deepspeed.py new file mode 100644 index 0000000000000000000000000000000000000000..22db891c63d9bd48691acd87a15a206c270017a9 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/deepspeed.py @@ -0,0 +1,385 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import base64 +import json +import os +from copy import deepcopy + +from torch import optim + +from ..optimizer import AcceleratedOptimizer +from ..scheduler import AcceleratedScheduler +from .dataclasses import DistributedType +from .imports import is_bnb_available +from .versions import compare_versions + + +def map_pytorch_optim_to_deepspeed(optimizer): + """ + Args: + optimizer: torch.optim.Optimizer + + Returns the DeepSeedCPUOptimizer (deepspeed.ops) version of the optimizer. + """ + + defaults = {k: v for k, v in optimizer.defaults.items() if k in ["lr", "weight_decay"]} + + # Select the DeepSpeedCPUOptimizer based on the original optimizer class. + # DeepSpeedCPUAdam is the default + from deepspeed.ops.adam import DeepSpeedCPUAdam + + optimizer_class = DeepSpeedCPUAdam + + # For DeepSpeedCPUAdam (adamw_mode) + if compare_versions("deepspeed", ">=", "0.3.1"): + defaults["adamw_mode"] = False + is_adaw = isinstance(optimizer, optim.AdamW) + + if is_bnb_available() and not is_adaw: + import bitsandbytes.optim as bnb_opt + + if isinstance(optimizer, (bnb_opt.AdamW, bnb_opt.AdamW32bit)): + try: + is_adaw = optimizer.optim_bits == 32 + except AttributeError: + is_adaw = optimizer.args.optim_bits == 32 + else: + is_adaw = False + + if is_adaw: + defaults["adamw_mode"] = True + + # For DeepSpeedCPUAdagrad + if compare_versions("deepspeed", ">=", "0.5.5"): + # Check if the optimizer is PyTorch's Adagrad. + is_ada = isinstance(optimizer, optim.Adagrad) + # If not, and bitsandbytes is available, + # # check if the optimizer is the 32-bit bitsandbytes Adagrad. + if is_bnb_available() and not is_ada: + import bitsandbytes.optim as bnb_opt + + if isinstance(optimizer, (bnb_opt.Adagrad, bnb_opt.Adagrad32bit)): + try: + is_ada = optimizer.optim_bits == 32 + except AttributeError: + is_ada = optimizer.args.optim_bits == 32 + if is_ada: + from deepspeed.ops.adagrad import DeepSpeedCPUAdagrad + + optimizer_class = DeepSpeedCPUAdagrad + + # For DeepSpeedCPULion + if is_bnb_available(min_version="0.38.0") and compare_versions("deepspeed", ">=", "0.11.0"): + from bitsandbytes.optim import Lion, Lion32bit + + if isinstance(optimizer, (Lion, Lion32bit)): + try: + is_bnb_32bits = optimizer.optim_bits == 32 + except AttributeError: + is_bnb_32bits = optimizer.args.optim_bits == 32 + if is_bnb_32bits: + from deepspeed.ops.lion import DeepSpeedCPULion + + optimizer_class = DeepSpeedCPULion + + return optimizer_class(optimizer.param_groups, **defaults) + + +def get_active_deepspeed_plugin(state): + """ + Returns the currently active DeepSpeedPlugin. + + Raises: + ValueError: If DeepSpeed was not enabled and this function is called. + """ + if state.distributed_type != DistributedType.DEEPSPEED: + raise ValueError( + "Couldn't retrieve the active `DeepSpeedPlugin` as none were enabled. " + "Please make sure that either `Accelerator` is configured for `deepspeed` " + "or make sure that the desired `DeepSpeedPlugin` has been enabled (`AcceleratorState().select_deepspeed_plugin(name)`) " + "before calling this function." + ) + if not isinstance(state.deepspeed_plugins, dict): + return state.deepspeed_plugins + return next(plugin for plugin in state.deepspeed_plugins.values() if plugin.selected) + + +class HfDeepSpeedConfig: + """ + This object contains a DeepSpeed configuration dictionary and can be quickly queried for things like zero stage. + + A `weakref` of this object is stored in the module's globals to be able to access the config from areas where + things like the Trainer object is not available (e.g. `from_pretrained` and `_get_resized_embeddings`). Therefore + it's important that this object remains alive while the program is still running. + + [`Trainer`] uses the `HfTrainerDeepSpeedConfig` subclass instead. That subclass has logic to sync the configuration + with values of [`TrainingArguments`] by replacing special placeholder values: `"auto"`. Without this special logic + the DeepSpeed configuration is not modified in any way. + + Args: + config_file_or_dict (`Union[str, Dict]`): path to DeepSpeed config file or dict. + + """ + + def __init__(self, config_file_or_dict): + if isinstance(config_file_or_dict, dict): + # Don't modify user's data should they want to reuse it (e.g. in tests), because once we + # modified it, it will not be accepted here again, since `auto` values would have been overridden + config = deepcopy(config_file_or_dict) + elif os.path.exists(config_file_or_dict): + with open(config_file_or_dict, encoding="utf-8") as f: + config = json.load(f) + else: + try: + try: + # First try parsing as JSON directly + config = json.loads(config_file_or_dict) + except json.JSONDecodeError: + # If that fails, try base64 decoding + config_decoded = base64.urlsafe_b64decode(config_file_or_dict).decode("utf-8") + config = json.loads(config_decoded) + except (UnicodeDecodeError, AttributeError, ValueError): + raise ValueError( + f"Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}" + ) + + self.config = config + + self.set_stage_and_offload() + + def set_stage_and_offload(self): + # zero stage - this is done as early as possible, before model is created, to allow + # ``is_deepspeed_zero3_enabled`` query and getting to the early deepspeed config object + # during ``zero.Init()`` which needs to know the dtype, and some other hparams. + self._stage = self.get_value("zero_optimization.stage", -1) + + # offload + self._offload = False + if self.is_zero2() or self.is_zero3(): + offload_devices_valid = set(["cpu", "nvme"]) + offload_devices = set( + [ + self.get_value("zero_optimization.offload_optimizer.device"), + self.get_value("zero_optimization.offload_param.device"), + ] + ) + if len(offload_devices & offload_devices_valid) > 0: + self._offload = True + + def find_config_node(self, ds_key_long): + config = self.config + + # find the config node of interest if it exists + nodes = ds_key_long.split(".") + ds_key = nodes.pop() + for node in nodes: + config = config.get(node) + if config is None: + return None, ds_key + + return config, ds_key + + def get_value(self, ds_key_long, default=None): + """ + Returns the set value or `default` if no value is set + """ + config, ds_key = self.find_config_node(ds_key_long) + if config is None: + return default + return config.get(ds_key, default) + + def del_config_sub_tree(self, ds_key_long, must_exist=False): + """ + Deletes a sub-section of the config file if it's found. + + Unless `must_exist` is `True` the section doesn't have to exist. + """ + config = self.config + + # find the config node of interest if it exists + nodes = ds_key_long.split(".") + for node in nodes: + parent_config = config + config = config.get(node) + if config is None: + if must_exist: + raise ValueError(f"Can't find {ds_key_long} entry in the config: {self.config}") + else: + return + + # if found remove it + if parent_config is not None: + parent_config.pop(node) + + def is_true(self, ds_key_long): + """ + Returns `True`/``False` only if the value is set, always `False` otherwise. So use this method to ask the very + specific question of whether the value is set to `True` (and it's not set to `False`` or isn't set). + + """ + value = self.get_value(ds_key_long) + return False if value is None else bool(value) + + def is_false(self, ds_key_long): + """ + Returns `True`/``False` only if the value is set, always `False` otherwise. So use this method to ask the very + specific question of whether the value is set to `False` (and it's not set to `True`` or isn't set). + """ + value = self.get_value(ds_key_long) + return False if value is None else not bool(value) + + def is_zero2(self): + return self._stage == 2 + + def is_zero3(self): + return self._stage == 3 + + def is_offload(self): + return self._offload + + +class DeepSpeedEngineWrapper: + """ + Internal wrapper for deepspeed.runtime.engine.DeepSpeedEngine. This is used to follow conventional training loop. + + Args: + engine (deepspeed.runtime.engine.DeepSpeedEngine): deepspeed engine to wrap + """ + + def __init__(self, engine): + self.engine = engine + + def backward(self, loss, sync_gradients=True, **kwargs): + # Set gradient accumulation boundary based on Accelerate's sync_gradients state + # This tells DeepSpeed whether this is the final micro-batch before gradient sync + self.engine.set_gradient_accumulation_boundary(is_boundary=sync_gradients) + + # runs backpropagation and handles mixed precision + self.engine.backward(loss, **kwargs) + + # Only perform step and related operations at gradient accumulation boundaries + if sync_gradients: + # Deepspeed's `engine.step` performs the following operations: + # - gradient accumulation check + # - gradient clipping + # - optimizer step + # - zero grad + # - checking overflow + # - lr_scheduler step (only if engine.lr_scheduler is not None) + self.engine.step() + # and this plugin overrides the above calls with no-ops when Accelerate runs under + # Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple + # training loop that works transparently under many training regimes. + + def get_global_grad_norm(self): + """Get the global gradient norm from DeepSpeed engine.""" + grad_norm = self.engine.get_global_grad_norm() + # Convert to scalar if it's a tensor + if hasattr(grad_norm, "item"): + return grad_norm.item() + return grad_norm + + +class DeepSpeedOptimizerWrapper(AcceleratedOptimizer): + """ + Internal wrapper around a deepspeed optimizer. + + Args: + optimizer (`torch.optim.optimizer.Optimizer`): + The optimizer to wrap. + """ + + def __init__(self, optimizer): + super().__init__(optimizer, device_placement=False, scaler=None) + self.__has_overflow__ = hasattr(self.optimizer, "overflow") + + def zero_grad(self, set_to_none=None): + pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed + + def step(self): + pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed + + @property + def step_was_skipped(self): + """Whether or not the optimizer step was done, or skipped because of gradient overflow.""" + if self.__has_overflow__: + return self.optimizer.overflow + return False + + +class DeepSpeedSchedulerWrapper(AcceleratedScheduler): + """ + Internal wrapper around a deepspeed scheduler. + + Args: + scheduler (`torch.optim.lr_scheduler.LambdaLR`): + The scheduler to wrap. + optimizers (one or a list of `torch.optim.Optimizer`): + """ + + def __init__(self, scheduler, optimizers): + super().__init__(scheduler, optimizers) + + def step(self): + pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed + + +class DummyOptim: + """ + Dummy optimizer presents model parameters or param groups, this is primarily used to follow conventional training + loop when optimizer config is specified in the deepspeed config file. + + Args: + lr (float): + Learning rate. + params (iterable): iterable of parameters to optimize or dicts defining + parameter groups + weight_decay (float): + Weight decay. + **kwargs (additional keyword arguments, *optional*): + Other arguments. + """ + + def __init__(self, params, lr=0.001, weight_decay=0, **kwargs): + self.params = params + self.lr = lr + self.weight_decay = weight_decay + self.kwargs = kwargs + + +class DummyScheduler: + """ + Dummy scheduler presents model parameters or param groups, this is primarily used to follow conventional training + loop when scheduler config is specified in the deepspeed config file. + + Args: + optimizer (`torch.optim.optimizer.Optimizer`): + The optimizer to wrap. + total_num_steps (int, *optional*): + Total number of steps. + warmup_num_steps (int, *optional*): + Number of steps for warmup. + lr_scheduler_callable (callable, *optional*): + A callable function that creates an LR Scheduler. It accepts only one argument `optimizer`. + **kwargs (additional keyword arguments, *optional*): + Other arguments. + """ + + def __init__(self, optimizer, total_num_steps=None, warmup_num_steps=0, lr_scheduler_callable=None, **kwargs): + self.optimizer = optimizer + self.total_num_steps = total_num_steps + self.warmup_num_steps = warmup_num_steps + self.lr_scheduler_callable = lr_scheduler_callable + self.kwargs = kwargs diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/environment.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/environment.py new file mode 100644 index 0000000000000000000000000000000000000000..c913702ef30290ed3d19c08a71213663297f32de --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/environment.py @@ -0,0 +1,421 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import math +import os +import platform +import subprocess +import sys +from contextlib import contextmanager +from dataclasses import dataclass, field +from functools import lru_cache, wraps +from shutil import which +from typing import Optional, Union + +import torch +from packaging.version import parse + + +logger = logging.getLogger(__name__) + + +def convert_dict_to_env_variables(current_env: dict): + """ + Verifies that all keys and values in `current_env` do not contain illegal keys or values, and returns a list of + strings as the result. + + Example: + ```python + >>> from accelerate.utils.environment import verify_env + + >>> env = {"ACCELERATE_DEBUG_MODE": "1", "BAD_ENV_NAME": ">> valid_env_items = verify_env(env) + >>> print(valid_env_items) + ["ACCELERATE_DEBUG_MODE=1\n", "OTHER_ENV=2\n"] + ``` + """ + forbidden_chars = [";", "\n", "<", ">", " "] + valid_env_items = [] + for key, value in current_env.items(): + if all(char not in (key + value) for char in forbidden_chars) and len(key) >= 1 and len(value) >= 1: + valid_env_items.append(f"{key}={value}\n") + else: + logger.warning(f"WARNING: Skipping {key}={value} as it contains forbidden characters or missing values.") + return valid_env_items + + +def str_to_bool(value, to_bool: bool = False) -> Union[int, bool]: + """ + Converts a string representation of truth to `True` (1) or `False` (0). + + True values are `y`, `yes`, `t`, `true`, `on`, and `1`; False value are `n`, `no`, `f`, `false`, `off`, and `0`; + """ + value = value.lower() + if value in ("y", "yes", "t", "true", "on", "1"): + return 1 if not to_bool else True + elif value in ("n", "no", "f", "false", "off", "0"): + return 0 if not to_bool else False + else: + raise ValueError(f"invalid truth value {value}") + + +def get_int_from_env(env_keys, default): + """Returns the first positive env value found in the `env_keys` list or the default.""" + for e in env_keys: + val = int(os.environ.get(e, -1)) + if val >= 0: + return val + return default + + +def parse_flag_from_env(key, default=False): + """Returns truthy value for `key` from the env if available else the default.""" + value = os.environ.get(key, str(default)) + return str_to_bool(value) == 1 # As its name indicates `str_to_bool` actually returns an int... + + +def parse_choice_from_env(key, default="no"): + value = os.environ.get(key, str(default)) + return value + + +def are_libraries_initialized(*library_names: str) -> list[str]: + """ + Checks if any of `library_names` are imported in the environment. Will return any names that are. + """ + return [lib_name for lib_name in library_names if lib_name in sys.modules.keys()] + + +def _nvidia_smi(): + """ + Returns the right nvidia-smi command based on the system. + """ + if platform.system() == "Windows": + # If platform is Windows and nvidia-smi can't be found in path + # try from systemd drive with default installation path + command = which("nvidia-smi") + if command is None: + command = f"{os.environ['systemdrive']}\\Program Files\\NVIDIA Corporation\\NVSMI\\nvidia-smi.exe" + else: + command = "nvidia-smi" + return command + + +def get_gpu_info(): + """ + Gets GPU count and names using `nvidia-smi` instead of torch to not initialize CUDA. + + Largely based on the `gputil` library. + """ + # Returns as list of `n` GPUs and their names + output = subprocess.check_output( + [_nvidia_smi(), "--query-gpu=count,name", "--format=csv,noheader"], universal_newlines=True + ) + output = output.strip() + gpus = output.split(os.linesep) + # Get names from output + gpu_count = len(gpus) + gpu_names = [gpu.split(",")[1].strip() for gpu in gpus] + return gpu_names, gpu_count + + +def get_driver_version(): + """ + Returns the driver version + + In the case of multiple GPUs, will return the first. + """ + output = subprocess.check_output( + [_nvidia_smi(), "--query-gpu=driver_version", "--format=csv,noheader"], universal_newlines=True + ) + output = output.strip() + return output.split(os.linesep)[0] + + +def check_cuda_p2p_ib_support(): + """ + Checks if the devices being used have issues with P2P and IB communications, namely any consumer GPU hardware after + the 3090. + + Noteably uses `nvidia-smi` instead of torch to not initialize CUDA. + """ + try: + device_names, device_count = get_gpu_info() + # As new consumer GPUs get released, add them to `unsupported_devices`` + unsupported_devices = {"RTX 40"} + if device_count > 1: + if any( + unsupported_device in device_name + for device_name in device_names + for unsupported_device in unsupported_devices + ): + # Check if they have the right driver version + acceptable_driver_version = "550.40.07" + current_driver_version = get_driver_version() + if parse(current_driver_version) < parse(acceptable_driver_version): + return False + return True + except Exception: + pass + return True + + +@lru_cache +def check_cuda_fp8_capability(): + """ + Checks if the current GPU available supports FP8. + + Notably might initialize `torch.cuda` to check. + """ + + try: + # try to get the compute capability from nvidia-smi + output = subprocess.check_output( + [_nvidia_smi(), "--query-gpu=compute_capability", "--format=csv,noheader"], universal_newlines=True + ) + output = output.strip() + # we take the first GPU's compute capability + compute_capability = tuple(map(int, output.split(os.linesep)[0].split("."))) + except Exception: + compute_capability = torch.cuda.get_device_capability() + + return compute_capability >= (8, 9) + + +@dataclass +class CPUInformation: + """ + Stores information about the CPU in a distributed environment. It contains the following attributes: + - rank: The rank of the current process. + - world_size: The total number of processes in the world. + - local_rank: The rank of the current process on the local node. + - local_world_size: The total number of processes on the local node. + """ + + rank: int = field(default=0, metadata={"help": "The rank of the current process."}) + world_size: int = field(default=1, metadata={"help": "The total number of processes in the world."}) + local_rank: int = field(default=0, metadata={"help": "The rank of the current process on the local node."}) + local_world_size: int = field(default=1, metadata={"help": "The total number of processes on the local node."}) + + +def get_cpu_distributed_information() -> CPUInformation: + """ + Returns various information about the environment in relation to CPU distributed training as a `CPUInformation` + dataclass. + """ + information = {} + information["rank"] = get_int_from_env(["RANK", "PMI_RANK", "OMPI_COMM_WORLD_RANK", "MV2_COMM_WORLD_RANK"], 0) + information["world_size"] = get_int_from_env( + ["WORLD_SIZE", "PMI_SIZE", "OMPI_COMM_WORLD_SIZE", "MV2_COMM_WORLD_SIZE"], 1 + ) + information["local_rank"] = get_int_from_env( + ["LOCAL_RANK", "MPI_LOCALRANKID", "OMPI_COMM_WORLD_LOCAL_RANK", "MV2_COMM_WORLD_LOCAL_RANK"], 0 + ) + information["local_world_size"] = get_int_from_env( + ["LOCAL_WORLD_SIZE", "MPI_LOCALNRANKS", "OMPI_COMM_WORLD_LOCAL_SIZE", "MV2_COMM_WORLD_LOCAL_SIZE"], + 1, + ) + return CPUInformation(**information) + + +def override_numa_affinity(local_process_index: int, verbose: Optional[bool] = None) -> None: + """ + Overrides whatever NUMA affinity is set for the current process. This is very taxing and requires recalculating the + affinity to set, ideally you should use `utils.environment.set_numa_affinity` instead. + + Args: + local_process_index (int): + The index of the current process on the current server. + verbose (bool, *optional*): + Whether to log out the assignment of each CPU. If `ACCELERATE_DEBUG_MODE` is enabled, will default to True. + """ + if verbose is None: + verbose = parse_flag_from_env("ACCELERATE_DEBUG_MODE", False) + if torch.cuda.is_available(): + from accelerate.utils import is_pynvml_available + + if not is_pynvml_available(): + raise ImportError( + "To set CPU affinity on CUDA GPUs the `pynvml` package must be available. (`pip install pynvml`)" + ) + import pynvml as nvml + + # The below code is based on https://github.com/NVIDIA/DeepLearningExamples/blob/master/TensorFlow2/LanguageModeling/BERT/gpu_affinity.py + nvml.nvmlInit() + num_elements = math.ceil(os.cpu_count() / 64) + handle = nvml.nvmlDeviceGetHandleByIndex(local_process_index) + affinity_string = "" + for j in nvml.nvmlDeviceGetCpuAffinity(handle, num_elements): + # assume nvml returns list of 64 bit ints + affinity_string = f"{j:064b}{affinity_string}" + affinity_list = [int(x) for x in affinity_string] + affinity_list.reverse() # so core 0 is the 0th element + affinity_to_set = [i for i, e in enumerate(affinity_list) if e != 0] + os.sched_setaffinity(0, affinity_to_set) + if verbose: + cpu_cores = os.sched_getaffinity(0) + logger.info(f"Assigning {len(cpu_cores)} cpu cores to process {local_process_index}: {cpu_cores}") + + +@lru_cache +def set_numa_affinity(local_process_index: int, verbose: Optional[bool] = None) -> None: + """ + Assigns the current process to a specific NUMA node. Ideally most efficient when having at least 2 cpus per node. + + This result is cached between calls. If you want to override it, please use + `accelerate.utils.environment.override_numa_afifnity`. + + Args: + local_process_index (int): + The index of the current process on the current server. + verbose (bool, *optional*): + Whether to print the new cpu cores assignment for each process. If `ACCELERATE_DEBUG_MODE` is enabled, will + default to True. + """ + override_numa_affinity(local_process_index=local_process_index, verbose=verbose) + + +@contextmanager +def clear_environment(): + """ + A context manager that will temporarily clear environment variables. + + When this context exits, the previous environment variables will be back. + + Example: + + ```python + >>> import os + >>> from accelerate.utils import clear_environment + + >>> os.environ["FOO"] = "bar" + >>> with clear_environment(): + ... print(os.environ) + ... os.environ["FOO"] = "new_bar" + ... print(os.environ["FOO"]) + {} + new_bar + + >>> print(os.environ["FOO"]) + bar + ``` + """ + _old_os_environ = os.environ.copy() + os.environ.clear() + + try: + yield + finally: + os.environ.clear() # clear any added keys, + os.environ.update(_old_os_environ) # then restore previous environment + + +@contextmanager +def patch_environment(**kwargs): + """ + A context manager that will add each keyword argument passed to `os.environ` and remove them when exiting. + + Will convert the values in `kwargs` to strings and upper-case all the keys. + + Example: + + ```python + >>> import os + >>> from accelerate.utils import patch_environment + + >>> with patch_environment(FOO="bar"): + ... print(os.environ["FOO"]) # prints "bar" + >>> print(os.environ["FOO"]) # raises KeyError + ``` + """ + existing_vars = {} + for key, value in kwargs.items(): + key = key.upper() + if key in os.environ: + existing_vars[key] = os.environ[key] + os.environ[key] = str(value) + + try: + yield + finally: + for key in kwargs: + key = key.upper() + if key in existing_vars: + # restore previous value + os.environ[key] = existing_vars[key] + else: + os.environ.pop(key, None) + + +def purge_accelerate_environment(func_or_cls): + """Decorator to clean up accelerate environment variables set by the decorated class or function. + + In some circumstances, calling certain classes or functions can result in accelerate env vars being set and not + being cleaned up afterwards. As an example, when calling: + + TrainingArguments(fp16=True, ...) + + The following env var will be set: + + ACCELERATE_MIXED_PRECISION=fp16 + + This can affect subsequent code, since the env var takes precedence over TrainingArguments(fp16=False). This is + especially relevant for unit testing, where we want to avoid the individual tests to have side effects on one + another. Decorate the unit test function or whole class with this decorator to ensure that after each test, the env + vars are cleaned up. This works for both unittest.TestCase and normal classes (pytest); it also works when + decorating the parent class. + + """ + prefix = "ACCELERATE_" + + @contextmanager + def env_var_context(): + # Store existing accelerate env vars + existing_vars = {k: v for k, v in os.environ.items() if k.startswith(prefix)} + try: + yield + finally: + # Restore original env vars or remove new ones + for key in [k for k in os.environ if k.startswith(prefix)]: + if key in existing_vars: + os.environ[key] = existing_vars[key] + else: + os.environ.pop(key, None) + + def wrap_function(func): + @wraps(func) + def wrapper(*args, **kwargs): + with env_var_context(): + return func(*args, **kwargs) + + wrapper._accelerate_is_purged_environment_wrapped = True + return wrapper + + if not isinstance(func_or_cls, type): + return wrap_function(func_or_cls) + + # Handle classes by wrapping test methods + def wrap_test_methods(test_class_instance): + for name in dir(test_class_instance): + if name.startswith("test"): + method = getattr(test_class_instance, name) + if callable(method) and not hasattr(method, "_accelerate_is_purged_environment_wrapped"): + setattr(test_class_instance, name, wrap_function(method)) + return test_class_instance + + # Handle inheritance + wrap_test_methods(func_or_cls) + func_or_cls.__init_subclass__ = classmethod(lambda cls, **kw: wrap_test_methods(cls)) + return func_or_cls diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/fsdp_utils.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/fsdp_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ef1ef7372ba9a366e2655ebdce7c2e10c22f3f8b --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/fsdp_utils.py @@ -0,0 +1,793 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import copy +import functools +import os +import shutil +import warnings +from collections import defaultdict +from contextlib import nullcontext +from pathlib import Path +from typing import Callable + +import torch + +from ..logging import get_logger +from .constants import FSDP_MODEL_NAME, OPTIMIZER_NAME, SAFE_WEIGHTS_NAME, WEIGHTS_NAME +from .dataclasses import get_module_class_from_name +from .modeling import get_non_persistent_buffers, is_peft_model +from .other import get_module_children_bottom_up, is_compiled_module, save +from .versions import is_torch_version + + +logger = get_logger(__name__) + + +def enable_fsdp_ram_efficient_loading(): + """ + Enables RAM efficient loading of Hugging Face models for FSDP in the environment. + """ + # Sets values for `transformers.modeling_utils.is_fsdp_enabled` + if "ACCELERATE_USE_FSDP" not in os.environ: + os.environ["ACCELERATE_USE_FSDP"] = "True" + os.environ["FSDP_CPU_RAM_EFFICIENT_LOADING"] = "True" + + +def disable_fsdp_ram_efficient_loading(): + """ + Disables RAM efficient loading of Hugging Face models for FSDP in the environment. + """ + os.environ["FSDP_CPU_RAM_EFFICIENT_LOADING"] = "False" + + +def _get_model_state_dict(model, adapter_only=False, sd_options=None): + if adapter_only and is_peft_model(model): + from peft import get_peft_model_state_dict + + return get_peft_model_state_dict(model, adapter_name=model.active_adapter) + + # Invariant: `sd_options` is not None only for FSDP2 + if sd_options is not None: + from torch.distributed.checkpoint.state_dict import get_model_state_dict + + return get_model_state_dict(model, options=sd_options) + else: + return model.state_dict() + + +def _set_model_state_dict(model, state_dict, adapter_only=False, sd_options=None): + if adapter_only and is_peft_model(model): + from peft import set_peft_model_state_dict + + return set_peft_model_state_dict(model, state_dict, adapter_name=model.active_adapter) + + # Invariant: `sd_options` is not None only for FSDP2 + if sd_options is not None: + from torch.distributed.checkpoint.state_dict import set_model_state_dict + + return set_model_state_dict(model, state_dict, options=sd_options) + else: + return model.load_state_dict(state_dict) + + +def _prepare_sd_options(fsdp_plugin): + sd_options = None + + # we use this only for FSDP2, as it requires torch >= 2.6.0 and this api requires torch >= 2.2.0 + if fsdp_plugin.fsdp_version == 2: + from torch.distributed.checkpoint.state_dict import StateDictOptions + from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType + + sd_options = StateDictOptions( + full_state_dict=fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT, + cpu_offload=getattr(fsdp_plugin.state_dict_config, "offload_to_cpu", False), + broadcast_from_rank0=getattr(fsdp_plugin.state_dict_config, "rank0_only", False), + ) + + return sd_options + + +def save_fsdp_model(fsdp_plugin, accelerator, model, output_dir, model_index=0, adapter_only=False): + # Note: We import here to reduce import time from general modules, and isolate outside dependencies + import torch.distributed.checkpoint as dist_cp + from torch.distributed.checkpoint.default_planner import DefaultSavePlanner + from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP + from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType + + os.makedirs(output_dir, exist_ok=True) + if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: + # FSDP raises error when single GPU is used with `offload_to_cpu=True` for FULL_STATE_DICT + # so, only enable it when num_processes>1 + is_multi_process = accelerator.num_processes > 1 + fsdp_plugin.state_dict_config.offload_to_cpu = is_multi_process + fsdp_plugin.state_dict_config.rank0_only = is_multi_process + + ctx = ( + FSDP.state_dict_type( + model, fsdp_plugin.state_dict_type, fsdp_plugin.state_dict_config, fsdp_plugin.optim_state_dict_config + ) + if fsdp_plugin.fsdp_version == 1 + else nullcontext() + ) + sd_options = _prepare_sd_options(fsdp_plugin) + + with ctx: + state_dict = _get_model_state_dict(model, adapter_only=adapter_only, sd_options=sd_options) + if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: + weights_name = f"{FSDP_MODEL_NAME}.bin" if model_index == 0 else f"{FSDP_MODEL_NAME}_{model_index}.bin" + output_model_file = os.path.join(output_dir, weights_name) + if accelerator.process_index == 0: + logger.info(f"Saving model to {output_model_file}") + torch.save(state_dict, output_model_file) + logger.info(f"Model saved to {output_model_file}") + # Invariant: `LOCAL_STATE_DICT` is never possible with `FSDP2` + elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: + weights_name = ( + f"{FSDP_MODEL_NAME}_rank{accelerator.process_index}.bin" + if model_index == 0 + else f"{FSDP_MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin" + ) + output_model_file = os.path.join(output_dir, weights_name) + logger.info(f"Saving model to {output_model_file}") + torch.save(state_dict, output_model_file) + logger.info(f"Model saved to {output_model_file}") + elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: + ckpt_dir = os.path.join(output_dir, f"{FSDP_MODEL_NAME}_{model_index}") + os.makedirs(ckpt_dir, exist_ok=True) + logger.info(f"Saving model to {ckpt_dir}") + state_dict = {"model": state_dict} + + dist_cp.save( + state_dict=state_dict, + storage_writer=dist_cp.FileSystemWriter(ckpt_dir), + planner=DefaultSavePlanner(), + ) + logger.info(f"Model saved to {ckpt_dir}") + + +def load_fsdp_model(fsdp_plugin, accelerator, model, input_dir, model_index=0, adapter_only=False): + # Note: We import here to reduce import time from general modules, and isolate outside dependencies + import torch.distributed.checkpoint as dist_cp + from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner + from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP + from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType + + accelerator.wait_for_everyone() + if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: + # FSDP raises error when single GPU is used with `offload_to_cpu=True` for FULL_STATE_DICT + # so, only enable it when num_processes>1 + is_multi_process = accelerator.num_processes > 1 + fsdp_plugin.state_dict_config.offload_to_cpu = is_multi_process + fsdp_plugin.state_dict_config.rank0_only = is_multi_process + + ctx = ( + FSDP.state_dict_type( + model, fsdp_plugin.state_dict_type, fsdp_plugin.state_dict_config, fsdp_plugin.optim_state_dict_config + ) + if fsdp_plugin.fsdp_version == 1 + else nullcontext() + ) + sd_options = _prepare_sd_options(fsdp_plugin) + with ctx: + if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: + if type(model) is not FSDP and accelerator.process_index != 0 and not accelerator.is_fsdp2: + if not fsdp_plugin.sync_module_states and fsdp_plugin.fsdp_version == 1: + raise ValueError( + "Set the `sync_module_states` flag to `True` so that model states are synced across processes when " + "initializing FSDP object" + ) + return + weights_name = f"{FSDP_MODEL_NAME}.bin" if model_index == 0 else f"{FSDP_MODEL_NAME}_{model_index}.bin" + input_model_file = os.path.join(input_dir, weights_name) + logger.info(f"Loading model from {input_model_file}") + # we want an empty state dict for FSDP2 as we use `broadcast_from_rank0` + load_model = not accelerator.is_fsdp2 or accelerator.is_main_process + if load_model: + state_dict = torch.load(input_model_file, weights_only=True) + else: + state_dict = {} + logger.info(f"Model loaded from {input_model_file}") + elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: + weights_name = ( + f"{FSDP_MODEL_NAME}_rank{accelerator.process_index}.bin" + if model_index == 0 + else f"{FSDP_MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin" + ) + input_model_file = os.path.join(input_dir, weights_name) + logger.info(f"Loading model from {input_model_file}") + state_dict = torch.load(input_model_file, weights_only=True) + logger.info(f"Model loaded from {input_model_file}") + elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: + ckpt_dir = ( + os.path.join(input_dir, f"{FSDP_MODEL_NAME}_{model_index}") + if f"{FSDP_MODEL_NAME}" not in input_dir + else input_dir + ) + logger.info(f"Loading model from {ckpt_dir}") + state_dict = {"model": _get_model_state_dict(model, adapter_only=adapter_only, sd_options=sd_options)} + dist_cp.load( + state_dict=state_dict, + storage_reader=dist_cp.FileSystemReader(ckpt_dir), + planner=DefaultLoadPlanner(), + ) + state_dict = state_dict["model"] + logger.info(f"Model loaded from {ckpt_dir}") + + load_result = _set_model_state_dict(model, state_dict, adapter_only=adapter_only, sd_options=sd_options) + return load_result + + +def save_fsdp_optimizer(fsdp_plugin, accelerator, optimizer, model, output_dir, optimizer_index=0): + # Note: We import here to reduce import time from general modules, and isolate outside dependencies + import torch.distributed.checkpoint as dist_cp + from torch.distributed.checkpoint.default_planner import DefaultSavePlanner + from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP + from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType + + os.makedirs(output_dir, exist_ok=True) + + ctx = ( + FSDP.state_dict_type( + model, fsdp_plugin.state_dict_type, fsdp_plugin.state_dict_config, fsdp_plugin.optim_state_dict_config + ) + if fsdp_plugin.fsdp_version == 1 + else nullcontext() + ) + + sd_options = _prepare_sd_options(fsdp_plugin) + + with ctx: + if fsdp_plugin.fsdp_version == 2: + from torch.distributed.checkpoint.state_dict import get_optimizer_state_dict + + optim_state = get_optimizer_state_dict(model, optimizer, options=sd_options) + else: + optim_state = FSDP.optim_state_dict(model, optimizer) + + if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: + if accelerator.process_index == 0: + optim_state_name = ( + f"{OPTIMIZER_NAME}.bin" if optimizer_index == 0 else f"{OPTIMIZER_NAME}_{optimizer_index}.bin" + ) + output_optimizer_file = os.path.join(output_dir, optim_state_name) + logger.info(f"Saving Optimizer state to {output_optimizer_file}") + torch.save(optim_state, output_optimizer_file) + logger.info(f"Optimizer state saved in {output_optimizer_file}") + else: + ckpt_dir = os.path.join(output_dir, f"{OPTIMIZER_NAME}_{optimizer_index}") + os.makedirs(ckpt_dir, exist_ok=True) + logger.info(f"Saving Optimizer state to {ckpt_dir}") + dist_cp.save( + state_dict={"optimizer": optim_state}, + storage_writer=dist_cp.FileSystemWriter(ckpt_dir), + planner=DefaultSavePlanner(), + ) + logger.info(f"Optimizer state saved in {ckpt_dir}") + + +def load_fsdp_optimizer(fsdp_plugin, accelerator, optimizer, model, input_dir, optimizer_index=0, adapter_only=False): + # Note: We import here to reduce import time from general modules, and isolate outside dependencies + import torch.distributed.checkpoint as dist_cp + from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP + from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType + + accelerator.wait_for_everyone() + ctx = ( + FSDP.state_dict_type( + model, fsdp_plugin.state_dict_type, fsdp_plugin.state_dict_config, fsdp_plugin.optim_state_dict_config + ) + if fsdp_plugin.fsdp_version == 1 + else nullcontext() + ) + sd_options = _prepare_sd_options(fsdp_plugin) + with ctx: + if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: + optim_state = None + if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only: + optimizer_name = ( + f"{OPTIMIZER_NAME}.bin" if optimizer_index == 0 else f"{OPTIMIZER_NAME}_{optimizer_index}.bin" + ) + input_optimizer_file = os.path.join(input_dir, optimizer_name) + logger.info(f"Loading Optimizer state from {input_optimizer_file}") + optim_state = torch.load(input_optimizer_file, weights_only=True) + logger.info(f"Optimizer state loaded from {input_optimizer_file}") + else: + ckpt_dir = ( + os.path.join(input_dir, f"{OPTIMIZER_NAME}_{optimizer_index}") + if f"{OPTIMIZER_NAME}" not in input_dir + else input_dir + ) + logger.info(f"Loading Optimizer from {ckpt_dir}") + optim_state = {"optimizer": optimizer.state_dict()} + dist_cp.load( + optim_state, + checkpoint_id=ckpt_dir, + storage_reader=dist_cp.FileSystemReader(ckpt_dir), + ) + optim_state = optim_state["optimizer"] + logger.info(f"Optimizer loaded from {ckpt_dir}") + + if fsdp_plugin.fsdp_version == 1: + flattened_osd = FSDP.optim_state_dict_to_load(model=model, optim=optimizer, optim_state_dict=optim_state) + optimizer.load_state_dict(flattened_osd) + else: + from torch.distributed.checkpoint.state_dict import set_optimizer_state_dict + + set_optimizer_state_dict(model, optimizer, optim_state, options=sd_options) + + +def _distributed_checkpoint_to_merged_weights(checkpoint_dir: str, save_path: str, safe_serialization: bool = True): + """ + Passthrough to `torch.distributed.checkpoint.format_utils.dcp_to_torch_save` + + Will save under `save_path` as either `model.safetensors` or `pytorch_model.bin`. + """ + # Note: We import here to reduce import time from general modules, and isolate outside dependencies + import torch.distributed.checkpoint as dist_cp + import torch.distributed.checkpoint.format_utils as dist_cp_format_utils + + state_dict = {} + save_path = Path(save_path) + save_path.mkdir(exist_ok=True) + dist_cp_format_utils._load_state_dict( + state_dict, + storage_reader=dist_cp.FileSystemReader(checkpoint_dir), + planner=dist_cp_format_utils._EmptyStateDictLoadPlanner(), + no_dist=True, + ) + save_path = save_path / SAFE_WEIGHTS_NAME if safe_serialization else save_path / WEIGHTS_NAME + + # To handle if state is a dict like {model: {...}} + if len(state_dict.keys()) == 1: + state_dict = state_dict[list(state_dict)[0]] + save(state_dict, save_path, safe_serialization=safe_serialization) + return save_path + + +def merge_fsdp_weights( + checkpoint_dir: str, output_path: str, safe_serialization: bool = True, remove_checkpoint_dir: bool = False +): + """ + Merge the weights from sharded FSDP model checkpoints into a single combined checkpoint. Should be used if + `SHARDED_STATE_DICT` was used for the model. Weights will be saved to `{output_path}/model.safetensors` if + `safe_serialization` else `pytorch_model.bin`. + + Note: this is a CPU-bound process. + + Args: + checkpoint_dir (`str`): + The directory containing the FSDP checkpoints (can be either the model or optimizer). + output_path (`str`): + The path to save the merged checkpoint. + safe_serialization (`bool`, *optional*, defaults to `True`): + Whether to save the merged weights with safetensors (recommended). + remove_checkpoint_dir (`bool`, *optional*, defaults to `False`): + Whether to remove the checkpoint directory after merging. + """ + checkpoint_dir = Path(checkpoint_dir) + from accelerate.state import PartialState + + if not is_torch_version(">=", "2.3.0"): + raise ValueError("`merge_fsdp_weights` requires PyTorch >= 2.3.0`") + + # Verify that the checkpoint directory exists + if not checkpoint_dir.exists(): + model_path_exists = (checkpoint_dir / "pytorch_model_fsdp_0").exists() + optimizer_path_exists = (checkpoint_dir / "optimizer_0").exists() + err = f"Tried to load from {checkpoint_dir} but couldn't find a valid metadata file." + if model_path_exists and optimizer_path_exists: + err += " However, potential model and optimizer checkpoint directories exist." + err += f"Please pass in either {checkpoint_dir}/pytorch_model_fsdp_0 or {checkpoint_dir}/optimizer_0" + err += "instead." + elif model_path_exists: + err += " However, a potential model checkpoint directory exists." + err += f"Please try passing in {checkpoint_dir}/pytorch_model_fsdp_0 instead." + elif optimizer_path_exists: + err += " However, a potential optimizer checkpoint directory exists." + err += f"Please try passing in {checkpoint_dir}/optimizer_0 instead." + raise ValueError(err) + + # To setup `save` to work + state = PartialState() + if state.is_main_process: + logger.info(f"Merging FSDP weights from {checkpoint_dir}") + save_path = _distributed_checkpoint_to_merged_weights(checkpoint_dir, output_path, safe_serialization) + logger.info(f"Successfully merged FSDP weights and saved to {save_path}") + if remove_checkpoint_dir: + logger.info(f"Removing old checkpoint directory {checkpoint_dir}") + shutil.rmtree(checkpoint_dir) + state.wait_for_everyone() + + +def ensure_weights_retied(param_init_fn, model: torch.nn.Module, device: torch.device): + _tied_names = getattr(model, "_tied_weights_keys", None) + if not _tied_names: + # if no tied names just passthrough + return param_init_fn + + # get map of parameter instances to params. + # - needed for replacement later + _tied_params = {} + for name in _tied_names: + name = name.split(".") + name, param_name = ".".join(name[:-1]), name[-1] + mod = model.get_submodule(name) + param = getattr(mod, param_name) + + _tied_params[id(param)] = None # placeholder for the param first + + # build param_init_fn for the case with tied params + def param_init_fn_tied_param(module: torch.nn.Module): + # track which params to tie + # - usually only 1, but for completeness consider > 1 + params_to_tie = defaultdict(list) + for n, param in module.named_parameters(recurse=False): + if id(param) in _tied_params: + params_to_tie[id(param)].append(n) + + # call the param init fn, which potentially re-allocates the + # parameters + module = param_init_fn(module) + + # search the parameters again and tie them up again + for id_key, _param_names in params_to_tie.items(): + for param_name in _param_names: + param = _tied_params[id_key] + if param is None: + # everything will be tied to the first time the + # param is observed + _tied_params[id_key] = getattr(module, param_name) + else: + setattr(module, param_name, param) # tie + + return module + + return param_init_fn_tied_param + + +def fsdp2_load_full_state_dict(accelerator, model: torch.nn.Module, full_sd: dict): + """ + Loads the full state dict (could be only on rank 0) into the sharded model. This is done by broadcasting the + parameters from rank 0 to all other ranks. This function modifies the model in-place. + + Args: + accelerator (`Accelerator`): The accelerator instance + model (`torch.nn.Module`): + The model to load the state dict into, expected to be on meta device or a VRAM spike can occur + full_sd (`dict`): The full state dict to load, can only be on rank 0 + """ + import torch.distributed as dist + from torch.distributed.tensor import distribute_tensor + + # Model was previously copied to meta device + meta_sharded_sd = model.state_dict() + sharded_sd = {} + + # Rank 0 distributes the full state dict to other ranks + def _infer_parameter_dtype(model, param_name, empty_param): + try: + old_param = model.get_parameter_or_buffer(param_name) + except AttributeError: + # Need this for LORA, as there some params are not *parameters* of sorts + base_param_name, local_param_name = param_name.rsplit(".", 1) + submodule = model.get_submodule(base_param_name) + old_param = getattr(submodule, local_param_name) + + is_torch_e4m3fn_available = hasattr(torch, "float8_e4m3fn") + casting_dtype = None + is_param_float8_e4m3fn = is_torch_e4m3fn_available and empty_param.dtype == torch.float8_e4m3fn + + if empty_param.dtype.is_floating_point and not is_param_float8_e4m3fn: + casting_dtype = old_param.dtype + + return old_param is not None and old_param.is_contiguous(), casting_dtype + + def _cast_and_contiguous(tensor, to_contiguous, dtype): + if dtype is not None: + tensor = tensor.to(dtype=dtype) + if to_contiguous: + tensor = tensor.contiguous() + return tensor + + if accelerator.is_main_process: + for (param_name, full_param), sharded_param in zip(full_sd.items(), meta_sharded_sd.values()): + device_mesh = sharded_param.device_mesh + full_param = full_param.detach().to(device_mesh.device_type) + dist.broadcast(full_param, src=0, group=device_mesh.get_group()) + sharded_tensor = distribute_tensor(full_param, device_mesh, sharded_param.placements) + to_contiguous, casting_dtype = _infer_parameter_dtype( + model, + param_name, + full_param, + ) + sharded_tensor = _cast_and_contiguous(sharded_tensor, to_contiguous, casting_dtype) + sharded_sd[param_name] = sharded_tensor + # We need this else to have a matching `broadcast` for all of the ranks, else we deadlock + else: + for param_name, sharded_param in meta_sharded_sd.items(): + device_mesh = sharded_param.device_mesh + full_tensor = torch.empty(sharded_param.size(), device=device_mesh.device_type, dtype=sharded_param.dtype) + dist.broadcast(full_tensor, src=0, group=device_mesh.get_group()) + sharded_tensor = distribute_tensor(full_tensor, device_mesh, sharded_param.placements) + to_contiguous, casting_dtype = _infer_parameter_dtype( + model, + param_name, + full_tensor, + ) + sharded_tensor = _cast_and_contiguous(sharded_tensor, to_contiguous, casting_dtype) + sharded_sd[param_name] = sharded_tensor + + # we set `assign=True` because our params are on meta device + model.load_state_dict(sharded_sd, assign=True) + return model + + +def fsdp2_switch_optimizer_parameters(optimizer: torch.optim.Optimizer, mapping: dict): + """ + Switches the parameters of the optimizer to new ones (sharded parameters in usual case). This function modifies the + optimizer in-place. + + Args: + optimizer (`torch.optim.Optimizer`): Optimizer instance which contains the original model parameters + mapping (`dict`): Mapping from the original parameter (specified by `data_ptr`) to the sharded parameter + + Raises: + KeyError: + If a parameter in the optimizer couldn't be switched to its sharded version. This should never happen and + indicates a bug. If we kept the original params instead of raising, the training wouldn't be numerically + correct and weights wouldn't get updated. + """ + from torch.distributed.tensor import DTensor + + accessor_mapping = {} + + accessor_mapping[DTensor] = "_local_tensor" + try: + for param_group in optimizer.param_groups: + param_group["params"] = [mapping[p.data_ptr] for p in param_group["params"]] + except KeyError: + # This shouldn't ever happen, but we want to fail here else training wouldn't be numerically correct + # This basically means that we're missing a mapping from the original parameter to the sharded parameter + raise KeyError( + "A parameter in the optimizer couldn't be switched to its sharded version. This breaks the training. Please raise an issue on GitHub." + ) + + +def fsdp2_apply_ac(accelerator, model: torch.nn.Module): + """ + Applies the activation checkpointing to the model. + + Args: + accelerator (`Accelerator`): The accelerator instance + model (`torch.nn.Module`): The model to apply the activation checkpointing to + + Returns: + `torch.nn.Module`: The model with the activation checkpointing applied + """ + + from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( + checkpoint_wrapper, + ) + + auto_wrap_policy_func = fsdp2_prepare_auto_wrap_policy(accelerator.state.fsdp_plugin, model) + + for layer_name, layer in get_module_children_bottom_up(model, return_fqns=True)[:-1]: + if len(layer_name.split(".")) > 1: + parent_name, child_name = layer_name.rsplit(".", 1) + else: + parent_name = None + child_name = layer_name + + parent_module = model.get_submodule(parent_name) if parent_name else model + if auto_wrap_policy_func(parent_module): + layer = checkpoint_wrapper(layer, preserve_rng_state=False) + parent_module.register_module(child_name, layer) + + return model + + +def fsdp2_prepare_model(accelerator, model: torch.nn.Module) -> torch.nn.Module: + """Prepares the model for FSDP2 in-place. Also returns the model to avoid misuse of the original model. + + Args: + accelerator (`Accelerator`): The accelerator instance + model (`torch.nn.Module`): The model to prepare + + Returns: + `torch.nn.Module`: Prepared model + """ + from torch.distributed.fsdp import FSDPModule, MixedPrecisionPolicy, fully_shard + + is_type_fsdp = isinstance(model, FSDPModule) or ( + is_compiled_module(model) and isinstance(model._orig_mod, FSDPModule) + ) + if is_type_fsdp: + return model + + fsdp2_plugin = accelerator.state.fsdp_plugin + + fsdp2_plugin.set_auto_wrap_policy(model) + + original_sd = model.state_dict() + mesh = getattr(accelerator, "torch_device_mesh", None) + + fsdp2_kwargs = { + "reshard_after_forward": fsdp2_plugin.reshard_after_forward, + "offload_policy": fsdp2_plugin.cpu_offload, + # `fully_shard` doesn't accept `None` in case of `MixedPrecisionPolicy` + "mp_policy": fsdp2_plugin.mixed_precision_policy or MixedPrecisionPolicy(), + "mesh": mesh[tuple(accelerator.parallelism_config.fsdp_dim_names)] if mesh is not None else None, + } + + model_has_params4bit = False + for name, param in model.named_parameters(): + # this is a temporary fix whereby loading models with bnb params cannot be moved from + # GPU to a meta device due with FSDP2 because torch operations don't return the original class type + # bypassing the move to meta will still cause the VRAM spike, but at least it still will load + if param.__class__.__name__ == "Params4bit": + model_has_params4bit = True + break + + if fsdp2_plugin.cpu_ram_efficient_loading and not model_has_params4bit: + # Context: `fully_shard` moves the model to GPU if it was on CPU, however it can also be on `meta` and then it stays there even after `fully_shard` + # For this reason, we need to move the model to `meta` device, as then sharding happens on `meta` device + # If we kept the model on CPU (`cpu_ram_efficient_loading` has model be on CPU on all ranks, though non-main ranks only have `torch.emtpy`), `fully_shard` would move it to GPU + # Afterwards, when we call `fsdp2_load_full_state_dict`, us creating the state_dict would result into briefly having two copies of model state_dict on the GPU -> VRAM spike + + # We need to keep the original non-persistent buffers, as those MAY not be in the state_dict, resulting in them staying on meta device + # Also, these buffers aren't getting sharded by default + # We get the FQNs of all non-persistent buffers, to re-register them after + non_persistent_buffer_fqns = get_non_persistent_buffers(model, recurse=True, fqns=True) + original_non_persistent_buffers = copy.deepcopy( + {k: v for k, v in model.named_buffers() if k in non_persistent_buffer_fqns} + ) + # We move the model to meta device, as then sharding happens on meta device + model = model.to(torch.device("meta")) + # We need to re-tie the weights, not exactly sure why, but if we don't do this, reference to `lm_head/embed_tokens` stay hanging -> more VRAM usage + # We assume `transformers` models have a `tie_weights` method if they support it + if hasattr(model, "tie_weights"): + model.tie_weights() + + auto_wrap_policy_func = fsdp2_prepare_auto_wrap_policy(fsdp2_plugin, model) + if auto_wrap_policy_func is not None: + # We skip the model itself, as that one is always wrapped + for module in get_module_children_bottom_up(model)[:-1]: + if auto_wrap_policy_func(module) and not isinstance(module, FSDPModule): + fully_shard(module, **fsdp2_kwargs) + + if not isinstance(model, FSDPModule): + fully_shard(model, **fsdp2_kwargs) + + if fsdp2_plugin.cpu_ram_efficient_loading: + # If `cpu_ram_efficient_loading` is enabled, only rank 0 loads the weights + # Other ranks have an empty model on `meta` device, so we need to distribute the weights properly + fsdp2_load_full_state_dict(accelerator, model, original_sd) + + if fsdp2_plugin.cpu_ram_efficient_loading and not model_has_params4bit: + # We re-register the buffers, as they may not be in the state_dict + for fqn, buffer_tensor in original_non_persistent_buffers.items(): + buffer_tensor = buffer_tensor.to(accelerator.device) + + if "." in fqn: + parent_fqn, local_buffer_name = fqn.rsplit(".", 1) + parent_module = model.get_submodule(parent_fqn) + else: + local_buffer_name = fqn + parent_module = model + + parent_module.register_buffer(local_buffer_name, buffer_tensor, persistent=False) + + # We need to tie the weights again, as call to `load_full_state_dict` breaks the tie + # Needs to be called both here and above + # removing this call makes the have slightly different loss + # removing the call above leads to extra memory usage as explained in the comment above + if hasattr(model, "tie_weights"): + model.tie_weights() + + # There is no `dtype` attribution for nn.Module + # Set it to None if it doesn't exist and do the upcast always + model_dtype = getattr(model, "dtype", None) + if accelerator.mixed_precision != "no" and (model_dtype is None or model_dtype != torch.float32): + # We upcast the model according to `deepspeed`'s implementation + # More info about this can be found in `accelerator.py:prepare_model`s FSDP1 section + model = model.to(torch.float32) + if accelerator.is_main_process: + # TODO(siro1): Add a warning for each parameter that was upcasted + warnings.warn( + "FSDP upcast of low precision parameters to fp32 (since mixed_precision != 'no') may affect the precision of model checkpoints." + ) + return model + + +def fsdp2_prepare_auto_wrap_policy(fsdp2_plugin, model: torch.nn.Module) -> Callable[[torch.nn.Module], bool]: + """Prepares the auto wrap policy based on its type, done to mimic the behaviour of FSDP1 auto wrap policy. + + Args: + fsdp2_plugin (`FullyShardedDataParallelPlugin`): + Instance of `FullyShardedDataParallelPlugin` containing the configuration options + auto_wrap_policy_type (`str`): + Either `transformer` or `size` + model (`torch.nn.Module`): + The model to wrap + + Returns: + `Callable[[torch.nn.Module], bool]`: + The auto wrap policy function to be applied to the model + """ + from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy, transformer_auto_wrap_policy + + fn = fsdp2_plugin.auto_wrap_policy + + if isinstance(fn, functools.partial): + fn = fn.func + + if fn is transformer_auto_wrap_policy: + no_split_modules = getattr(model, "_no_split_modules", None) + if no_split_modules is None: + no_split_modules = [] + transformer_cls_names_to_wrap = list(no_split_modules) + if fsdp2_plugin.transformer_cls_names_to_wrap is not None: + transformer_cls_names_to_wrap = fsdp2_plugin.transformer_cls_names_to_wrap + transformer_cls_to_wrap = set() + + for layer_class in transformer_cls_names_to_wrap: + transformer_cls = get_module_class_from_name(model, layer_class) + if transformer_cls is None: + raise ValueError(f"Could not find the transformer layer class {layer_class} in the model.") + transformer_cls_to_wrap.add(transformer_cls) + + def policy(module: torch.nn.Module) -> bool: + if fsdp2_plugin.transformer_cls_names_to_wrap is None: + return False + return isinstance(module, tuple(transformer_cls_to_wrap)) + + elif fn is size_based_auto_wrap_policy: + + def policy(module: torch.nn.Module) -> bool: + module_num_params = sum(p.numel() for p in module.parameters()) + return module_num_params > fsdp2_plugin.min_num_params + else: + return None + + return policy + + +def get_fsdp2_grad_scaler(**kwargs): + """ + Returns a `GradScaler` for FSDP2, as the current implementation of `get_grad_scaler` doesn't accept other args. We + need this as current `get_grad_scaler` accepts only `distributed_type` as arg, which doesn't differentiate between + FSDP1 and FSDP2 + """ + from torch.amp.grad_scaler import GradScaler + + return GradScaler(**kwargs) + + +def fsdp2_canonicalize_names(named_params: dict) -> dict: + """Removes parameter name modifiers in order to map them back to their original names. + + See huggingface/accelerate#3554 for more context. + + Args: + named_params (`dict`): The named parameters dictionary to canonicalize. + + Returns: + `dict`: The canonicalized named parameters dictionary + """ + named_params = {k.replace("._checkpoint_wrapped_module", ""): v for k, v in named_params.items()} + named_params = { + k.replace("_orig_mod.", "") if k.startswith("_orig_mod.") else k: v for k, v in named_params.items() + } + named_params = {k.replace("._orig_mod", ""): v for k, v in named_params.items()} + return named_params diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/imports.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/imports.py new file mode 100644 index 0000000000000000000000000000000000000000..a919827994824cdbc745acac83f03e501c8688f9 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/imports.py @@ -0,0 +1,551 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import importlib +import importlib.metadata +import os +import sys +import warnings +from functools import lru_cache, wraps + +import torch +from packaging import version +from packaging.version import parse + +from .environment import parse_flag_from_env, patch_environment, str_to_bool +from .versions import compare_versions, is_torch_version + + +# Try to run Torch native job in an environment with TorchXLA installed by setting this value to 0. +USE_TORCH_XLA = parse_flag_from_env("USE_TORCH_XLA", default=True) + +_torch_xla_available = False +if USE_TORCH_XLA: + try: + import torch_xla.core.xla_model as xm # noqa: F401 + import torch_xla.runtime + + _torch_xla_available = True + except ImportError: + pass + +# Keep it for is_tpu_available. It will be removed along with is_tpu_available. +_tpu_available = _torch_xla_available + +# Cache this result has it's a C FFI call which can be pretty time-consuming +_torch_distributed_available = torch.distributed.is_available() + + +def _is_package_available(pkg_name, metadata_name=None): + # Check we're not importing a "pkg_name" directory somewhere but the actual library by trying to grab the version + package_exists = importlib.util.find_spec(pkg_name) is not None + if package_exists: + try: + # Some libraries have different names in the metadata + _ = importlib.metadata.metadata(pkg_name if metadata_name is None else metadata_name) + return True + except importlib.metadata.PackageNotFoundError: + return False + + +def is_torch_distributed_available() -> bool: + return _torch_distributed_available + + +def is_xccl_available(): + if is_torch_version(">=", "2.7.0"): + return torch.distributed.distributed_c10d.is_xccl_available() + if is_ipex_available(): + return False + return False + + +def is_ccl_available(): + try: + pass + except ImportError: + print( + "Intel(R) oneCCL Bindings for PyTorch* is required to run DDP on Intel(R) XPUs, but it is not" + " detected. If you see \"ValueError: Invalid backend: 'ccl'\" error, please install Intel(R) oneCCL" + " Bindings for PyTorch*." + ) + return importlib.util.find_spec("oneccl_bindings_for_pytorch") is not None + + +def get_ccl_version(): + return importlib.metadata.version("oneccl_bind_pt") + + +def is_import_timer_available(): + return _is_package_available("import_timer") + + +def is_pynvml_available(): + return _is_package_available("pynvml") or _is_package_available("pynvml", "nvidia-ml-py") + + +def is_pytest_available(): + return _is_package_available("pytest") + + +def is_msamp_available(): + return _is_package_available("msamp", "ms-amp") + + +def is_schedulefree_available(): + return _is_package_available("schedulefree") + + +def is_transformer_engine_available(): + if is_hpu_available(): + return _is_package_available("intel_transformer_engine", "intel-transformer-engine") + else: + return _is_package_available("transformer_engine", "transformer-engine") + + +def is_lomo_available(): + return _is_package_available("lomo_optim") + + +def is_cuda_available(): + """ + Checks if `cuda` is available via an `nvml-based` check which won't trigger the drivers and leave cuda + uninitialized. + """ + with patch_environment(PYTORCH_NVML_BASED_CUDA_CHECK="1"): + available = torch.cuda.is_available() + + return available + + +@lru_cache +def is_torch_xla_available(check_is_tpu=False, check_is_gpu=False): + """ + Check if `torch_xla` is available. To train a native pytorch job in an environment with torch xla installed, set + the USE_TORCH_XLA to false. + """ + assert not (check_is_tpu and check_is_gpu), "The check_is_tpu and check_is_gpu cannot both be true." + + if not _torch_xla_available: + return False + elif check_is_gpu: + return torch_xla.runtime.device_type() in ["GPU", "CUDA"] + elif check_is_tpu: + return torch_xla.runtime.device_type() == "TPU" + + return True + + +def is_torchao_available(): + package_exists = _is_package_available("torchao") + if package_exists: + torchao_version = version.parse(importlib.metadata.version("torchao")) + return compare_versions(torchao_version, ">=", "0.6.1") + return False + + +def is_deepspeed_available(): + return _is_package_available("deepspeed") + + +def is_pippy_available(): + return is_torch_version(">=", "2.4.0") + + +def is_bf16_available(ignore_tpu=False): + "Checks if bf16 is supported, optionally ignoring the TPU" + if is_torch_xla_available(check_is_tpu=True): + return not ignore_tpu + if is_cuda_available(): + return torch.cuda.is_bf16_supported() + if is_mlu_available(): + return torch.mlu.is_bf16_supported() + if is_xpu_available(): + return torch.xpu.is_bf16_supported() + if is_mps_available(): + return False + return True + + +def is_fp16_available(): + "Checks if fp16 is supported" + if is_habana_gaudi1(): + return False + + return True + + +def is_fp8_available(): + "Checks if fp8 is supported" + return is_msamp_available() or is_transformer_engine_available() or is_torchao_available() + + +def is_4bit_bnb_available(): + package_exists = _is_package_available("bitsandbytes") + if package_exists: + bnb_version = version.parse(importlib.metadata.version("bitsandbytes")) + return compare_versions(bnb_version, ">=", "0.39.0") + return False + + +def is_8bit_bnb_available(): + package_exists = _is_package_available("bitsandbytes") + if package_exists: + bnb_version = version.parse(importlib.metadata.version("bitsandbytes")) + return compare_versions(bnb_version, ">=", "0.37.2") + return False + + +def is_bnb_available(min_version=None): + package_exists = _is_package_available("bitsandbytes") + if package_exists and min_version is not None: + bnb_version = version.parse(importlib.metadata.version("bitsandbytes")) + return compare_versions(bnb_version, ">=", min_version) + else: + return package_exists + + +def is_bitsandbytes_multi_backend_available(): + if not is_bnb_available(): + return False + import bitsandbytes as bnb + + return "multi_backend" in getattr(bnb, "features", set()) + + +def is_torchvision_available(): + return _is_package_available("torchvision") + + +def is_megatron_lm_available(): + if str_to_bool(os.environ.get("ACCELERATE_USE_MEGATRON_LM", "False")) == 1: + if importlib.util.find_spec("megatron") is not None: + try: + megatron_version = parse(importlib.metadata.version("megatron-core")) + if compare_versions(megatron_version, ">=", "0.8.0"): + return importlib.util.find_spec(".training", "megatron") + except Exception as e: + warnings.warn(f"Parse Megatron version failed. Exception:{e}") + return False + + +def is_transformers_available(): + return _is_package_available("transformers") + + +def is_datasets_available(): + return _is_package_available("datasets") + + +def is_peft_available(): + return _is_package_available("peft") + + +def is_timm_available(): + return _is_package_available("timm") + + +def is_triton_available(): + if is_xpu_available(): + return _is_package_available("triton", "pytorch-triton-xpu") + return _is_package_available("triton") + + +def is_aim_available(): + package_exists = _is_package_available("aim") + if package_exists: + aim_version = version.parse(importlib.metadata.version("aim")) + return compare_versions(aim_version, "<", "4.0.0") + return False + + +def is_tensorboard_available(): + return _is_package_available("tensorboard") or _is_package_available("tensorboardX") + + +def is_wandb_available(): + return _is_package_available("wandb") + + +def is_comet_ml_available(): + return _is_package_available("comet_ml") + + +def is_swanlab_available(): + return _is_package_available("swanlab") + + +def is_trackio_available(): + return sys.version_info >= (3, 10) and _is_package_available("trackio") + + +def is_boto3_available(): + return _is_package_available("boto3") + + +def is_rich_available(): + if _is_package_available("rich"): + return parse_flag_from_env("ACCELERATE_ENABLE_RICH", False) + return False + + +def is_sagemaker_available(): + return _is_package_available("sagemaker") + + +def is_tqdm_available(): + return _is_package_available("tqdm") + + +def is_clearml_available(): + return _is_package_available("clearml") + + +def is_pandas_available(): + return _is_package_available("pandas") + + +def is_matplotlib_available(): + return _is_package_available("matplotlib") + + +def is_mlflow_available(): + if _is_package_available("mlflow"): + return True + + if importlib.util.find_spec("mlflow") is not None: + try: + _ = importlib.metadata.metadata("mlflow-skinny") + return True + except importlib.metadata.PackageNotFoundError: + return False + return False + + +def is_mps_available(min_version="1.12"): + "Checks if MPS device is available. The minimum version required is 1.12." + # With torch 1.12, you can use torch.backends.mps + # With torch 2.0.0, you can use torch.mps + return is_torch_version(">=", min_version) and torch.backends.mps.is_available() and torch.backends.mps.is_built() + + +def is_ipex_available(): + "Checks if ipex is installed." + + def get_major_and_minor_from_version(full_version): + return str(version.parse(full_version).major) + "." + str(version.parse(full_version).minor) + + _torch_version = importlib.metadata.version("torch") + if importlib.util.find_spec("intel_extension_for_pytorch") is None: + return False + _ipex_version = "N/A" + try: + _ipex_version = importlib.metadata.version("intel_extension_for_pytorch") + except importlib.metadata.PackageNotFoundError: + return False + torch_major_and_minor = get_major_and_minor_from_version(_torch_version) + ipex_major_and_minor = get_major_and_minor_from_version(_ipex_version) + if torch_major_and_minor != ipex_major_and_minor: + warnings.warn( + f"Intel Extension for PyTorch {ipex_major_and_minor} needs to work with PyTorch {ipex_major_and_minor}.*," + f" but PyTorch {_torch_version} is found. Please switch to the matching version and run again." + ) + return False + return True + + +@lru_cache +def is_mlu_available(check_device=False): + """ + Checks if `mlu` is available via an `cndev-based` check which won't trigger the drivers and leave mlu + uninitialized. + """ + if importlib.util.find_spec("torch_mlu") is None: + return False + + import torch_mlu # noqa: F401 + + with patch_environment(PYTORCH_CNDEV_BASED_MLU_CHECK="1"): + available = torch.mlu.is_available() + + return available + + +@lru_cache +def is_musa_available(check_device=False): + "Checks if `torch_musa` is installed and potentially if a MUSA is in the environment" + if importlib.util.find_spec("torch_musa") is None: + return False + + import torch_musa # noqa: F401 + + if check_device: + try: + # Will raise a RuntimeError if no MUSA is found + _ = torch.musa.device_count() + return torch.musa.is_available() + except RuntimeError: + return False + return hasattr(torch, "musa") and torch.musa.is_available() + + +@lru_cache +def is_npu_available(check_device=False): + "Checks if `torch_npu` is installed and potentially if a NPU is in the environment" + if importlib.util.find_spec("torch_npu") is None: + return False + + import torch_npu # noqa: F401 + + if check_device: + try: + # Will raise a RuntimeError if no NPU is found + _ = torch.npu.device_count() + return torch.npu.is_available() + except RuntimeError: + return False + return hasattr(torch, "npu") and torch.npu.is_available() + + +@lru_cache +def is_sdaa_available(check_device=False): + "Checks if `torch_sdaa` is installed and potentially if a SDAA is in the environment" + if importlib.util.find_spec("torch_sdaa") is None: + return False + + import torch_sdaa # noqa: F401 + + if check_device: + try: + # Will raise a RuntimeError if no NPU is found + _ = torch.sdaa.device_count() + return torch.sdaa.is_available() + except RuntimeError: + return False + return hasattr(torch, "sdaa") and torch.sdaa.is_available() + + +@lru_cache +def is_hpu_available(init_hccl=False): + "Checks if `torch.hpu` is installed and potentially if a HPU is in the environment" + if ( + importlib.util.find_spec("habana_frameworks") is None + or importlib.util.find_spec("habana_frameworks.torch") is None + ): + return False + + import habana_frameworks.torch # noqa: F401 + + if init_hccl: + import habana_frameworks.torch.distributed.hccl as hccl # noqa: F401 + + return hasattr(torch, "hpu") and torch.hpu.is_available() + + +def is_habana_gaudi1(): + if is_hpu_available(): + import habana_frameworks.torch.utils.experimental as htexp # noqa: F401 + + if htexp._get_device_type() == htexp.synDeviceType.synDeviceGaudi: + return True + + return False + + +@lru_cache +def is_xpu_available(check_device=False): + """ + Checks if XPU acceleration is available either via `intel_extension_for_pytorch` or via stock PyTorch (>=2.4) and + potentially if a XPU is in the environment + """ + + if is_ipex_available(): + import intel_extension_for_pytorch # noqa: F401 + else: + if is_torch_version("<=", "2.3"): + return False + + if check_device: + try: + # Will raise a RuntimeError if no XPU is found + _ = torch.xpu.device_count() + return torch.xpu.is_available() + except RuntimeError: + return False + return hasattr(torch, "xpu") and torch.xpu.is_available() + + +def is_dvclive_available(): + return _is_package_available("dvclive") + + +def is_torchdata_available(): + return _is_package_available("torchdata") + + +# TODO: Remove this function once stateful_dataloader is a stable feature in torchdata. +def is_torchdata_stateful_dataloader_available(): + package_exists = _is_package_available("torchdata") + if package_exists: + torchdata_version = version.parse(importlib.metadata.version("torchdata")) + return compare_versions(torchdata_version, ">=", "0.8.0") + return False + + +def torchao_required(func): + """ + A decorator that ensures the decorated function is only called when torchao is available. + """ + + @wraps(func) + def wrapper(*args, **kwargs): + if not is_torchao_available(): + raise ImportError( + "`torchao` is not available, please install it before calling this function via `pip install torchao`." + ) + return func(*args, **kwargs) + + return wrapper + + +# TODO: Rework this into `utils.deepspeed` and migrate the "core" chunks into `accelerate.deepspeed` +def deepspeed_required(func): + """ + A decorator that ensures the decorated function is only called when deepspeed is enabled. + """ + + @wraps(func) + def wrapper(*args, **kwargs): + from accelerate.state import AcceleratorState + from accelerate.utils.dataclasses import DistributedType + + if AcceleratorState._shared_state != {} and AcceleratorState().distributed_type != DistributedType.DEEPSPEED: + raise ValueError( + "DeepSpeed is not enabled, please make sure that an `Accelerator` is configured for `deepspeed` " + "before calling this function." + ) + return func(*args, **kwargs) + + return wrapper + + +def is_weights_only_available(): + # Weights only with allowlist was added in 2.4.0 + # ref: https://github.com/pytorch/pytorch/pull/124331 + return is_torch_version(">=", "2.4.0") + + +def is_numpy_available(min_version="1.25.0"): + numpy_version = parse(importlib.metadata.version("numpy")) + return compare_versions(numpy_version, ">=", min_version) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/launch.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..020c0e820e5554d4a5f80f2a86b7e5315bc8d06a --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/launch.py @@ -0,0 +1,760 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import os +import subprocess +import sys +import warnings +from ast import literal_eval +from shutil import which +from typing import Any + +import torch + +from ..commands.config.config_args import SageMakerConfig +from ..utils import ( + DynamoBackend, + PrecisionType, + is_ccl_available, + is_fp8_available, + is_hpu_available, + is_ipex_available, + is_mlu_available, + is_musa_available, + is_npu_available, + is_sdaa_available, + is_torch_xla_available, + is_xpu_available, +) +from ..utils.constants import DEEPSPEED_MULTINODE_LAUNCHERS +from ..utils.other import get_free_port, is_port_in_use, merge_dicts +from ..utils.versions import compare_versions +from .dataclasses import DistributedType, SageMakerDistributedType + + +def _filter_args(args, parser, default_args=[]): + """ + Filters out all `accelerate` specific args + """ + new_args, _ = parser.parse_known_args(default_args) + for key, value in vars(args).items(): + if key in vars(new_args).keys(): + setattr(new_args, key, value) + return new_args + + +def _get_mpirun_args(): + """ + Determines the executable and argument names for mpirun, based on the type of install. The supported MPI programs + are: OpenMPI, Intel MPI, or MVAPICH. + + Returns: Program name and arg names for hostfile, num processes, and processes per node + """ + # Find the MPI program name + mpi_apps = [x for x in ["mpirun", "mpiexec"] if which(x)] + + if len(mpi_apps) == 0: + raise OSError("mpirun or mpiexec were not found. Ensure that Intel MPI, Open MPI, or MVAPICH are installed.") + + # Call the app with the --version flag to determine which MPI app is installed + mpi_app = mpi_apps[0] + mpirun_version = subprocess.check_output([mpi_app, "--version"]) + + if b"Open MPI" in mpirun_version: + return mpi_app, "--hostfile", "-n", "--npernode", "--bind-to" + else: + # Intel MPI and MVAPICH both use the same arg names + return mpi_app, "-f", "-n", "-ppn", "" + + +def setup_fp8_env(args: argparse.Namespace, current_env: dict[str, str]): + """ + Setup the FP8 environment variables. + """ + prefix = "ACCELERATE_" + for arg in vars(args): + if arg.startswith("fp8_"): + value = getattr(args, arg) + if value is not None: + if arg == "fp8_override_linear_precision": + current_env[prefix + "FP8_OVERRIDE_FPROP"] = str(value[0]) + current_env[prefix + "FP8_OVERRIDE_DGRAD"] = str(value[1]) + current_env[prefix + "FP8_OVERRIDE_WGRAD"] = str(value[2]) + else: + current_env[f"{prefix}{arg.upper()}"] = str(getattr(args, arg)) + return current_env + + +def prepare_simple_launcher_cmd_env(args: argparse.Namespace) -> tuple[list[str], dict[str, str]]: + """ + Prepares and returns the command list and an environment with the correct simple launcher environment variables. + """ + cmd = [] + if args.no_python and args.module: + raise ValueError("--module and --no_python cannot be used together") + + num_processes = getattr(args, "num_processes", None) + num_machines = args.num_machines + if args.mpirun_hostfile is not None: + mpi_app_name, hostfile_arg, num_proc_arg, proc_per_node_arg, bind_to_arg = _get_mpirun_args() + bind_to = getattr(args, "bind-to", "socket") + nproc_per_node = str(num_processes // num_machines) if num_processes and num_machines else "1" + cmd += [ + mpi_app_name, + hostfile_arg, + args.mpirun_hostfile, + proc_per_node_arg, + nproc_per_node, + ] + if num_processes: + cmd += [num_proc_arg, str(num_processes)] + if bind_to_arg: + cmd += [bind_to_arg, bind_to] + if not args.no_python: + cmd.append(sys.executable) + if args.module: + cmd.append("-m") + cmd.append(args.training_script) + cmd.extend(args.training_script_args) + + current_env = os.environ.copy() + current_env["ACCELERATE_USE_CPU"] = str(args.cpu or args.use_cpu) + if args.debug: + current_env["ACCELERATE_DEBUG_MODE"] = "true" + if args.gpu_ids != "all" and args.gpu_ids is not None: + if is_xpu_available(): + current_env["ZE_AFFINITY_MASK"] = args.gpu_ids + elif is_mlu_available(): + current_env["MLU_VISIBLE_DEVICES"] = args.gpu_ids + elif is_sdaa_available(): + current_env["SDAA_VISIBLE_DEVICES"] = args.gpu_ids + elif is_musa_available(): + current_env["MUSA_VISIBLE_DEVICES"] = args.gpu_ids + elif is_npu_available(): + current_env["ASCEND_RT_VISIBLE_DEVICES"] = args.gpu_ids + elif is_hpu_available(): + current_env["HABANA_VISIBLE_MODULES"] = args.gpu_ids + else: + current_env["CUDA_VISIBLE_DEVICES"] = args.gpu_ids + if num_machines > 1: + assert args.main_process_ip is not None, ( + "When using multiple machines, you need to specify the main process IP." + ) + assert args.main_process_port is not None, ( + "When using multiple machines, you need to specify the main process port." + ) + + ccl_worker_count = getattr(args, "mpirun_ccl", 0) if is_ccl_available() else 0 + if (num_processes is not None and num_processes > 1) or num_machines > 1: + current_env["MASTER_ADDR"] = args.main_process_ip if args.main_process_ip is not None else "127.0.0.1" + current_env["MASTER_PORT"] = str(args.main_process_port) if args.main_process_port is not None else "29500" + current_env["CCL_WORKER_COUNT"] = str(ccl_worker_count) + if current_env["ACCELERATE_USE_CPU"]: + current_env["KMP_AFFINITY"] = "granularity=fine,compact,1,0" + current_env["KMP_BLOCKTIME"] = str(1) + + try: + mixed_precision = PrecisionType(args.mixed_precision.lower()) + except ValueError: + raise ValueError( + f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}." + ) + + current_env["ACCELERATE_MIXED_PRECISION"] = str(mixed_precision) + if args.mixed_precision.lower() == "fp8": + if not is_fp8_available(): + raise RuntimeError( + "FP8 is not available on this machine. Please ensure that either Transformer Engine, MSAMP or torchao is installed." + ) + current_env = setup_fp8_env(args, current_env) + + try: + dynamo_backend = DynamoBackend(args.dynamo_backend.upper()) + except ValueError: + raise ValueError( + f"Unknown dynamo backend: {args.dynamo_backend.upper()}. Choose between {DynamoBackend.list()}." + ) + current_env["ACCELERATE_DYNAMO_BACKEND"] = dynamo_backend.value + current_env["ACCELERATE_DYNAMO_MODE"] = args.dynamo_mode + current_env["ACCELERATE_DYNAMO_USE_FULLGRAPH"] = str(args.dynamo_use_fullgraph) + current_env["ACCELERATE_DYNAMO_USE_DYNAMIC"] = str(args.dynamo_use_dynamic) + current_env["ACCELERATE_DYNAMO_USE_REGIONAL_COMPILATION"] = str(args.dynamo_use_regional_compilation) + + current_env["OMP_NUM_THREADS"] = str(args.num_cpu_threads_per_process) + if is_ipex_available(): + current_env["ACCELERATE_USE_IPEX"] = str(args.ipex).lower() + if args.enable_cpu_affinity: + current_env["ACCELERATE_CPU_AFFINITY"] = "1" + return cmd, current_env + + +def prepare_multi_gpu_env(args: argparse.Namespace) -> dict[str, str]: + """ + Prepares and returns an environment with the correct multi-GPU environment variables. + """ + # get free port and update configurations + if args.main_process_port == 0: + args.main_process_port = get_free_port() + + elif args.main_process_port is None: + args.main_process_port = 29500 + + num_processes = args.num_processes + num_machines = args.num_machines + main_process_ip = args.main_process_ip + main_process_port = args.main_process_port + if num_machines > 1: + args.nproc_per_node = str(num_processes // num_machines) + args.nnodes = str(num_machines) + args.node_rank = int(args.machine_rank) + if getattr(args, "same_network", False): + args.master_addr = str(main_process_ip) + args.master_port = str(main_process_port) + else: + args.rdzv_endpoint = f"{main_process_ip}:{main_process_port}" + else: + args.nproc_per_node = str(num_processes) + if main_process_port is not None: + args.master_port = str(main_process_port) + + # only need to check port availability in main process, in case we have to start multiple launchers on the same machine + # for some reasons like splitting log files. + need_port_check = num_machines <= 1 or int(args.machine_rank) == 0 + if need_port_check and is_port_in_use(main_process_port): + if num_machines <= 1: + args.standalone = True + warnings.warn( + f"Port `{main_process_port}` is already in use. " + "Accelerate will attempt to launch in a standalone-like mode by finding an open port automatically for this session. " + "If this current attempt fails, or for more control in future runs, please specify a different port " + "(e.g., `--main_process_port `) or use `--main_process_port 0` for automatic selection " + "in your launch command or Accelerate config file." + ) + else: + raise ConnectionError( + f"Tried to launch distributed communication on port `{main_process_port}`, but another process is utilizing it. " + "Please specify a different port (such as using the `--main_process_port` flag or specifying a different `main_process_port` in your config file)" + " and rerun your script. To automatically use the next open port (on a single node), you can set this to `0`." + ) + + if args.module and args.no_python: + raise ValueError("--module and --no_python cannot be used together") + elif args.module: + args.module = True + elif args.no_python: + args.no_python = True + + current_env = os.environ.copy() + if args.debug: + current_env["ACCELERATE_DEBUG_MODE"] = "true" + gpu_ids = getattr(args, "gpu_ids", "all") + if gpu_ids != "all" and args.gpu_ids is not None: + if is_xpu_available(): + current_env["ZE_AFFINITY_MASK"] = gpu_ids + elif is_mlu_available(): + current_env["MLU_VISIBLE_DEVICES"] = gpu_ids + elif is_sdaa_available(): + current_env["SDAA_VISIBLE_DEVICES"] = gpu_ids + elif is_musa_available(): + current_env["MUSA_VISIBLE_DEVICES"] = gpu_ids + elif is_npu_available(): + current_env["ASCEND_RT_VISIBLE_DEVICES"] = gpu_ids + elif is_hpu_available(): + current_env["HABANA_VISIBLE_MODULES"] = gpu_ids + else: + current_env["CUDA_VISIBLE_DEVICES"] = gpu_ids + mixed_precision = args.mixed_precision.lower() + try: + mixed_precision = PrecisionType(mixed_precision) + except ValueError: + raise ValueError(f"Unknown mixed_precision mode: {mixed_precision}. Choose between {PrecisionType.list()}.") + + current_env["ACCELERATE_MIXED_PRECISION"] = str(mixed_precision) + if args.mixed_precision.lower() == "fp8": + if not is_fp8_available(): + raise RuntimeError( + "FP8 is not available on this machine. Please ensure that either Transformer Engine, MSAMP or torchao is installed." + ) + current_env = setup_fp8_env(args, current_env) + + try: + dynamo_backend = DynamoBackend(args.dynamo_backend.upper()) + except ValueError: + raise ValueError( + f"Unknown dynamo backend: {args.dynamo_backend.upper()}. Choose between {DynamoBackend.list()}." + ) + current_env["ACCELERATE_DYNAMO_BACKEND"] = dynamo_backend.value + current_env["ACCELERATE_DYNAMO_MODE"] = args.dynamo_mode + current_env["ACCELERATE_DYNAMO_USE_FULLGRAPH"] = str(args.dynamo_use_fullgraph) + current_env["ACCELERATE_DYNAMO_USE_DYNAMIC"] = str(args.dynamo_use_dynamic) + current_env["ACCELERATE_DYNAMO_USE_REGIONAL_COMPILATION"] = str(args.dynamo_use_regional_compilation) + + if args.use_fsdp: + current_env["ACCELERATE_USE_FSDP"] = "true" + if args.fsdp_cpu_ram_efficient_loading and not args.fsdp_sync_module_states: + raise ValueError("When using `--fsdp_cpu_ram_efficient_loading` set `--fsdp_sync_module_states` to `True`") + + current_env["FSDP_VERSION"] = str(args.fsdp_version) if hasattr(args, "fsdp_version") else "1" + + # For backwards compatibility, we support this in launched scripts, + # however, we do not ask users for this in `accelerate config` CLI + current_env["FSDP_SHARDING_STRATEGY"] = str(args.fsdp_sharding_strategy) + + current_env["FSDP_RESHARD_AFTER_FORWARD"] = str(args.fsdp_reshard_after_forward).lower() + current_env["FSDP_OFFLOAD_PARAMS"] = str(args.fsdp_offload_params).lower() + current_env["FSDP_MIN_NUM_PARAMS"] = str(args.fsdp_min_num_params) + if args.fsdp_auto_wrap_policy is not None: + current_env["FSDP_AUTO_WRAP_POLICY"] = str(args.fsdp_auto_wrap_policy) + if args.fsdp_transformer_layer_cls_to_wrap is not None: + current_env["FSDP_TRANSFORMER_CLS_TO_WRAP"] = str(args.fsdp_transformer_layer_cls_to_wrap) + if args.fsdp_backward_prefetch is not None: + current_env["FSDP_BACKWARD_PREFETCH"] = str(args.fsdp_backward_prefetch) + if args.fsdp_state_dict_type is not None: + current_env["FSDP_STATE_DICT_TYPE"] = str(args.fsdp_state_dict_type) + current_env["FSDP_FORWARD_PREFETCH"] = str(args.fsdp_forward_prefetch).lower() + current_env["FSDP_USE_ORIG_PARAMS"] = str(args.fsdp_use_orig_params).lower() + current_env["FSDP_CPU_RAM_EFFICIENT_LOADING"] = str(args.fsdp_cpu_ram_efficient_loading).lower() + current_env["FSDP_SYNC_MODULE_STATES"] = str(args.fsdp_sync_module_states).lower() + current_env["FSDP_ACTIVATION_CHECKPOINTING"] = str(args.fsdp_activation_checkpointing).lower() + if getattr(args, "fsdp_ignored_modules", None) is not None: + current_env["FSDP_IGNORED_MODULES"] = str(args.fsdp_ignored_modules) + + if args.use_megatron_lm: + prefix = "MEGATRON_LM_" + current_env["ACCELERATE_USE_MEGATRON_LM"] = "true" + current_env[prefix + "TP_DEGREE"] = str(args.megatron_lm_tp_degree) + current_env[prefix + "PP_DEGREE"] = str(args.megatron_lm_pp_degree) + current_env[prefix + "GRADIENT_CLIPPING"] = str(args.megatron_lm_gradient_clipping) + if args.megatron_lm_num_micro_batches is not None: + current_env[prefix + "NUM_MICRO_BATCHES"] = str(args.megatron_lm_num_micro_batches) + if args.megatron_lm_sequence_parallelism is not None: + current_env[prefix + "SEQUENCE_PARALLELISM"] = str(args.megatron_lm_sequence_parallelism) + if args.megatron_lm_recompute_activations is not None: + current_env[prefix + "RECOMPUTE_ACTIVATIONS"] = str(args.megatron_lm_recompute_activations) + if args.megatron_lm_use_distributed_optimizer is not None: + current_env[prefix + "USE_DISTRIBUTED_OPTIMIZER"] = str(args.megatron_lm_use_distributed_optimizer) + + current_env["OMP_NUM_THREADS"] = str(args.num_cpu_threads_per_process) + if args.enable_cpu_affinity: + current_env["ACCELERATE_CPU_AFFINITY"] = "1" + + if not args.use_parallelism_config: + return current_env + + prefix = "PARALLELISM_CONFIG_" + if args.use_parallelism_config: + current_env["ACCELERATE_USE_PARALLELISM_CONFIG"] = "true" + current_env[prefix + "DP_REPLICATE_SIZE"] = str(args.parallelism_config_dp_replicate_size) + current_env[prefix + "TP_SIZE"] = str(args.parallelism_config_tp_size) + current_env[prefix + "CP_SIZE"] = str(args.parallelism_config_cp_size) + current_env[prefix + "DP_SHARD_SIZE"] = str(args.parallelism_config_dp_shard_size) + if args.parallelism_config_cp_size > 1: + current_env[prefix + "CP_COMM_STRATEGY"] = str(args.parallelism_config_cp_comm_strategy) + + return current_env + + +def prepare_deepspeed_cmd_env(args: argparse.Namespace) -> tuple[list[str], dict[str, str]]: + """ + Prepares and returns the command list and an environment with the correct DeepSpeed environment variables. + """ + # get free port and update configurations + if args.main_process_port == 0: + args.main_process_port = get_free_port() + + elif args.main_process_port is None: + args.main_process_port = 29500 + + num_processes = args.num_processes + num_machines = args.num_machines + main_process_ip = args.main_process_ip + main_process_port = args.main_process_port + cmd = None + + # make sure launcher is not None + if args.deepspeed_multinode_launcher is None: + # set to default pdsh + args.deepspeed_multinode_launcher = DEEPSPEED_MULTINODE_LAUNCHERS[0] + + if num_machines > 1 and args.deepspeed_multinode_launcher != DEEPSPEED_MULTINODE_LAUNCHERS[1]: + cmd = ["deepspeed"] + cmd.extend(["--hostfile", str(args.deepspeed_hostfile)]) + if args.deepspeed_multinode_launcher == "nossh": + if compare_versions("deepspeed", "<", "0.14.5"): + raise ValueError("nossh launcher requires DeepSpeed >= 0.14.5") + cmd.extend(["--node_rank", str(args.machine_rank), "--no_ssh"]) + else: + cmd.extend(["--no_local_rank", "--launcher", str(args.deepspeed_multinode_launcher)]) + if args.deepspeed_exclusion_filter is not None: + cmd.extend( + [ + "--exclude", + str(args.deepspeed_exclusion_filter), + ] + ) + elif args.deepspeed_inclusion_filter is not None: + cmd.extend( + [ + "--include", + str(args.deepspeed_inclusion_filter), + ] + ) + else: + cmd.extend(["--num_gpus", str(args.num_processes // args.num_machines)]) + if main_process_ip: + cmd.extend(["--master_addr", str(main_process_ip)]) + cmd.extend(["--master_port", str(main_process_port)]) + if args.module and args.no_python: + raise ValueError("--module and --no_python cannot be used together") + elif args.module: + cmd.append("--module") + elif args.no_python: + cmd.append("--no_python") + cmd.append(args.training_script) + cmd.extend(args.training_script_args) + elif num_machines > 1 and args.deepspeed_multinode_launcher == DEEPSPEED_MULTINODE_LAUNCHERS[1]: + args.nproc_per_node = str(num_processes // num_machines) + args.nnodes = str(num_machines) + args.node_rank = int(args.machine_rank) + if getattr(args, "same_network", False): + args.master_addr = str(main_process_ip) + args.master_port = str(main_process_port) + else: + args.rdzv_endpoint = f"{main_process_ip}:{main_process_port}" + else: + args.nproc_per_node = str(num_processes) + if main_process_port is not None: + args.master_port = str(main_process_port) + + # only need to check port availability in main process, in case we have to start multiple launchers on the same machine + # for some reasons like splitting log files. + need_port_check = num_machines <= 1 or int(args.machine_rank) == 0 + if need_port_check and is_port_in_use(main_process_port): + if num_machines <= 1: + args.standalone = True + warnings.warn( + f"Port `{main_process_port}` is already in use. " + "Accelerate will attempt to launch in a standalone-like mode by finding an open port automatically for this session. " + "If this current attempt fails, or for more control in future runs, please specify a different port " + "(e.g., `--main_process_port `) or use `--main_process_port 0` for automatic selection " + "in your launch command or Accelerate config file." + ) + else: + raise ConnectionError( + f"Tried to launch distributed communication on port `{main_process_port}`, but another process is utilizing it. " + "Please specify a different port (such as using the `--main_process_port` flag or specifying a different `main_process_port` in your config file)" + " and rerun your script. To automatically use the next open port (on a single node), you can set this to `0`." + ) + + if args.module and args.no_python: + raise ValueError("--module and --no_python cannot be used together") + elif args.module: + args.module = True + elif args.no_python: + args.no_python = True + + current_env = os.environ.copy() + if args.debug: + current_env["ACCELERATE_DEBUG_MODE"] = "true" + gpu_ids = getattr(args, "gpu_ids", "all") + if gpu_ids != "all" and args.gpu_ids is not None: + if is_xpu_available(): + current_env["ZE_AFFINITY_MASK"] = gpu_ids + elif is_mlu_available(): + current_env["MLU_VISIBLE_DEVICES"] = gpu_ids + elif is_sdaa_available(): + current_env["SDAA_VISIBLE_DEVICES"] = gpu_ids + elif is_musa_available(): + current_env["MUSA_VISIBLE_DEVICES"] = gpu_ids + elif is_npu_available(): + current_env["ASCEND_RT_VISIBLE_DEVICES"] = gpu_ids + elif is_hpu_available(): + current_env["HABANA_VISIBLE_MODULES"] = gpu_ids + else: + current_env["CUDA_VISIBLE_DEVICES"] = gpu_ids + try: + mixed_precision = PrecisionType(args.mixed_precision.lower()) + except ValueError: + raise ValueError( + f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}." + ) + + current_env["PYTHONPATH"] = env_var_path_add("PYTHONPATH", os.path.abspath(".")) + current_env["ACCELERATE_MIXED_PRECISION"] = str(mixed_precision) + if args.mixed_precision.lower() == "fp8": + if not is_fp8_available(): + raise RuntimeError( + "FP8 is not available on this machine. Please ensure that either Transformer Engine, MSAMP or torchao is installed." + ) + current_env = setup_fp8_env(args, current_env) + current_env["ACCELERATE_CONFIG_DS_FIELDS"] = str(args.deepspeed_fields_from_accelerate_config).lower() + current_env["ACCELERATE_USE_DEEPSPEED"] = "true" + if args.zero_stage is not None: + current_env["ACCELERATE_DEEPSPEED_ZERO_STAGE"] = str(args.zero_stage) + if args.gradient_accumulation_steps is not None: + current_env["ACCELERATE_GRADIENT_ACCUMULATION_STEPS"] = str(args.gradient_accumulation_steps) + if args.gradient_clipping is not None: + current_env["ACCELERATE_GRADIENT_CLIPPING"] = str(args.gradient_clipping).lower() + if args.offload_optimizer_device is not None: + current_env["ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_DEVICE"] = str(args.offload_optimizer_device).lower() + if args.offload_param_device is not None: + current_env["ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_DEVICE"] = str(args.offload_param_device).lower() + if args.zero3_init_flag is not None: + current_env["ACCELERATE_DEEPSPEED_ZERO3_INIT"] = str(args.zero3_init_flag).lower() + if args.zero3_save_16bit_model is not None: + current_env["ACCELERATE_DEEPSPEED_ZERO3_SAVE_16BIT_MODEL"] = str(args.zero3_save_16bit_model).lower() + if args.deepspeed_config_file is not None: + current_env["ACCELERATE_DEEPSPEED_CONFIG_FILE"] = str(args.deepspeed_config_file) + if args.enable_cpu_affinity: + current_env["ACCELERATE_CPU_AFFINITY"] = "1" + if args.deepspeed_moe_layer_cls_names is not None: + current_env["ACCELERATE_DEEPSPEED_MOE_LAYER_CLS_NAMES"] = str(args.deepspeed_moe_layer_cls_names) + return cmd, current_env + + +def prepare_tpu( + args: argparse.Namespace, current_env: dict[str, str], pod: bool = False +) -> tuple[argparse.Namespace, dict[str, str]]: + """ + Prepares and returns an environment with the correct TPU environment variables. + """ + if args.mixed_precision == "bf16" and is_torch_xla_available(check_is_tpu=True): + if args.downcast_bf16: + current_env["XLA_DOWNCAST_BF16"] = "1" + else: + current_env["XLA_USE_BF16"] = "1" + if args.debug: + current_env["ACCELERATE_DEBUG_MODE"] = "true" + if pod: + # Take explicit args and set them up for XLA + args.vm = args.tpu_vm + args.tpu = args.tpu_name + return args, current_env + + +def _convert_nargs_to_dict(nargs: list[str]) -> dict[str, str]: + if len(nargs) < 0: + return {} + # helper function to infer type for argsparser + + def _infer_type(s): + try: + s = float(s) + + if s // 1 == s: + return int(s) + return s + except ValueError: + return s + + parser = argparse.ArgumentParser() + _, unknown = parser.parse_known_args(nargs) + for index, argument in enumerate(unknown): + if argument.startswith(("-", "--")): + action = None + if index + 1 < len(unknown): # checks if next index would be in list + if unknown[index + 1].startswith(("-", "--")): # checks if next element is an key + # raise an error if element is store_true or store_false + raise ValueError( + "SageMaker doesn’t support argparse actions for `store_true` or `store_false`. Please define explicit types" + ) + else: # raise an error if last element is store_true or store_false + raise ValueError( + "SageMaker doesn’t support argparse actions for `store_true` or `store_false`. Please define explicit types" + ) + # adds argument to parser based on action_store true + if action is None: + parser.add_argument(argument, type=_infer_type) + else: + parser.add_argument(argument, action=action) + + return { + key: (literal_eval(value) if value in ("True", "False") else value) + for key, value in parser.parse_args(nargs).__dict__.items() + } + + +def prepare_sagemager_args_inputs( + sagemaker_config: SageMakerConfig, args: argparse.Namespace +) -> tuple[argparse.Namespace, dict[str, Any]]: + # configure environment + print("Configuring Amazon SageMaker environment") + os.environ["AWS_DEFAULT_REGION"] = sagemaker_config.region + + # configure credentials + if sagemaker_config.profile is not None: + os.environ["AWS_PROFILE"] = sagemaker_config.profile + elif args.aws_access_key_id is not None and args.aws_secret_access_key is not None: + os.environ["AWS_ACCESS_KEY_ID"] = args.aws_access_key_id + os.environ["AWS_SECRET_ACCESS_KEY"] = args.aws_secret_access_key + else: + raise OSError("You need to provide an aws_access_key_id and aws_secret_access_key when not using aws_profile") + + # extract needed arguments + source_dir = os.path.dirname(args.training_script) + if not source_dir: # checks if string is empty + source_dir = "." + entry_point = os.path.basename(args.training_script) + if not entry_point.endswith(".py"): + raise ValueError(f'Your training script should be a python script and not "{entry_point}"') + + print("Converting Arguments to Hyperparameters") + hyperparameters = _convert_nargs_to_dict(args.training_script_args) + + try: + mixed_precision = PrecisionType(args.mixed_precision.lower()) + except ValueError: + raise ValueError( + f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}." + ) + + try: + dynamo_backend = DynamoBackend(args.dynamo_backend.upper()) + except ValueError: + raise ValueError( + f"Unknown dynamo backend: {args.dynamo_backend.upper()}. Choose between {DynamoBackend.list()}." + ) + + # Environment variables to be set for use during training job + environment = { + "ACCELERATE_USE_SAGEMAKER": "true", + "ACCELERATE_MIXED_PRECISION": str(mixed_precision), + "ACCELERATE_DYNAMO_BACKEND": dynamo_backend.value, + "ACCELERATE_DYNAMO_MODE": args.dynamo_mode, + "ACCELERATE_DYNAMO_USE_FULLGRAPH": str(args.dynamo_use_fullgraph), + "ACCELERATE_DYNAMO_USE_DYNAMIC": str(args.dynamo_use_dynamic), + "ACCELERATE_DYNAMO_USE_REGIONAL_COMPILATION": str(args.dynamo_use_regional_compilation), + "ACCELERATE_SAGEMAKER_DISTRIBUTED_TYPE": sagemaker_config.distributed_type.value, + } + if args.mixed_precision.lower() == "fp8": + if not is_fp8_available(): + raise RuntimeError( + "FP8 is not available on this machine. Please ensure that either Transformer Engine, MSAMP or torchao is installed." + ) + environment = setup_fp8_env(args, environment) + # configure distribution set up + distribution = None + if sagemaker_config.distributed_type == SageMakerDistributedType.DATA_PARALLEL: + distribution = {"smdistributed": {"dataparallel": {"enabled": True}}} + + # configure sagemaker inputs + sagemaker_inputs = None + if sagemaker_config.sagemaker_inputs_file is not None: + print(f"Loading SageMaker Inputs from {sagemaker_config.sagemaker_inputs_file} file") + sagemaker_inputs = {} + with open(sagemaker_config.sagemaker_inputs_file) as file: + for i, line in enumerate(file): + if i == 0: + continue + l = line.split("\t") + sagemaker_inputs[l[0]] = l[1].strip() + print(f"Loaded SageMaker Inputs: {sagemaker_inputs}") + + # configure sagemaker metrics + sagemaker_metrics = None + if sagemaker_config.sagemaker_metrics_file is not None: + print(f"Loading SageMaker Metrics from {sagemaker_config.sagemaker_metrics_file} file") + sagemaker_metrics = [] + with open(sagemaker_config.sagemaker_metrics_file) as file: + for i, line in enumerate(file): + if i == 0: + continue + l = line.split("\t") + metric_dict = { + "Name": l[0], + "Regex": l[1].strip(), + } + sagemaker_metrics.append(metric_dict) + print(f"Loaded SageMaker Metrics: {sagemaker_metrics}") + + # configure session + print("Creating Estimator") + args = { + "image_uri": sagemaker_config.image_uri, + "entry_point": entry_point, + "source_dir": source_dir, + "role": sagemaker_config.iam_role_name, + "transformers_version": sagemaker_config.transformers_version, + "pytorch_version": sagemaker_config.pytorch_version, + "py_version": sagemaker_config.py_version, + "base_job_name": sagemaker_config.base_job_name, + "instance_count": sagemaker_config.num_machines, + "instance_type": sagemaker_config.ec2_instance_type, + "debugger_hook_config": False, + "distribution": distribution, + "hyperparameters": hyperparameters, + "environment": environment, + "metric_definitions": sagemaker_metrics, + } + + if sagemaker_config.additional_args is not None: + args = merge_dicts(sagemaker_config.additional_args, args) + return args, sagemaker_inputs + + +def env_var_path_add(env_var_name, path_to_add): + """ + Extends a path-based environment variable's value with a new path and returns the updated value. It's up to the + caller to set it in os.environ. + """ + paths = [p for p in os.environ.get(env_var_name, "").split(":") if len(p) > 0] + paths.append(str(path_to_add)) + return ":".join(paths) + + +class PrepareForLaunch: + """ + Prepare a function that will launched in a distributed setup. + + Args: + launcher (`Callable`): + The function to launch. + distributed_type ([`~state.DistributedType`]): + The distributed type to prepare for. + debug (`bool`, *optional*, defaults to `False`): + Whether or not this is a debug launch. + """ + + def __init__(self, launcher, distributed_type="NO", debug=False): + self.launcher = launcher + self.distributed_type = DistributedType(distributed_type) + self.debug = debug + + def __call__(self, index, *args): + if self.debug: + world_size = int(os.environ.get("WORLD_SIZE")) + rdv_file = os.environ.get("ACCELERATE_DEBUG_RDV_FILE") + torch.distributed.init_process_group( + "gloo", + rank=index, + store=torch.distributed.FileStore(rdv_file, world_size), + world_size=world_size, + ) + elif self.distributed_type in ( + DistributedType.MULTI_GPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_NPU, + DistributedType.MULTI_XPU, + DistributedType.MULTI_CPU, + ): + # Prepare the environment for torch.distributed + os.environ["LOCAL_RANK"] = str(index) + nproc = int(os.environ.get("NPROC", 1)) + node_rank = int(os.environ.get("NODE_RANK", 0)) + os.environ["RANK"] = str(nproc * node_rank + index) + + os.environ["FORK_LAUNCHED"] = str(1) + self.launcher(*args) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/megatron_lm.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/megatron_lm.py new file mode 100644 index 0000000000000000000000000000000000000000..9f6d87b2edb13299e0b6b34dd32851f020415242 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/megatron_lm.py @@ -0,0 +1,1424 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import math +import os +from abc import ABC +from functools import partial + +import torch +import torch.nn.functional as F +from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss +from torch.nn.parallel.distributed import DistributedDataParallel as torchDDP + +from ..optimizer import AcceleratedOptimizer +from ..scheduler import AcceleratedScheduler +from .imports import is_megatron_lm_available +from .operations import recursively_apply, send_to_device + + +if is_megatron_lm_available(): + from megatron.core import mpu, tensor_parallel + from megatron.core.distributed import DistributedDataParallel as LocalDDP + from megatron.core.distributed import finalize_model_grads + from megatron.core.enums import ModelType + from megatron.core.num_microbatches_calculator import get_num_microbatches + from megatron.core.optimizer import get_megatron_optimizer + from megatron.core.parallel_state import get_tensor_model_parallel_group, get_tensor_model_parallel_src_rank + from megatron.core.pipeline_parallel import get_forward_backward_func + from megatron.core.utils import get_model_config + from megatron.inference.text_generation.communication import broadcast_int_list, broadcast_tensor + from megatron.inference.text_generation.generation import ( + beam_search_and_return_on_first_stage, + generate_tokens_probs_and_return_on_first_stage, + ) + from megatron.legacy.data.dataset_utils import build_train_valid_test_datasets + from megatron.legacy.model import BertModel, Float16Module, GPTModel, T5Model + from megatron.legacy.model.classification import Classification + from megatron.training import ( + get_args, + get_tensorboard_writer, + get_tokenizer, + print_rank_last, + ) + from megatron.training.arguments import ( + _add_data_args, + _add_validation_args, + core_transformer_config_from_args, + parse_args, + validate_args, + ) + from megatron.training.checkpointing import load_args_from_checkpoint, load_checkpoint, save_checkpoint + from megatron.training.global_vars import set_global_variables + from megatron.training.initialize import ( + _compile_dependencies, + _init_autoresume, + _initialize_distributed, + _set_random_seed, + set_jit_fusion_options, + write_args_to_tensorboard, + ) + from megatron.training.tokenizer.tokenizer import _vocab_size_with_padding + from megatron.training.training import ( + build_train_valid_test_data_iterators, + get_optimizer_param_scheduler, + num_floating_point_operations, + setup_model_and_optimizer, + train_step, + training_log, + ) + from megatron.training.utils import ( + average_losses_across_data_parallel_group, + calc_params_l2_norm, + get_ltor_masks_and_position_ids, + unwrap_model, + ) + + +# model utilities +def model_provider_func(pre_process=True, post_process=True, add_encoder=True, add_decoder=True): + """Build the model.""" + args = get_args() + mode = "pre-training" if args.pretraining_flag else "fine-tuning" + if args.rank == 0: + print(f"Building {args.model_type_name} model in the {mode} mode.") + print( + "The Megatron LM model weights are initialized at random in `accelerator.prepare`. " + "Please use `accelerator.load_checkpoint` to load a pre-trained checkpoint matching the distributed setup." + ) + config = core_transformer_config_from_args(args) + if args.model_type_name == "bert": + if args.pretraining_flag: + num_tokentypes = 2 if args.bert_binary_head else 0 + model = BertModel( + config=config, + num_tokentypes=num_tokentypes, + add_binary_head=args.bert_binary_head, + parallel_output=True, + pre_process=pre_process, + post_process=post_process, + ) + else: + model = Classification( + config=config, + num_classes=args.num_labels, + num_tokentypes=2, + pre_process=pre_process, + post_process=post_process, + ) + elif args.model_type_name == "gpt": + model = GPTModel( + config=config, + num_tokentypes=0, + parallel_output=True, + pre_process=pre_process, + post_process=post_process, + ) + elif args.model_type_name == "t5": + model = T5Model( + config=config, + num_tokentypes=0, + parallel_output=True, + pre_process=pre_process, + post_process=post_process, + add_encoder=add_encoder, + add_decoder=add_decoder, + ) + else: + raise ValueError(f"Unsupported model type: {args.model_type_name}") + return model + + +def prepare_model_optimizer_scheduler(accelerator): + accelerator.print("Preparing model optimizer scheduler") + args = get_args() + if accelerator.state.megatron_lm_plugin.custom_prepare_model_function is not None: + if accelerator.state.megatron_lm_plugin.custom_model_provider_function is None: + raise ValueError( + "You must provide a `custom_model_provider_function` when using a `custom_prepare_model_function`." + ) + custom_model_provider_func = accelerator.state.megatron_lm_plugin.custom_model_provider_function + model = accelerator.state.megatron_lm_plugin.custom_prepare_model_function(custom_model_provider_func) + optimizer = prepare_optimizer(accelerator, model) + scheduler = prepare_scheduler(accelerator, optimizer, scheduler=None) + else: + model_type = ModelType.encoder_or_decoder + if args.model_type_name == "t5": + model_type = ModelType.encoder_and_decoder + model_provider_func_ = model_provider_func + if accelerator.state.megatron_lm_plugin.custom_model_provider_function is not None: + model_provider_func_ = accelerator.state.megatron_lm_plugin.custom_model_provider_function + (model, optimizer, scheduler) = setup_model_and_optimizer( + model_provider_func_, + model_type, + no_wd_decay_cond=args.no_wd_decay_cond, + scale_lr_cond=args.scale_lr_cond, + lr_mult=args.lr_mult, + ) + args.model_len = len(model) + return model, optimizer, scheduler + + +# dataloader utilities +class MegatronLMDummyDataLoader: + """ + Dummy dataloader presents model parameters or param groups, this is primarily used to follow conventional training + + Args: + **dataset_kwargs: Megatron data arguments. + """ + + def __init__(self, **dataset_kwargs): + parser = argparse.ArgumentParser() + parser = _add_data_args(parser) + parser = _add_validation_args(parser) + data_args = parser.parse_known_args() + self.dataset_args = vars(data_args[0]) + self.dataset_args.update(dataset_kwargs) + self.dataset_args["megatron_dataset_flag"] = True + + def set_megatron_data_args(self): + args = get_args() + for key, value in self.dataset_args.items(): + old_value = getattr(args, key, "") + if old_value != value: + print( + f"WARNING: MegatronLMDummyDataLoader overriding arguments for {key}:{old_value} with {key}:{value}" + ) + setattr(args, key, value) + + def get_train_valid_test_datasets_provider(self, accelerator): + def train_valid_test_datasets_provider(train_val_test_num_samples): + """Build train, valid, and test datasets.""" + args = get_args() + dataset_args = { + "data_prefix": args.data_path if isinstance(args.data_path, (list, tuple)) else [args.data_path], + "splits_string": args.split, + "train_valid_test_num_samples": train_val_test_num_samples, + "seed": args.seed, + } + if args.model_type_name == "bert": + dataset_args.update( + { + "max_seq_length": args.seq_length, + "binary_head": args.bert_binary_head, + } + ) + elif args.model_type_name == "gpt": + dataset_args.update( + { + "max_seq_length": args.seq_length, + } + ) + elif args.model_type_name == "t5": + dataset_args.update( + { + "max_seq_length": args.encoder_seq_length, + "max_seq_length_dec": args.decoder_seq_length, + "dataset_type": "t5", + } + ) + else: + raise ValueError(f"Unsupported model type: {args.model_type_name}") + train_ds, valid_ds, test_ds = build_train_valid_test_datasets(**dataset_args) + return train_ds, valid_ds, test_ds + + if accelerator.state.megatron_lm_plugin.custom_megatron_datasets_provider_function is not None: + return accelerator.state.megatron_lm_plugin.custom_megatron_datasets_provider_function + try: + args = get_args() + # Use '--no-use-pep517 -e' to pip install nvidia's megatron from source + if args.model_type_name == "bert": + from pretrain_bert import train_valid_test_datasets_provider + + train_valid_test_datasets_provider.is_distributed = True + return train_valid_test_datasets_provider + elif args.model_type_name == "gpt": + from pretrain_gpt import train_valid_test_datasets_provider + + train_valid_test_datasets_provider.is_distributed = True + return train_valid_test_datasets_provider + elif args.model_type_name == "t5": + from pretrain_t5 import train_valid_test_datasets_provider + + train_valid_test_datasets_provider.is_distributed = True + return train_valid_test_datasets_provider + except ImportError: + pass + return train_valid_test_datasets_provider + + def build_train_valid_test_data_iterators(self, accelerator): + args = get_args() + + train_valid_test_dataset_provider = self.get_train_valid_test_datasets_provider(accelerator) + if args.virtual_pipeline_model_parallel_size is not None: + train_data_iterator = [] + valid_data_iterator = [] + test_data_iterator = [] + for i in range(getattr(args, "model_len", 0)): + mpu.set_virtual_pipeline_model_parallel_rank(i) + iterators = build_train_valid_test_data_iterators(train_valid_test_dataset_provider) + train_data_iterator.append(iterators[0]) + valid_data_iterator.append(iterators[1]) + test_data_iterator.append(iterators[2]) + else: + train_data_iterator, valid_data_iterator, test_data_iterator = build_train_valid_test_data_iterators( + train_valid_test_dataset_provider + ) + + return train_data_iterator, valid_data_iterator, test_data_iterator + + +def _handle_megatron_data_iterator(accelerator, data_iterator): + class DummyMegatronDataloader: + def __iter__(self): + return self + + def __next__(self): + return {} + + is_data_iterator_empty = data_iterator is None + is_src_data_iterator_empty = torch.tensor(is_data_iterator_empty, dtype=torch.bool, device=accelerator.device) + torch.distributed.broadcast( + is_src_data_iterator_empty, get_tensor_model_parallel_src_rank(), group=get_tensor_model_parallel_group() + ) + if not is_src_data_iterator_empty and is_data_iterator_empty: + return DummyMegatronDataloader() + return data_iterator + + +def prepare_data_loader(accelerator, dataloader): + accelerator.print("Preparing dataloader") + args = get_args() + if not args.megatron_dataset_flag: + from ..data_loader import _PYTORCH_DATALOADER_KWARGS, prepare_data_loader + + micro_batch_size = args.micro_batch_size * args.num_micro_batches + kwargs = {k: getattr(dataloader, k, _PYTORCH_DATALOADER_KWARGS[k]) for k in _PYTORCH_DATALOADER_KWARGS} + if kwargs["batch_size"] is None: + if isinstance(kwargs["sampler"], torch.utils.data.BatchSampler): + kwargs["sampler"].batch_size = micro_batch_size + else: + del kwargs["sampler"] + del kwargs["shuffle"] + del kwargs["batch_size"] + kwargs["batch_sampler"].batch_size = micro_batch_size + else: + del kwargs["batch_sampler"] + kwargs["batch_size"] = micro_batch_size + + dataloader = torch.utils.data.DataLoader(dataloader.dataset, **kwargs) + # split_batches: + # Megatron only needs to fetch different data between different dp groups, + # and does not need to split the data within the dp group. + return prepare_data_loader( + dataloader, + accelerator.device, + num_processes=mpu.get_data_parallel_world_size(), + process_index=mpu.get_data_parallel_rank(), + split_batches=False, + put_on_device=True, + rng_types=accelerator.rng_types.copy(), + dispatch_batches=accelerator.dispatch_batches, + ) + else: + if args.consumed_samples is not None: + ( + args.consumed_train_samples, + args.consumed_valid_samples, + args.consumed_test_samples, + ) = args.consumed_samples + else: + args.consumed_train_samples, args.consumed_valid_samples, args.consumed_test_samples = 0, 0, 0 + args.micro_batch_size = args.micro_batch_size * args.num_micro_batches + # In order to be compatible with data in transform format, + # it needs to increase the size of mbs first, + # and then split the large batch data into some mbs. + ( + train_data_iterator, + valid_data_iterator, + test_data_iterator, + ) = dataloader.build_train_valid_test_data_iterators(accelerator) + args.micro_batch_size = args.micro_batch_size // args.num_micro_batches + + train_data_iterator = _handle_megatron_data_iterator( + accelerator=accelerator, data_iterator=train_data_iterator + ) + valid_data_iterator = _handle_megatron_data_iterator( + accelerator=accelerator, data_iterator=valid_data_iterator + ) + test_data_iterator = _handle_megatron_data_iterator(accelerator=accelerator, data_iterator=test_data_iterator) + + return train_data_iterator, valid_data_iterator, test_data_iterator + + +# optimizer utilities +class MegatronLMOptimizerWrapper(AcceleratedOptimizer): + def __init__(self, optimizer): + super().__init__(optimizer, device_placement=False, scaler=None) + + def zero_grad(self, set_to_none=None): + pass # `model(**batch)` is doing that automatically. Therefore, its implementation is not needed + + def step(self): + pass # `model(**batch)` is doing that automatically. Therefore, its implementation is not needed + + @property + def step_was_skipped(self): + """Whether or not the optimizer step was done, or skipped because of gradient overflow.""" + return self.optimizer.skipped_iter + + +def prepare_optimizer(accelerator, model): + accelerator.print("Preparing optimizer") + args = get_args() + return get_megatron_optimizer(model, args.no_wd_decay_cond, args.scale_lr_cond, args.lr_mult) + + +# scheduler utilities +class MegatronLMDummyScheduler: + """ + Dummy scheduler presents model parameters or param groups, this is primarily used to follow conventional training + loop when scheduler config is specified in the deepspeed config file. + + Args: + optimizer (`torch.optim.optimizer.Optimizer`): + The optimizer to wrap. + total_num_steps (int): + Total number of steps. + warmup_num_steps (int): + Number of steps for warmup. + **kwargs (additional keyword arguments, *optional*): + Other arguments. + """ + + def __init__(self, optimizer, total_num_steps=None, warmup_num_steps=0, **kwargs): + self.optimizer = optimizer + self.total_num_steps = total_num_steps + self.warmup_num_steps = warmup_num_steps + self.kwargs = kwargs + + +class MegatronLMSchedulerWrapper(AcceleratedScheduler): + def __init__(self, scheduler, optimizers): + super().__init__(scheduler, optimizers) + + def step(self, *args, **kwargs): + return # `model(**batch)` is doing that automatically. Therefore, its implementation is not needed + + +def prepare_scheduler(accelerator, optimizer, scheduler): + accelerator.print("Preparing scheduler") + scheduler = get_optimizer_param_scheduler(optimizer) + return scheduler + + +class AbstractTrainStep(ABC): + """Abstract class for batching, forward pass and loss handler.""" + + def __init__(self, name): + super().__init__() + self.name = name + + def get_batch_func(self, accelerator, megatron_dataset_flag): + pass + + def get_forward_step_func(self): + pass + + def get_loss_func(self, accelerator): + pass + + +class BertTrainStep(AbstractTrainStep): + """ + Bert train step class. + + Args: + args (`argparse.Namespace`): Megatron-LM arguments. + """ + + def __init__(self, accelerator, args): + super().__init__("BertTrainStep") + self.get_batch = self.get_batch_func(accelerator, args.megatron_dataset_flag) + self.loss_func = self.get_loss_func(accelerator, args.pretraining_flag, args.num_labels) + self.forward_step = self.get_forward_step_func(args.pretraining_flag, args.bert_binary_head) + if not args.model_return_dict: + self.model_output_class = None + else: + from transformers.modeling_outputs import SequenceClassifierOutput + + self.model_output_class = SequenceClassifierOutput + + def get_batch_func(self, accelerator, megatron_dataset_flag): + def get_batch_megatron(data_iterator): + """Build the batch.""" + + # Items and their type. + keys = ["text", "types", "labels", "is_random", "loss_mask", "padding_mask"] + datatype = torch.int64 + + # Broadcast data. + if data_iterator is not None: + data = next(data_iterator) + else: + data = None + data_b = tensor_parallel.broadcast_data(keys, data, datatype) + + # Unpack. + tokens = data_b["text"].long() + types = data_b["types"].long() + sentence_order = data_b["is_random"].long() + loss_mask = data_b["loss_mask"].float() + lm_labels = data_b["labels"].long() + padding_mask = data_b["padding_mask"].long() + + return tokens, types, sentence_order, loss_mask, lm_labels, padding_mask + + def get_batch_transformer(data_iterator): + """Build the batch.""" + data = next(data_iterator) + data = send_to_device(data, torch.cuda.current_device()) + + # Unpack. + tokens = data["input_ids"].long() + padding_mask = data["attention_mask"].long() + if "token_type_ids" in data: + types = data["token_type_ids"].long() + else: + types = None + if "labels" in data: + lm_labels = data["labels"].long() + loss_mask = (data["labels"] != -100).to(torch.float) + else: + lm_labels = None + loss_mask = None + if "next_sentence_label" in data: + sentence_order = data["next_sentence_label"].long() + else: + sentence_order = None + + return tokens, types, sentence_order, loss_mask, lm_labels, padding_mask + + if accelerator.state.megatron_lm_plugin.custom_get_batch_function is not None: + return accelerator.state.megatron_lm_plugin.custom_get_batch_function + if megatron_dataset_flag: + try: + # Use '--no-use-pep517 -e' to pip install nvidia's megatron from source + from pretrain_bert import get_batch + + return get_batch + except ImportError: + pass + return get_batch_megatron + else: + return get_batch_transformer + + def get_loss_func(self, accelerator, pretraining_flag, num_labels): + def loss_func_pretrain(loss_mask, sentence_order, output_tensor): + lm_loss_, sop_logits = output_tensor + + lm_loss_ = lm_loss_.float() + loss_mask = loss_mask.float() + lm_loss = torch.sum(lm_loss_.view(-1) * loss_mask.reshape(-1)) / loss_mask.sum() + + if sop_logits is not None: + sop_loss = F.cross_entropy(sop_logits.view(-1, 2).float(), sentence_order.view(-1), ignore_index=-1) + sop_loss = sop_loss.float() + loss = lm_loss + sop_loss + averaged_losses = average_losses_across_data_parallel_group([lm_loss, sop_loss]) + return loss, {"lm loss": averaged_losses[0], "sop loss": averaged_losses[1]} + + else: + loss = lm_loss + averaged_losses = average_losses_across_data_parallel_group([lm_loss]) + return loss, {"lm loss": averaged_losses[0]} + + def loss_func_finetune(labels, logits): + if num_labels == 1: + # We are doing regression + loss_fct = MSELoss() + loss = loss_fct(logits.view(-1), labels.view(-1)) + elif self.num_labels > 1 and (labels.dtype in (torch.long, torch.int)): + loss_fct = CrossEntropyLoss() + loss = loss_fct(logits.view(-1, num_labels), labels.view(-1)) + else: + loss_fct = BCEWithLogitsLoss() + loss = loss_fct(logits, labels) + averaged_losses = average_losses_across_data_parallel_group([loss]) + return loss, {"loss": averaged_losses[0]} + + if accelerator.state.megatron_lm_plugin.custom_loss_function is not None: + return accelerator.state.megatron_lm_plugin.custom_loss_function + if pretraining_flag: + return loss_func_pretrain + else: + return loss_func_finetune + + def get_forward_step_func(self, pretraining_flag, bert_binary_head): + def forward_step(data_iterator, model): + """Forward step.""" + tokens, types, sentence_order, loss_mask, labels, padding_mask = self.get_batch(data_iterator) + if not bert_binary_head: + types = None + # Forward pass through the model. + if pretraining_flag: + output_tensor = model(tokens, padding_mask, tokentype_ids=types, lm_labels=labels) + return output_tensor, partial(self.loss_func, loss_mask, sentence_order) + else: + logits = model(tokens, padding_mask, tokentype_ids=types) + return logits, partial(self.loss_func, labels) + + return forward_step + + +class GPTTrainStep(AbstractTrainStep): + """ + GPT train step class. + + Args: + args (`argparse.Namespace`): Megatron-LM arguments. + """ + + def __init__(self, accelerator, args): + super().__init__("GPTTrainStep") + self.get_batch = self.get_batch_func(accelerator, args.megatron_dataset_flag) + self.loss_func = self.get_loss_func(accelerator) + self.forward_step = self.get_forward_step_func() + self.eod_token = args.padded_vocab_size - 1 + if args.vocab_file is not None: + tokenizer = get_tokenizer() + self.eod_token = tokenizer.eod + self.reset_position_ids = args.reset_position_ids + self.reset_attention_mask = args.reset_attention_mask + self.eod_mask_loss = args.eod_mask_loss + if not args.model_return_dict: + self.model_output_class = None + else: + from transformers.modeling_outputs import CausalLMOutputWithCrossAttentions + + self.model_output_class = CausalLMOutputWithCrossAttentions + + def get_batch_func(self, accelerator, megatron_dataset_flag): + def get_batch_megatron(data_iterator): + """Generate a batch""" + # Items and their type. + keys = ["text"] + datatype = torch.int64 + + # Broadcast data. + if data_iterator is not None: + data = next(data_iterator) + else: + data = None + data_b = tensor_parallel.broadcast_data(keys, data, datatype) + + # Unpack. + tokens_ = data_b["text"].long() + labels = tokens_[:, 1:].contiguous() + tokens = tokens_[:, :-1].contiguous() + + # Get the masks and position ids. + attention_mask, loss_mask, position_ids = get_ltor_masks_and_position_ids( + tokens, self.eod_token, self.reset_position_ids, self.reset_attention_mask, self.eod_mask_loss + ) + + return tokens, labels, loss_mask, attention_mask, position_ids + + def get_batch_transformer(data_iterator): + data = next(data_iterator) + data = {"input_ids": data["input_ids"]} + data = send_to_device(data, torch.cuda.current_device()) + + tokens_ = data["input_ids"].long() + padding = torch.zeros((tokens_.shape[0], 1), dtype=tokens_.dtype, device=tokens_.device) + self.eod_token + tokens_ = torch.concat([tokens_, padding], dim=1) + labels = tokens_[:, 1:].contiguous() + tokens = tokens_[:, :-1].contiguous() + # Get the masks and position ids. + attention_mask, loss_mask, position_ids = get_ltor_masks_and_position_ids( + tokens, self.eod_token, self.reset_position_ids, self.reset_attention_mask, True + ) + return tokens, labels, loss_mask, attention_mask, position_ids + + if accelerator.state.megatron_lm_plugin.custom_get_batch_function is not None: + return accelerator.state.megatron_lm_plugin.custom_get_batch_function + if megatron_dataset_flag: + try: + # Use '--no-use-pep517 -e' to pip install nvidia's megatron from source + from pretrain_gpt import get_batch + + return get_batch + except ImportError: + pass + return get_batch_megatron + else: + return get_batch_transformer + + def get_loss_func(self, accelerator): + args = get_args() + + def loss_func(loss_mask, output_tensor): + if args.return_logits: + losses, logits = output_tensor + else: + losses = output_tensor + losses = losses.float() + loss_mask = loss_mask.view(-1).float() + if args.context_parallel_size > 1: + loss = torch.cat([torch.sum(losses.view(-1) * loss_mask).view(1), loss_mask.sum().view(1)]) + torch.distributed.all_reduce(loss, group=mpu.get_context_parallel_group()) + loss = loss[0] / loss[1] + else: + loss = torch.sum(losses.view(-1) * loss_mask) / loss_mask.sum() + + # Check individual rank losses are not NaN prior to DP all-reduce. + if args.check_for_nan_in_loss_and_grad: + global_rank = torch.distributed.get_rank() + assert not loss.isnan(), ( + f"Rank {global_rank}: found NaN in local forward loss calculation. " + f"Device: {torch.cuda.current_device()}, node: {os.uname()[1]}" + ) + + # Reduce loss for logging. + averaged_loss = average_losses_across_data_parallel_group([loss]) + + output_dict = {"lm loss": averaged_loss[0]} + if args.return_logits: + output_dict.update({"logits": logits}) + return loss, output_dict + + if accelerator.state.megatron_lm_plugin.custom_loss_function is not None: + return accelerator.state.megatron_lm_plugin.custom_loss_function + return loss_func + + def get_forward_step_func(self): + def forward_step(data_iterator, model): + """Forward step.""" + # Get the batch. + tokens, labels, loss_mask, attention_mask, position_ids = self.get_batch(data_iterator) + output_tensor = model(tokens, position_ids, attention_mask, labels=labels) + + return output_tensor, partial(self.loss_func, loss_mask) + + return forward_step + + +class T5TrainStep(AbstractTrainStep): + """ + T5 train step class. + + Args: + args (`argparse.Namespace`): Megatron-LM arguments. + """ + + def __init__(self, accelerator, args): + super().__init__("T5TrainStep") + self.get_batch = self.get_batch_func(accelerator, args.megatron_dataset_flag) + self.loss_func = self.get_loss_func(accelerator) + self.forward_step = self.get_forward_step_func() + if not args.model_return_dict: + self.model_output_class = None + else: + from transformers.modeling_outputs import Seq2SeqLMOutput + + self.model_output_class = Seq2SeqLMOutput + + @staticmethod + def attn_mask_postprocess(attention_mask): + # We create a 3D attention mask from a 2D tensor mask. + # [b, 1, s] + attention_mask_b1s = attention_mask.unsqueeze(1) + # [b, s, 1] + attention_mask_bs1 = attention_mask.unsqueeze(2) + # [b, s, s] + attention_mask_bss = attention_mask_b1s * attention_mask_bs1 + # Convert attention mask to binary: + extended_attention_mask = attention_mask_bss < 0.5 + return extended_attention_mask + + @staticmethod + def get_decoder_mask(seq_length, device): + attention_mask = torch.tril(torch.ones((1, seq_length, seq_length), device=device)) + attention_mask = attention_mask < 0.5 + return attention_mask + + @staticmethod + def get_enc_dec_mask(attention_mask, dec_seq_length, device): + batch_size, _ = attention_mask.shape + # We create a 3D attention mask from a 2D tensor mask. + # [b, 1, s] + attention_mask_b1s = attention_mask.unsqueeze(1) + # [b, s, 1] + attention_mask_bs1 = torch.ones((batch_size, dec_seq_length, 1), device=device) + attention_mask_bss = attention_mask_bs1 * attention_mask_b1s + extended_attention_mask = attention_mask_bss < 0.5 + return extended_attention_mask + + def get_batch_func(self, accelerator, megatron_dataset_flag): + def get_batch_megatron(data_iterator): + """Build the batch.""" + + keys = ["text_enc", "text_dec", "labels", "loss_mask", "enc_mask", "dec_mask", "enc_dec_mask"] + datatype = torch.int64 + + # Broadcast data. + if data_iterator is not None: + data = next(data_iterator) + else: + data = None + data_b = tensor_parallel.broadcast_data(keys, data, datatype) + + # Unpack. + tokens_enc = data_b["text_enc"].long() + tokens_dec = data_b["text_dec"].long() + labels = data_b["labels"].long() + loss_mask = data_b["loss_mask"].float() + + enc_mask = data_b["enc_mask"] < 0.5 + dec_mask = data_b["dec_mask"] < 0.5 + enc_dec_mask = data_b["enc_dec_mask"] < 0.5 + + return tokens_enc, tokens_dec, loss_mask, labels, enc_mask, dec_mask, enc_dec_mask + + def get_batch_transformer(data_iterator): + """Build the batch.""" + data = next(data_iterator) + data = send_to_device(data, torch.cuda.current_device()) + + tokens_enc = data["input_ids"].long() + labels = data["labels"].long() + loss_mask = (labels != -100).to(torch.float) + if "decoder_input_ids" in data: + tokens_dec = data["decoder_input_ids"].long() + else: + tokens_dec = labels.new_zeros(labels.shape, device=labels.device, dtype=torch.long) + tokens_dec[..., 1:] = labels[..., :-1].clone() + tokens_dec[..., 0] = 0 + tokens_dec.masked_fill_(tokens_dec == -100, 0) + enc_mask = T5TrainStep.attn_mask_postprocess(data["attention_mask"].long()) + dec_mask = T5TrainStep.get_decoder_mask(tokens_dec.shape[1], tokens_dec.device) + enc_dec_mask = T5TrainStep.get_enc_dec_mask( + data["attention_mask"].long(), tokens_dec.shape[1], tokens_dec.device + ) + + return tokens_enc, tokens_dec, loss_mask, labels, enc_mask, dec_mask, enc_dec_mask + + if accelerator.state.megatron_lm_plugin.custom_get_batch_function is not None: + return accelerator.state.megatron_lm_plugin.custom_get_batch_function + if megatron_dataset_flag: + try: + # Use '--no-use-pep517 -e' to pip install nvidia's megatron from source + from pretrain_t5 import get_batch + + return get_batch + except ImportError: + pass + return get_batch_megatron + else: + return get_batch_transformer + + def get_loss_func(self, accelerator): + def loss_func(loss_mask, output_tensor): + lm_loss_ = output_tensor.float() + lm_loss = torch.sum(lm_loss_.view(-1) * loss_mask.reshape(-1)) / loss_mask.sum() + + loss = lm_loss + averaged_losses = average_losses_across_data_parallel_group([lm_loss]) + + return loss, {"lm loss": averaged_losses[0]} + + if accelerator.state.megatron_lm_plugin.custom_loss_function is not None: + return accelerator.state.megatron_lm_plugin.custom_loss_function + return loss_func + + def get_forward_step_func(self): + def forward_step(data_iterator, model): + """Forward step.""" + # Get the batch. + tokens_enc, tokens_dec, loss_mask, lm_labels, enc_mask, dec_mask, enc_dec_mask = self.get_batch( + data_iterator + ) + # Forward model lm_labels + output_tensor = model( + tokens_enc, tokens_dec, enc_mask, dec_mask, enc_dec_mask, tokentype_ids=None, lm_labels=lm_labels + ) + + return output_tensor, partial(self.loss_func, loss_mask) + + return forward_step + + +def finish_mpu_init(): + # torch.distributed initialization + args = get_args() + # Pytorch distributed. + _initialize_distributed() + + # Random seeds for reproducibility. + if args.rank == 0: + print(f"> setting random seeds to {args.seed} ...") + _set_random_seed(args.seed, args.data_parallel_random_init) + + +# intialize megatron setup +def initialize(accelerator, extra_args_provider=None, args_defaults={}): + accelerator.print("Initializing Megatron-LM") + assert torch.cuda.is_available(), "Megatron requires CUDA." + + # Parse arguments + args = parse_args(extra_args_provider, ignore_unknown_args=True) + + # Set defaults + for key, value in args_defaults.items(): + if getattr(args, key, None) is not None: + if args.rank == 0: + print( + f"WARNING: overriding default arguments for {key}:{getattr(args, key)} with {key}:{value}", + flush=True, + ) + setattr(args, key, value) + + if args.use_checkpoint_args or args_defaults.get("use_checkpoint_args", False): + assert args.load is not None, "--use-checkpoints-args requires --load argument" + load_args_from_checkpoint(args) + + validate_args(args) + + # set global args, build tokenizer, and set adlr-autoresume, + # tensorboard-writer, and timers. + set_global_variables(args) + + # Megatron's MPU is the master. Complete initialization right away. + finish_mpu_init() + + # Autoresume. + _init_autoresume() + + # Compile dependencies. + _compile_dependencies() + + # Set pytorch JIT layer fusion options and warmup JIT functions. + set_jit_fusion_options() + args = get_args() + if getattr(args, "padded_vocab_size", None) is None: + args.padded_vocab_size = _vocab_size_with_padding(args.orig_vocab_size, args) + if args.model_type_name == "bert" and args.pretraining_flag and args.num_labels == 2: + args.bert_binary_head = True + else: + args.bert_binary_head = False + args.iteration = 0 + + +class MegatronEngine(torch.nn.Module): + """ + Megatron-LM model wrapper + + Args: + accelerator (:class:`~accelerate.Accelerator`): The accelerator object to use. + model: Megatron-LM model + optimizer: Megatron-LM optimizer + lr_scheduler: Megatron-LM lr scheduler + """ + + def __init__(self, accelerator, model, optimizer, scheduler): + super().__init__() + self.module = model + self.base_model = model[0] + self.optimizer = optimizer + self.scheduler = scheduler + args = get_args() + if accelerator.state.megatron_lm_plugin.custom_train_step_class is not None: + self.train_step_handler = accelerator.state.megatron_lm_plugin.custom_train_step_class( + args, **accelerator.state.megatron_lm_plugin.custom_train_step_kwargs + ) + elif args.model_type_name == "bert": + self.train_step_handler = BertTrainStep(accelerator, args) + elif args.model_type_name == "gpt": + self.train_step_handler = GPTTrainStep(accelerator, args) + elif args.model_type_name == "t5": + self.train_step_handler = T5TrainStep(accelerator, args) + else: + raise ValueError(f"Unsupported model type: {args.model_type_name}") + self.optimizer.skipped_iter = False + + # Tracking loss. + self.total_loss_dict = {} + self.eval_total_loss_dict = {} + self.iteration = 0 + self.report_memory_flag = True + self.num_floating_point_operations_so_far = 0 + self.module_config = None + if args.tensorboard_dir is not None: + write_args_to_tensorboard() + + def get_module_config(self): + args = get_args() + config = get_model_config(self.module[0]) + # Setup some training config params + config.grad_scale_func = self.optimizer.scale_loss + if isinstance(self.module[0], LocalDDP) and args.overlap_grad_reduce: + assert config.no_sync_func is None, ( + "When overlap_grad_reduce is True, config.no_sync_func must be None; " + "a custom no_sync_func is not supported when overlapping grad-reduce" + ) + config.no_sync_func = [model_chunk.no_sync for model_chunk in self.module] + if len(self.module) == 1: + config.no_sync_func = config.no_sync_func[0] + if args.delay_grad_reduce: + config.grad_sync_func = [model_chunk.start_grad_sync for model_chunk in self.module] + if len(self.module) == 1: + config.grad_sync_func = config.grad_sync_func[0] + if args.overlap_param_gather and args.delay_param_gather: + config.param_sync_func = [ + lambda x: self.optimizer.finish_param_sync(model_index, x) for model_index in range(len(self.module)) + ] + if len(self.module) == 1: + config.param_sync_func = config.param_sync_func[0] + config.finalize_model_grads_func = finalize_model_grads + return config + + def train(self): + for model_module in self.module: + model_module.train() + + if self.module_config is None: + self.module_config = self.get_module_config() + + self.log_eval_results() + + def eval(self): + for model_module in self.module: + model_module.eval() + + if self.module_config is None: + self.module_config = self.get_module_config() + + def get_batch_data_iterator(self, batch_data): + args = get_args() + data_chunks = [] + if len(batch_data) > 0: + if args.num_micro_batches > 1: + for i in range(0, args.num_micro_batches): + data_chunks.append( + { + k: v[i * args.micro_batch_size : (i + 1) * args.micro_batch_size] + for k, v in batch_data.items() + } + ) + else: + data_chunks = [batch_data] + + if len(self.module) > 1: + batch_data_iterator = ( + [iter(data_chunks) for _ in range(len(self.module))] + if len(batch_data) > 0 + else [None] * len(self.module) + ) + else: + batch_data_iterator = iter(data_chunks) if len(batch_data) > 0 else None + return batch_data_iterator + + def train_step(self, **batch_data): + """ + Training step for Megatron-LM + + Args: + batch_data (:obj:`dict`): The batch data to train on. + """ + + batch_data_iterator = self.get_batch_data_iterator(batch_data) + + loss_reduced, skipped_iter, grad_norm, num_zeros_in_grad = train_step( + forward_step_func=self.train_step_handler.forward_step, + data_iterator=batch_data_iterator, + model=self.module, + optimizer=self.optimizer, + opt_param_scheduler=self.scheduler, + config=self.module_config, + ) + + self.optimizer.skipped_iter = skipped_iter == 1 + + return loss_reduced, skipped_iter, grad_norm, num_zeros_in_grad + + def eval_step(self, **batch_data): + """ + Evaluation step for Megatron-LM + + Args: + batch_data (:obj:`dict`): The batch data to evaluate on. + """ + + args = get_args() + batch_data_iterator = self.get_batch_data_iterator(batch_data) + forward_backward_func = get_forward_backward_func() + loss_dicts = forward_backward_func( + forward_step_func=self.train_step_handler.forward_step, + data_iterator=batch_data_iterator, + model=self.module, + num_microbatches=get_num_microbatches(), + seq_length=args.seq_length, + micro_batch_size=args.micro_batch_size, + forward_only=True, + ) + # Empty unused memory + if args.empty_unused_memory_level >= 1: + torch.cuda.empty_cache() + + args.consumed_valid_samples += ( + mpu.get_data_parallel_world_size() * args.micro_batch_size * get_num_microbatches() + ) + + if mpu.is_pipeline_last_stage(ignore_virtual=True): + # Average loss across microbatches. + loss_reduced = {} + for key in loss_dicts[0]: + losses_reduced_for_key = [x[key] for x in loss_dicts] + if len(losses_reduced_for_key[0].shape) == 0: + loss_reduced[key] = sum(losses_reduced_for_key) / len(losses_reduced_for_key) + else: + loss_reduced[key] = torch.concat(losses_reduced_for_key) + return loss_reduced + return {} + + def forward(self, **batch_data): + # During training, we use train_step() + # model(**batch_data) performs following operations by delegating it to `self.train_step`: + # 1. Prepare **batch_data for Tendor, Pipeline and Model Parallelism + # 2. Set grad to zero. + # 3. forward pass and backward pass using Pipeline Parallelism + # 4. Empty unused memory. + # 5. Reduce gradients. + # 6. Update parameters. + # 7. Gather params when using Distributed Optimizer (Data Parallelism). + # 8. Update learning rate if scheduler is specified. + # 9. Empty unused memory. + # 10. Average loss across microbatches and across DP ranks. + # + # During evaluation, we use eval_step() + args = get_args() + if self.module[0].training: + loss_dict, skipped_iter, grad_norm, num_zeros_in_grad = self.train_step(**batch_data) + self.iteration += 1 + batch_size = mpu.get_data_parallel_world_size() * args.micro_batch_size * get_num_microbatches() + args.consumed_train_samples += batch_size + self.num_floating_point_operations_so_far += num_floating_point_operations(args, batch_size) + if args.tensorboard_dir is not None: + # Logging. + loss_scale = self.optimizer.get_loss_scale().item() + params_norm = None + if args.log_params_norm: + params_norm = calc_params_l2_norm(self.model) + self.report_memory_flag = training_log( + loss_dict, + self.total_loss_dict, + self.optimizer.param_groups[0]["lr"], + self.iteration, + loss_scale, + self.report_memory_flag, + skipped_iter, + grad_norm, + params_norm, + num_zeros_in_grad, + ) + else: + loss_dict = self.eval_step(**batch_data) + if args.tensorboard_dir is not None: + for key in loss_dict: + self.eval_total_loss_dict[key] = ( + self.eval_total_loss_dict.get(key, torch.cuda.FloatTensor([0.0])) + loss_dict[key] + ) + self.eval_total_loss_dict[key + "_num_iters"] = self.eval_total_loss_dict.get( + key + "_num_iters", torch.cuda.FloatTensor([0.0]) + ) + torch.cuda.FloatTensor([1.0]) + + loss = torch.tensor(0.0, device=torch.cuda.current_device()) + for key in loss_dict: + if len(loss_dict[key].shape) == 0: + loss += loss_dict[key] + + logits = None + if "logits" in loss_dict: + logits = loss_dict["logits"] + if self.train_step_handler.model_output_class is not None: + return self.train_step_handler.model_output_class(loss=loss, logits=logits) + return loss + + def log_eval_results(self): + args = get_args() + if args.tensorboard_dir is None or self.iteration == 0: + return + args = get_args() + writer = get_tensorboard_writer() + string = f"validation loss at iteration {self.iteration} | " + for key in self.eval_total_loss_dict: + if key.endswith("_num_iters"): + continue + value = self.eval_total_loss_dict[key] / self.eval_total_loss_dict[key + "_num_iters"] + string += f"{key} value: {value} | " + ppl = math.exp(min(20, value.item())) + if args.pretraining_flag: + string += f"{key} PPL: {ppl} | " + if writer: + writer.add_scalar(f"{key} validation", value.item(), self.iteration) + if args.pretraining_flag: + writer.add_scalar(f"{key} validation ppl", ppl, self.iteration) + + length = len(string) + 1 + print_rank_last("-" * length) + print_rank_last(string) + print_rank_last("-" * length) + self.eval_total_loss_dict = {} + + def save_checkpoint(self, output_dir): + self.log_eval_results() + args = get_args() + args.save = output_dir + torch.distributed.barrier() + save_checkpoint( + self.iteration, + self.module, + self.optimizer, + self.scheduler, + num_floating_point_operations_so_far=self.num_floating_point_operations_so_far, + ) + torch.distributed.barrier() + + def load_checkpoint(self, input_dir): + args = get_args() + args.load = input_dir + args.consumed_train_samples = 0 + args.consumed_valid_samples = 0 + torch.distributed.barrier() + iteration, num_floating_point_operations_so_far = load_checkpoint(self.module, self.optimizer, self.scheduler) + torch.distributed.barrier() + self.iteration = iteration + self.num_floating_point_operations_so_far = num_floating_point_operations_so_far + if args.fp16 and self.iteration == 0: + self.optimizer.reload_model_params() + + def megatron_generate( + self, + inputs, + attention_mask=None, + max_length=None, + max_new_tokens=None, + num_beams=None, + temperature=None, + top_k=None, + top_p=None, + length_penalty=None, + **kwargs, + ): + """ + Generate method for GPT2 model. This method is used for inference. Supports both greedy and beam search along + with sampling. Refer the Megatron-LM repo for more details + + Args: + inputs (torch.Tensor): input ids + attention_mask (torch.Tensor, optional): attention mask. Defaults to None. + max_length (int, optional): max length of the generated sequence. Defaults to None. + Either this or max_new_tokens should be provided. + max_new_tokens (int, optional): max number of tokens to be generated. Defaults to None. + Either this or max_length should be provided. + num_beams (int, optional): number of beams to use for beam search. Defaults to None. + temperature (float, optional): temperature for sampling. Defaults to 1.0. + top_k (int, optional): top k tokens to consider for sampling. Defaults to 0.0. + top_p (float, optional): tokens in top p probability are considered for sampling. Defaults to 0.0. + length_penalty (float, optional): length penalty for beam search. Defaults to None. + kwargs: additional key-value arguments + """ + + # checking if required arguments are passed + args = get_args() + if args.model_type_name != "gpt": + raise NotImplementedError("Generate method is not implemented for this model") + + if args.data_parallel_size > 1: + raise ValueError("Generate method requires data parallelism to be 1") + + if args.sequence_parallel: + raise ValueError("Generate method requires sequence parallelism to be False") + + if args.recompute_granularity is not None: + raise ValueError("Checkpoint activations cannot be set for inference") + + if args.vocab_file is None: + raise ValueError("Vocab file is required for inference") + + # Prepare inputs + if max_length is None and max_new_tokens is None: + raise ValueError("`max_length` or `max_new_tokens` are required for inference") + + if temperature is None: + temperature = 1.0 + elif not (0.0 < temperature <= 100.0): + raise ValueError("temperature must be a positive number less than or equal to 100.0") + + if top_k is None: + top_k = 0 + elif not (0 <= top_k <= 1000): + raise ValueError("top_k must be a positive number less than or equal to 1000") + + if top_p is None: + top_p = 0.0 + elif top_p > 0.0 and top_k > 0.0: + raise ValueError("top_p and top_k sampling cannot be set together") + else: + if not (0.0 <= top_p <= 1.0): + raise ValueError("top_p must be less than or equal to 1.0") + + top_p_decay = kwargs.get("top_p_decay", 0.0) + if not (0.0 <= top_p_decay <= 1.0): + raise ValueError("top_p_decay must be less than or equal to 1.0") + + top_p_bound = kwargs.get("top_p_bound", 0.0) + if not (0.0 <= top_p_bound <= 1.0): + raise ValueError("top_p_bound must be less than or equal to 1.0") + + add_BOS = kwargs.get("add_BOS", False) + if not (isinstance(add_BOS, bool)): + raise ValueError("add_BOS must be a boolean") + + beam_width = num_beams + if beam_width is not None: + if not isinstance(beam_width, int): + raise ValueError("beam_width must be an integer") + if beam_width < 1: + raise ValueError("beam_width must be greater than 0") + if inputs.shape[0] > 1: + return "When doing beam_search, batch size must be 1" + + tokenizer = get_tokenizer() + + stop_token = kwargs.get("stop_token", tokenizer.eod) + if stop_token is not None: + if not isinstance(stop_token, int): + raise ValueError("stop_token must be an integer") + + if length_penalty is None: + length_penalty = 1.0 + + sizes_list = None + prompts_tokens_tensor = None + prompts_length_tensor = None + if torch.distributed.get_rank() == 0: + # Get the prompts length. + if attention_mask is None: + prompts_length_tensor = torch.cuda.LongTensor([inputs.shape[1]] * inputs.shape[0]) + else: + prompts_length_tensor = attention_mask.sum(axis=-1).cuda() + + if max_new_tokens is None: + max_new_tokens = max_length - inputs.shape[1] + if max_new_tokens <= 0: + raise ValueError("max_new_tokens must be greater than 0") + + if add_BOS: + max_length = max_new_tokens + inputs.shape[1] + 1 + # making sure that `max_length` is a multiple of 4 to leverage fused kernels + max_length = 4 * math.ceil(max_length / 4) + max_new_tokens = max_length - (inputs.shape[1] + 1) + padding = torch.cuda.LongTensor([[tokenizer.eod] * max_new_tokens] * inputs.shape[0]) + prompts_tokens_tensor = torch.concat( + [torch.unsqueeze(padding[:, 0], axis=-1), inputs.cuda(), padding], axis=-1 + ) + else: + # making sure that `max_length` is a multiple of 4 to leverage fused kernels + max_length = max_new_tokens + inputs.shape[1] + max_length = 4 * math.ceil(max_length / 4) + max_new_tokens = max_length - inputs.shape[1] + padding = torch.cuda.LongTensor([[tokenizer.eod] * max_new_tokens] * inputs.shape[0]) + prompts_tokens_tensor = torch.concat([inputs.cuda(), padding], axis=-1) + + # We need the sizes of these tensors for the boradcast + sizes_list = [ + prompts_tokens_tensor.size(0), # Batch size + prompts_tokens_tensor.size(1), + ] # Sequence length + + # First, broadcast the sizes. + sizes_tensor = broadcast_int_list(2, int_list=sizes_list, rank=0) + + # Now that we have the sizes, we can boradcast the tokens + # and length tensors. + sizes = sizes_tensor.tolist() + context_tokens_tensor = broadcast_tensor(sizes, torch.int64, tensor=prompts_tokens_tensor, rank=0) + context_length_tensor = broadcast_tensor(sizes[0], torch.int64, tensor=prompts_length_tensor, rank=0) + + # Run the inference + random_seed = kwargs.get("random_seed", 0) + torch.random.manual_seed(random_seed) + unwrapped_model = unwrap_model(self.base_model, (torchDDP, LocalDDP, Float16Module)) + if beam_width is not None: + tokens, _ = beam_search_and_return_on_first_stage( + unwrapped_model, + context_tokens_tensor, + context_length_tensor, + beam_width, + stop_token=stop_token, + num_return_gen=1, + length_penalty=length_penalty, + ) + else: + tokens, _, _ = generate_tokens_probs_and_return_on_first_stage( + unwrapped_model, + context_tokens_tensor, + context_length_tensor, + return_output_log_probs=False, + top_k=top_k, + top_p=top_p, + top_p_decay=top_p_decay, + top_p_bound=top_p_bound, + temperature=temperature, + use_eod_token_for_early_termination=True, + ) + return tokens + + +# other utilities +def avg_losses_across_data_parallel_group(losses): + """ + Average losses across data parallel group. + + Args: + losses (List[Tensor]): List of losses to average across data parallel group. + """ + + return average_losses_across_data_parallel_group(losses) + + +def gather_across_data_parallel_groups(tensor): + """ + Recursively gather tensor in a nested list/tuple/dictionary of tensors from data parallel ranks. + + Args: + tensor (nested list/tuple/dictionary of `torch.Tensor`): + The data to gather across data parallel ranks. + + """ + + def _gpu_gather_one(tensor): + if tensor.ndim == 0: + tensor = tensor.clone()[None] + output_tensors = [ + torch.empty_like(tensor) + for _ in range(torch.distributed.get_world_size(group=mpu.get_data_parallel_group())) + ] + torch.distributed.all_gather(output_tensors, tensor, group=mpu.get_data_parallel_group()) + return torch.cat(output_tensors, dim=0) + + return recursively_apply(_gpu_gather_one, tensor, error_on_other_type=True) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/memory.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/memory.py new file mode 100644 index 0000000000000000000000000000000000000000..e25649168ab85f189c9b115898611840858389fe --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/memory.py @@ -0,0 +1,207 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +A collection of utilities for ensuring that training can always occur. Heavily influenced by the +[toma](https://github.com/BlackHC/toma) library. +""" + +import functools +import gc +import importlib +import inspect +import warnings + +import torch +from packaging import version + +from .imports import ( + is_cuda_available, + is_hpu_available, + is_ipex_available, + is_mlu_available, + is_mps_available, + is_musa_available, + is_npu_available, + is_sdaa_available, + is_xpu_available, +) +from .versions import compare_versions + + +def clear_device_cache(garbage_collection=False): + """ + Clears the device cache by calling `torch.{backend}.empty_cache`. Can also run `gc.collect()`, but do note that + this is a *considerable* slowdown and should be used sparingly. + """ + if garbage_collection: + gc.collect() + + if is_xpu_available(): + torch.xpu.empty_cache() + elif is_mlu_available(): + torch.mlu.empty_cache() + elif is_sdaa_available(): + torch.sdaa.empty_cache() + elif is_musa_available(): + torch.musa.empty_cache() + elif is_npu_available(): + torch.npu.empty_cache() + elif is_mps_available(min_version="2.0"): + torch.mps.empty_cache() + elif is_cuda_available(): + torch.cuda.empty_cache() + elif is_hpu_available(): + # torch.hpu.empty_cache() # not available on hpu as it reserves all device memory for the current process + pass + + +def release_memory(*objects): + """ + Releases memory from `objects` by setting them to `None` and calls `gc.collect()` and `torch.cuda.empty_cache()`. + Returned objects should be reassigned to the same variables. + + Args: + objects (`Iterable`): + An iterable of objects + Returns: + A list of `None` objects to replace `objects` + + Example: + + ```python + >>> import torch + >>> from accelerate.utils import release_memory + + >>> a = torch.ones(1000, 1000).cuda() + >>> b = torch.ones(1000, 1000).cuda() + >>> a, b = release_memory(a, b) + ``` + """ + if not isinstance(objects, list): + objects = list(objects) + for i in range(len(objects)): + objects[i] = None + clear_device_cache(garbage_collection=True) + return objects + + +def should_reduce_batch_size(exception: Exception) -> bool: + """ + Checks if `exception` relates to CUDA out-of-memory, XPU out-of-memory, CUDNN not supported, or CPU out-of-memory + + Args: + exception (`Exception`): + An exception + """ + _statements = [ + " out of memory.", # OOM for CUDA, HIP, XPU + "cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.", # CUDNN SNAFU + "DefaultCPUAllocator: can't allocate memory", # CPU OOM + "FATAL ERROR :: MODULE:PT_DEVMEM Allocation failed", # HPU OOM + ] + if isinstance(exception, RuntimeError) and len(exception.args) == 1: + return any(err in exception.args[0] for err in _statements) + return False + + +def find_executable_batch_size( + function: callable = None, starting_batch_size: int = 128, reduce_batch_size_fn: callable = None +): + """ + A basic decorator that will try to execute `function`. If it fails from exceptions related to out-of-memory or + CUDNN, the batch size is multiplied by 0.9 and passed to `function` + + `function` must take in a `batch_size` parameter as its first argument. + + Args: + function (`callable`, *optional*): + A function to wrap + starting_batch_size (`int`, *optional*): + The batch size to try and fit into memory + + Example: + + ```python + >>> from accelerate.utils import find_executable_batch_size + + + >>> @find_executable_batch_size(starting_batch_size=128) + ... def train(batch_size, model, optimizer): + ... ... + + + >>> train(model, optimizer) + ``` + """ + if function is None: + return functools.partial(find_executable_batch_size, starting_batch_size=starting_batch_size) + + batch_size = starting_batch_size + if reduce_batch_size_fn is None: + + def reduce_batch_size_fn(): + nonlocal batch_size + batch_size = int(batch_size * 0.9) + return batch_size + + def decorator(*args, **kwargs): + nonlocal batch_size + clear_device_cache(garbage_collection=True) + params = list(inspect.signature(function).parameters.keys()) + # Guard against user error + if len(params) < (len(args) + 1): + arg_str = ", ".join([f"{arg}={value}" for arg, value in zip(params[1:], args[1:])]) + raise TypeError( + f"Batch size was passed into `{function.__name__}` as the first argument when called." + f"Remove this as the decorator already does so: `{function.__name__}({arg_str})`" + ) + while True: + if batch_size == 0: + raise RuntimeError("No executable batch size found, reached zero.") + try: + return function(batch_size, *args, **kwargs) + except Exception as e: + if should_reduce_batch_size(e): + clear_device_cache(garbage_collection=True) + batch_size = reduce_batch_size_fn() + else: + raise + + return decorator + + +def get_xpu_available_memory(device_index: int): + if version.parse(torch.__version__).release >= version.parse("2.6").release: + # torch.xpu.mem_get_info API is available starting from PyTorch 2.6 + # It further requires PyTorch built with the SYCL runtime which supports API + # to query available device memory. If not available, exception will be + # raised. Version of SYCL runtime used to build PyTorch is being reported + # with print(torch.version.xpu) and corresponds to the version of Intel DPC++ + # SYCL compiler. First version to support required feature is 20250001. + try: + return torch.xpu.mem_get_info(device_index)[0] + except Exception: + pass + elif is_ipex_available(): + ipex_version = version.parse(importlib.metadata.version("intel_extension_for_pytorch")) + if compare_versions(ipex_version, ">=", "2.5"): + from intel_extension_for_pytorch.xpu import mem_get_info + + return mem_get_info(device_index)[0] + + warnings.warn( + "The XPU `mem_get_info` API is available in IPEX version >=2.5 or PyTorch >=2.6. The current returned available memory is incorrect. Please consider upgrading your IPEX or PyTorch version." + ) + return torch.xpu.max_memory_allocated(device_index) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/modeling.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/modeling.py new file mode 100644 index 0000000000000000000000000000000000000000..dccac1a8c5add94299a13f33005b0263c7f01ca3 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/modeling.py @@ -0,0 +1,2198 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import contextlib +import gc +import inspect +import json +import logging +import os +import re +import shutil +import tempfile +import warnings +from collections import OrderedDict, defaultdict +from typing import Optional, Union + +import torch +from torch import distributed as dist +from torch import nn + +from ..state import AcceleratorState +from .constants import SAFE_WEIGHTS_NAME, WEIGHTS_NAME +from .dataclasses import AutocastKwargs, CustomDtype, DistributedType +from .imports import ( + is_hpu_available, + is_mlu_available, + is_mps_available, + is_musa_available, + is_npu_available, + is_peft_available, + is_sdaa_available, + is_torch_xla_available, + is_xpu_available, +) +from .memory import clear_device_cache, get_xpu_available_memory +from .offload import load_offloaded_weight, offload_weight, save_offload_index +from .tqdm import is_tqdm_available, tqdm +from .versions import is_torch_version + + +if is_npu_available(check_device=False): + import torch_npu # noqa: F401 + +if is_mlu_available(check_device=False): + import torch_mlu # noqa: F401 + +if is_sdaa_available(check_device=False): + import torch_sdaa # noqa: F401 + +if is_musa_available(check_device=False): + import torch_musa # noqa: F401 + +from safetensors import safe_open +from safetensors.torch import load_file as safe_load_file + + +WEIGHTS_INDEX_NAME = "pytorch_model.bin.index.json" + +logger = logging.getLogger(__name__) + + +def is_peft_model(model): + from .other import extract_model_from_parallel + + if is_peft_available(): + from peft import PeftModel + + return is_peft_available() and isinstance(extract_model_from_parallel(model), PeftModel) + + +def check_device_same(first_device, second_device): + """ + Utility method to check if two `torch` devices are similar. When dealing with CUDA devices, torch throws `False` + for `torch.device("cuda") == torch.device("cuda:0")` whereas they should be the same + + Args: + first_device (`torch.device`): + First device to check + second_device (`torch.device`): + Second device to check + """ + if first_device.type != second_device.type: + return False + + if first_device.type != "cpu" and first_device.index is None: + # In case the first_device is a cuda device and have + # the index attribute set to `None`, default it to `0` + first_device = torch.device(first_device.type, index=0) + + if second_device.type != "cpu" and second_device.index is None: + # In case the second_device is a cuda device and have + # the index attribute set to `None`, default it to `0` + second_device = torch.device(second_device.type, index=0) + + return first_device == second_device + + +def convert_file_size_to_int(size: Union[int, str]): + """ + Converts a size expressed as a string with digits an unit (like `"5MB"`) to an integer (in bytes). + + Args: + size (`int` or `str`): The size to convert. Will be directly returned if an `int`. + + Example: + + ```py + >>> convert_file_size_to_int("1MiB") + 1048576 + ``` + """ + mem_size = -1 + err_msg = ( + f"`size` {size} is not in a valid format. Use an integer for bytes, or a string with an unit (like '5.0GB')." + ) + try: + if isinstance(size, int): + mem_size = size + elif size.upper().endswith("GIB"): + mem_size = int(float(size[:-3]) * (2**30)) + elif size.upper().endswith("MIB"): + mem_size = int(float(size[:-3]) * (2**20)) + elif size.upper().endswith("KIB"): + mem_size = int(float(size[:-3]) * (2**10)) + elif size.upper().endswith("GB"): + int_size = int(float(size[:-2]) * (10**9)) + mem_size = int_size // 8 if size.endswith("b") else int_size + elif size.upper().endswith("MB"): + int_size = int(float(size[:-2]) * (10**6)) + mem_size = int_size // 8 if size.endswith("b") else int_size + elif size.upper().endswith("KB"): + int_size = int(float(size[:-2]) * (10**3)) + mem_size = int_size // 8 if size.endswith("b") else int_size + except ValueError: + raise ValueError(err_msg) + + if mem_size < 0: + raise ValueError(err_msg) + return mem_size + + +def dtype_byte_size(dtype: torch.dtype): + """ + Returns the size (in bytes) occupied by one parameter of type `dtype`. + + Example: + + ```py + >>> dtype_byte_size(torch.float32) + 4 + ``` + """ + if dtype == torch.bool: + return 1 / 8 + elif dtype == CustomDtype.INT2: + return 1 / 4 + elif dtype == CustomDtype.INT4: + return 1 / 2 + elif dtype == CustomDtype.FP8: + return 1 + elif is_torch_version(">=", "2.1.0") and dtype in [torch.float8_e4m3fn, torch.float8_e5m2]: + return 1 + bit_search = re.search(r"[^\d](\d+)$", str(dtype)) + if bit_search is None: + raise ValueError(f"`dtype` is not a valid dtype: {dtype}.") + bit_size = int(bit_search.groups()[0]) + return bit_size // 8 + + +def id_tensor_storage(tensor: torch.Tensor) -> tuple[torch.device, int, int]: + """ + Unique identifier to a tensor storage. Multiple different tensors can share the same underlying storage. For + example, "meta" tensors all share the same storage, and thus their identifier will all be equal. This identifier is + guaranteed to be unique and constant for this tensor's storage during its lifetime. Two tensor storages with + non-overlapping lifetimes may have the same id. + """ + _SIZE = { + torch.int64: 8, + torch.float32: 4, + torch.int32: 4, + torch.bfloat16: 2, + torch.float16: 2, + torch.int16: 2, + torch.uint8: 1, + torch.int8: 1, + torch.bool: 1, + torch.float64: 8, + } + try: + storage_ptr = tensor.untyped_storage().data_ptr() + storage_size = tensor.untyped_storage().nbytes() + except Exception: + try: + # Fallback for torch==1.10 + storage_ptr = tensor.storage().data_ptr() + storage_size = tensor.storage().size() * _SIZE[tensor.dtype] + except NotImplementedError: + # Fallback for meta storage + storage_ptr = 0 + # On torch >=2.0 this is the tensor size + storage_size = tensor.nelement() * _SIZE[tensor.dtype] + + return tensor.device, storage_ptr, storage_size + + +def set_module_tensor_to_device( + module: nn.Module, + tensor_name: str, + device: Union[int, str, torch.device], + value: Optional[torch.Tensor] = None, + dtype: Optional[Union[str, torch.dtype]] = None, + fp16_statistics: Optional[torch.HalfTensor] = None, + tied_params_map: Optional[dict[int, dict[torch.device, torch.Tensor]]] = None, + non_blocking: bool = False, + clear_cache: bool = True, +): + """ + A helper function to set a given tensor (parameter of buffer) of a module on a specific device (note that doing + `param.to(device)` creates a new tensor not linked to the parameter, which is why we need this function). + + Args: + module (`torch.nn.Module`): + The module in which the tensor we want to move lives. + tensor_name (`str`): + The full name of the parameter/buffer. + device (`int`, `str` or `torch.device`): + The device on which to set the tensor. + value (`torch.Tensor`, *optional*): + The value of the tensor (useful when going from the meta device to any other device). + dtype (`torch.dtype`, *optional*): + If passed along the value of the parameter will be cast to this `dtype`. Otherwise, `value` will be cast to + the dtype of the existing parameter in the model. + fp16_statistics (`torch.HalfTensor`, *optional*): + The list of fp16 statistics to set on the module, used for 8 bit model serialization. + tied_params_map (Dict[int, Dict[torch.device, torch.Tensor]], *optional*, defaults to `None`): + A map of current data pointers to dictionaries of devices to already dispatched tied weights. For a given + execution device, this parameter is useful to reuse the first available pointer of a shared weight on the + device for all others, instead of duplicating memory. + non_blocking (`bool`, *optional*, defaults to `False`): + If `True`, the device transfer will be asynchronous with respect to the host, if possible. + clear_cache (`bool`, *optional*, defaults to `True`): + Whether or not to clear the device cache after setting the tensor on the device. + """ + # Recurse if needed + if "." in tensor_name: + splits = tensor_name.split(".") + for split in splits[:-1]: + new_module = getattr(module, split) + if new_module is None: + raise ValueError(f"{module} has no attribute {split}.") + module = new_module + tensor_name = splits[-1] + + if tensor_name not in module._parameters and tensor_name not in module._buffers: + raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}.") + is_buffer = tensor_name in module._buffers + old_value = getattr(module, tensor_name) + + # Treat the case where old_value (or a custom `value`, typically offloaded to RAM/disk) belongs to a tied group, and one of the weight + # in the tied group has already been dispatched to the device, by avoiding reallocating memory on the device and just copying the pointer. + if ( + value is not None + and tied_params_map is not None + and value.data_ptr() in tied_params_map + and device in tied_params_map[value.data_ptr()] + ): + module._parameters[tensor_name] = tied_params_map[value.data_ptr()][device] + return + elif ( + tied_params_map is not None + and old_value.data_ptr() in tied_params_map + and device in tied_params_map[old_value.data_ptr()] + ): + module._parameters[tensor_name] = tied_params_map[old_value.data_ptr()][device] + return + + if old_value.device == torch.device("meta") and device not in ["meta", torch.device("meta")] and value is None: + raise ValueError(f"{tensor_name} is on the meta device, we need a `value` to put in on {device}.") + + param = module._parameters[tensor_name] if tensor_name in module._parameters else None + param_cls = type(param) + + if value is not None: + # We can expect mismatches when using bnb 4bit since Params4bit will reshape and pack the weights. + # In other cases, we want to make sure we're not loading checkpoints that do not match the config. + if old_value.shape != value.shape and param_cls.__name__ != "Params4bit": + raise ValueError( + f'Trying to set a tensor of shape {value.shape} in "{tensor_name}" (which has shape {old_value.shape}), this looks incorrect.' + ) + + if dtype is None: + # For compatibility with PyTorch load_state_dict which converts state dict dtype to existing dtype in model + value = value.to(old_value.dtype, non_blocking=non_blocking) + elif not str(value.dtype).startswith(("torch.uint", "torch.int", "torch.bool")): + value = value.to(dtype, non_blocking=non_blocking) + + device_quantization = None + with torch.no_grad(): + # leave it on cpu first before moving them to cuda + # # fix the case where the device is meta, we don't want to put it on cpu because there is no data =0 + if ( + param is not None + and param.device.type not in ("cuda", "xpu") + and torch.device(device).type in ("cuda", "xpu") + and param_cls.__name__ in ["Int8Params", "FP4Params", "Params4bit"] + ): + device_quantization = device + device = "cpu" + # `torch.Tensor.to()` is not supported by `torch_npu` (see this [issue](https://github.com/Ascend/pytorch/issues/16)). + if isinstance(device, int): + if is_npu_available(): + device = f"npu:{device}" + elif is_mlu_available(): + device = f"mlu:{device}" + elif is_sdaa_available(): + device = f"sdaa:{device}" + elif is_musa_available(): + device = f"musa:{device}" + elif is_hpu_available(): + device = "hpu" + if "xpu" in str(device) and not is_xpu_available(): + raise ValueError(f'{device} is not available, you should use device="cpu" instead') + if value is None: + new_value = old_value.to(device, non_blocking=non_blocking) + if dtype is not None and device in ["meta", torch.device("meta")]: + if not str(old_value.dtype).startswith(("torch.uint", "torch.int", "torch.bool")): + new_value = new_value.to(dtype, non_blocking=non_blocking) + + if not is_buffer: + module._parameters[tensor_name] = param_cls(new_value, requires_grad=old_value.requires_grad) + elif isinstance(value, torch.Tensor): + new_value = value.to(device, non_blocking=non_blocking) + else: + new_value = torch.tensor(value, device=device) + if device_quantization is not None: + device = device_quantization + if is_buffer: + module._buffers[tensor_name] = new_value + elif value is not None or not check_device_same(torch.device(device), module._parameters[tensor_name].device): + param_cls = type(module._parameters[tensor_name]) + kwargs = module._parameters[tensor_name].__dict__ + if param_cls.__name__ in ["Int8Params", "FP4Params", "Params4bit"]: + if param_cls.__name__ == "Int8Params" and new_value.dtype == torch.float32: + # downcast to fp16 if any - needed for 8bit serialization + new_value = new_value.to(torch.float16, non_blocking=non_blocking) + # quantize module that are going to stay on the cpu so that we offload quantized weights + if device == "cpu" and param_cls.__name__ == "Int8Params": + new_value = param_cls(new_value, requires_grad=old_value.requires_grad, **kwargs).to(0).to("cpu") + new_value.CB = new_value.CB.to("cpu") + new_value.SCB = new_value.SCB.to("cpu") + else: + new_value = param_cls(new_value, requires_grad=old_value.requires_grad, **kwargs).to( + device, non_blocking=non_blocking + ) + elif param_cls.__name__ in ["QTensor", "QBitsTensor"]: + new_value = torch.nn.Parameter(new_value, requires_grad=old_value.requires_grad).to( + device, non_blocking=non_blocking + ) + elif param_cls.__name__ in ["AffineQuantizedTensor"]: + new_value = new_value.to(device, non_blocking=non_blocking) + else: + new_value = param_cls(new_value, requires_grad=old_value.requires_grad).to( + device, non_blocking=non_blocking + ) + + module._parameters[tensor_name] = new_value + if fp16_statistics is not None: + module._parameters[tensor_name].SCB = fp16_statistics.to(device, non_blocking=non_blocking) + del fp16_statistics + # as we put the weight to meta, it doesn't have SCB attr anymore. make sure that it is not a meta weight + if ( + module.__class__.__name__ == "Linear8bitLt" + and getattr(module.weight, "SCB", None) is None + and str(module.weight.device) != "meta" + ): + # quantize only if necessary + device_index = torch.device(device).index if torch.device(device).type == "cuda" else None + if not getattr(module.weight, "SCB", None) and device_index is not None: + if module.bias is not None and module.bias.device.type != "meta": + # if a bias exists, we need to wait until the bias is set on the correct device + module = module.cuda(device_index) + elif module.bias is None: + # if no bias exists, we can quantize right away + module = module.cuda(device_index) + elif ( + module.__class__.__name__ == "Linear4bit" + and getattr(module.weight, "quant_state", None) is None + and str(module.weight.device) != "meta" + ): + # quantize only if necessary + device_index = torch.device(device).index if torch.device(device).type == "cuda" else None + if not getattr(module.weight, "quant_state", None) and device_index is not None: + module.weight = module.weight.cuda(device_index) + + # clean pre and post forward hook + if clear_cache and device != "cpu": + clear_device_cache() + + # When handling tied weights, we update tied_params_map to keep track of the tied weights that have already been allocated on the device in + # order to avoid duplicating memory, see above. + if ( + tied_params_map is not None + and old_value.data_ptr() in tied_params_map + and device not in tied_params_map[old_value.data_ptr()] + ): + tied_params_map[old_value.data_ptr()][device] = new_value + elif ( + value is not None + and tied_params_map is not None + and value.data_ptr() in tied_params_map + and device not in tied_params_map[value.data_ptr()] + ): + tied_params_map[value.data_ptr()][device] = new_value + + +def named_module_tensors( + module: nn.Module, include_buffers: bool = True, recurse: bool = False, remove_non_persistent: bool = False +): + """ + A helper function that gathers all the tensors (parameters + buffers) of a given module. If `include_buffers=True` + it's the same as doing `module.named_parameters(recurse=recurse) + module.named_buffers(recurse=recurse)`. + + Args: + module (`torch.nn.Module`): + The module we want the tensors on. + include_buffer (`bool`, *optional*, defaults to `True`): + Whether or not to include the buffers in the result. + recurse (`bool`, *optional`, defaults to `False`): + Whether or not to go look in every submodule or just return the direct parameters and buffers. + remove_non_persistent (`bool`, *optional*, defaults to `False`): + Whether or not to remove the non persistent buffer from the buffers. Useful only when include_buffers = + True + """ + yield from module.named_parameters(recurse=recurse) + + if include_buffers: + non_persistent_buffers = set() + if remove_non_persistent: + non_persistent_buffers = get_non_persistent_buffers(module, recurse=recurse) + for named_buffer in module.named_buffers(recurse=recurse): + name, _ = named_buffer + if name not in non_persistent_buffers: + yield named_buffer + + +def get_non_persistent_buffers(module: nn.Module, recurse: bool = False, fqns: bool = False): + """ + Gather all non persistent buffers of a given modules into a set + + Args: + module (`nn.Module`): + The module we want the non persistent buffers on. + recurse (`bool`, *optional*, defaults to `False`): + Whether or not to go look in every submodule or just return the direct non persistent buffers. + fqns (`bool`, *optional*, defaults to `False`): + Whether or not to return the fully-qualified names of the non persistent buffers. + """ + + non_persistent_buffers_set = module._non_persistent_buffers_set + if recurse: + for n, m in module.named_modules(): + if fqns: + non_persistent_buffers_set |= {n + "." + b for b in m._non_persistent_buffers_set} + else: + non_persistent_buffers_set |= m._non_persistent_buffers_set + + return non_persistent_buffers_set + + +class FindTiedParametersResult(list): + """ + This is a subclass of a list to handle backward compatibility for Transformers. Do not rely on the fact this is not + a list or on the `values` method as in the future this will be removed. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def values(self): + warnings.warn( + "The 'values' method of FindTiedParametersResult is deprecated and will be removed in Accelerate v1.3.0. ", + FutureWarning, + ) + return sum([x[1:] for x in self], []) + + +def check_tied_parameters_in_config(model: nn.Module): + """ + Check if there is any indication in the given model that some weights should be tied. + + Args: + model (`torch.nn.Module`): The model to inspect + + Returns: + bool: True if the model needs to have tied weights + """ + + # based on model.tie_weights() method + has_tied_word_embedding = False + has_tied_encoder_decoder = False + has_tied_module = False + + if "PreTrainedModel" in [c.__name__ for c in inspect.getmro(model.__class__)]: + has_tied_word_embedding = False + model_decoder_config = None + if hasattr(model, "config"): + model_decoder_config = ( + model.config.get_text_config(decoder=True) + if hasattr(model.config, "get_text_config") + else model.config + ) + has_tied_word_embedding = ( + model_decoder_config is not None + and getattr(model_decoder_config, "tie_word_embeddings", False) + and model.get_output_embeddings() + ) + + has_tied_encoder_decoder = ( + hasattr(model, "config") + and getattr(model.config, "is_encoder_decoder", False) + and getattr(model.config, "tie_encoder_decoder", False) + ) + has_tied_module = any(hasattr(module, "_tie_weights") for module in model.modules()) + return any([has_tied_word_embedding, has_tied_encoder_decoder, has_tied_module]) + + +def _get_param_device(param, device_map): + if param in device_map: + return device_map[param] + parent_param = ".".join(param.split(".")[:-1]) + if parent_param == param: + raise ValueError(f"The `device_map` does not contain the module {param}.") + else: + return _get_param_device(parent_param, device_map) + + +def check_tied_parameters_on_same_device(tied_params, device_map): + """ + Check if tied parameters are on the same device + + Args: + tied_params (`List[List[str]]`): + A list of lists of parameter names being all tied together. + + device_map (`Dict[str, Union[int, str, torch.device]]`): + A map that specifies where each submodule should go. + + """ + for tie_param in tied_params: + tie_param_devices = {} + for param in tie_param: + tie_param_devices[param] = _get_param_device(param, device_map) + if len(set(tie_param_devices.values())) > 1: + logger.warning( + f"Tied parameters are on different devices: {tie_param_devices}. " + "Please modify your custom device map or set `device_map='auto'`. " + ) + + +def find_tied_parameters(model: torch.nn.Module, **kwargs): + """ + Find the tied parameters in a given model. + + + + The signature accepts keyword arguments, but they are for the recursive part of this function and you should ignore + them. + + + + Args: + model (`torch.nn.Module`): The model to inspect. + + Returns: + List[List[str]]: A list of lists of parameter names being all tied together. + + Example: + + ```py + >>> from collections import OrderedDict + >>> import torch.nn as nn + + >>> model = nn.Sequential(OrderedDict([("linear1", nn.Linear(4, 4)), ("linear2", nn.Linear(4, 4))])) + >>> model.linear2.weight = model.linear1.weight + >>> find_tied_parameters(model) + [['linear1.weight', 'linear2.weight']] + ``` + """ + + # get ALL model parameters and their names + all_named_parameters = {name: param for name, param in model.named_parameters(remove_duplicate=False)} + + # get ONLY unique named parameters, + # if parameter is tied and have multiple names, it will be included only once + no_duplicate_named_parameters = {name: param for name, param in model.named_parameters(remove_duplicate=True)} + + # the difference of the two sets will give us the tied parameters + tied_param_names = set(all_named_parameters.keys()) - set(no_duplicate_named_parameters.keys()) + + # 'tied_param_names' contains the names of parameters that are tied in the model, but we do not know + # which names refer to the same parameter. To identify this, we need to group them together. + tied_param_groups = {} + for tied_param_name in tied_param_names: + tied_param = all_named_parameters[tied_param_name] + for param_name, param in no_duplicate_named_parameters.items(): + # compare if parameters are the same, if so, group their names together + if param is tied_param: + if param_name not in tied_param_groups: + tied_param_groups[param_name] = [] + tied_param_groups[param_name].append(tied_param_name) + + return FindTiedParametersResult([sorted([weight] + list(set(tied))) for weight, tied in tied_param_groups.items()]) + + +def retie_parameters(model, tied_params): + """ + Reties tied parameters in a given model if the link was broken (for instance when adding hooks). + + Args: + model (`torch.nn.Module`): + The model in which to retie parameters. + tied_params (`List[List[str]]`): + A mapping parameter name to tied parameter name as obtained by `find_tied_parameters`. + """ + for tied_group in tied_params: + param_to_tie = None + # two loops : the first one to set param_to_tie , the second one to change the values of tied_group + for param_name in tied_group: + module = model + splits = param_name.split(".") + for split in splits[:-1]: + module = getattr(module, split) + param = getattr(module, splits[-1]) + if param_to_tie is None and param.device != torch.device("meta"): + param_to_tie = param + break + if param_to_tie is not None: + for param_name in tied_group: + module = model + splits = param_name.split(".") + for split in splits[:-1]: + module = getattr(module, split) + setattr(module, splits[-1], param_to_tie) + + +def _get_proper_dtype(dtype: Union[str, torch.device]) -> torch.dtype: + """ + Just does torch.dtype(dtype) if necessary. + """ + if isinstance(dtype, str): + # We accept "torch.float16" or just "float16" + dtype = dtype.replace("torch.", "") + dtype = getattr(torch, dtype) + return dtype + + +def compute_module_sizes( + model: nn.Module, + dtype: Optional[Union[str, torch.device]] = None, + special_dtypes: Optional[dict[str, Union[str, torch.device]]] = None, + buffers_only: bool = False, +): + """ + Compute the size of each submodule of a given model. + """ + if dtype is not None: + dtype = _get_proper_dtype(dtype) + dtype_size = dtype_byte_size(dtype) + if special_dtypes is not None: + special_dtypes = {key: _get_proper_dtype(dtyp) for key, dtyp in special_dtypes.items()} + special_dtypes_size = {key: dtype_byte_size(dtyp) for key, dtyp in special_dtypes.items()} + module_sizes = defaultdict(int) + + module_list = [] + + if not buffers_only: + module_list = named_module_tensors(model, recurse=True) + else: + module_list = model.named_buffers(recurse=True) + + for name, tensor in module_list: + if special_dtypes is not None and name in special_dtypes: + size = tensor.numel() * special_dtypes_size[name] + elif dtype is None: + size = tensor.numel() * dtype_byte_size(tensor.dtype) + elif str(tensor.dtype).startswith(("torch.uint", "torch.int", "torch.bool")): + # According to the code in set_module_tensor_to_device, these types won't be converted + # so use their original size here + size = tensor.numel() * dtype_byte_size(tensor.dtype) + else: + size = tensor.numel() * min(dtype_size, dtype_byte_size(tensor.dtype)) + name_parts = name.split(".") + for idx in range(len(name_parts) + 1): + module_sizes[".".join(name_parts[:idx])] += size + + return module_sizes + + +def compute_module_total_buffer_size( + model: nn.Module, + dtype: Optional[Union[str, torch.device]] = None, + special_dtypes: Optional[dict[str, Union[str, torch.device]]] = None, +): + """ + Compute the total size of buffers in each submodule of a given model. + """ + module_sizes = compute_module_sizes(model, dtype=dtype, special_dtypes=special_dtypes, buffers_only=True) + return module_sizes.get("", 0) + + +def get_max_layer_size( + modules: list[tuple[str, torch.nn.Module]], module_sizes: dict[str, int], no_split_module_classes: list[str] +): + """ + Utility function that will scan a list of named modules and return the maximum size used by one full layer. The + definition of a layer being: + - a module with no direct children (just parameters and buffers) + - a module whose class name is in the list `no_split_module_classes` + + Args: + modules (`List[Tuple[str, torch.nn.Module]]`): + The list of named modules where we want to determine the maximum layer size. + module_sizes (`Dict[str, int]`): + A dictionary mapping each layer name to its size (as generated by `compute_module_sizes`). + no_split_module_classes (`List[str]`): + A list of class names for layers we don't want to be split. + + Returns: + `Tuple[int, List[str]]`: The maximum size of a layer with the list of layer names realizing that maximum size. + """ + max_size = 0 + layer_names = [] + modules_to_treat = modules.copy() + while len(modules_to_treat) > 0: + module_name, module = modules_to_treat.pop(0) + modules_children = list(module.named_children()) if isinstance(module, torch.nn.Module) else [] + if len(modules_children) == 0 or module.__class__.__name__ in no_split_module_classes: + # No splitting this one so we compare to the max_size + size = module_sizes[module_name] + if size > max_size: + max_size = size + layer_names = [module_name] + elif size == max_size: + layer_names.append(module_name) + else: + modules_to_treat = [(f"{module_name}.{n}", v) for n, v in modules_children] + modules_to_treat + return max_size, layer_names + + +def get_max_memory(max_memory: Optional[dict[Union[int, str], Union[int, str]]] = None): + """ + Get the maximum memory available if nothing is passed, converts string to int otherwise. + """ + import psutil + + if max_memory is None: + max_memory = {} + # Make sure CUDA is initialized on each GPU to have the right memory info. + if is_npu_available(): + for i in range(torch.npu.device_count()): + try: + _ = torch.tensor(0, device=torch.device("npu", i)) + max_memory[i] = torch.npu.mem_get_info(i)[0] + except Exception: + logger.info(f"Device {i} seems unavailable, Proceeding to check subsequent devices.") + continue + elif is_mlu_available(): + for i in range(torch.mlu.device_count()): + try: + _ = torch.tensor(0, device=torch.device("mlu", i)) + max_memory[i] = torch.mlu.mem_get_info(i)[0] + except Exception: + logger.info(f"Device {i} seems unavailable, Proceeding to check subsequent devices.") + continue + elif is_sdaa_available(): + for i in range(torch.sdaa.device_count()): + try: + _ = torch.tensor(0, device=torch.device("sdaa", i)) + max_memory[i] = torch.sdaa.mem_get_info(i)[0] + except Exception: + logger.info(f"Device {i} seems unavailable, Proceeding to check subsequent devices.") + continue + elif is_musa_available(): + for i in range(torch.musa.device_count()): + try: + _ = torch.tensor(0, device=torch.device("musa", i)) + max_memory[i] = torch.musa.mem_get_info(i)[0] + except Exception: + logger.info(f"Device {i} seems unavailable, Proceeding to check subsequent devices.") + continue + elif is_xpu_available(): + for i in range(torch.xpu.device_count()): + try: + _ = torch.tensor(0, device=torch.device("xpu", i)) + max_memory[i] = get_xpu_available_memory(i) + except Exception: + logger.info(f"Device {i} seems unavailable, Proceeding to check subsequent devices.") + continue + elif is_hpu_available(): + for i in range(torch.hpu.device_count()): + try: + _ = torch.tensor(0, device=torch.device("hpu", i)) + max_memory[i] = torch.hpu.mem_get_info(i)[0] + except Exception: + logger.info(f"Device {i} seems unavailable, Proceeding to check subsequent devices.") + continue + else: + for i in range(torch.cuda.device_count()): + try: + _ = torch.tensor([0], device=i) + max_memory[i] = torch.cuda.mem_get_info(i)[0] + except Exception: + logger.info(f"Device {i} seems unavailable, Proceeding to check subsequent devices.") + continue + # allocate everything in the mps device as the RAM is shared + if is_mps_available(): + max_memory["mps"] = psutil.virtual_memory().available + else: + max_memory["cpu"] = psutil.virtual_memory().available + return max_memory + + for key in max_memory: + if isinstance(max_memory[key], str): + max_memory[key] = convert_file_size_to_int(max_memory[key]) + + # Need to sort the device by type to make sure that we allocate the gpu first. + # As gpu/npu/xpu are represented by int, we need to sort them first. + gpu_devices = [k for k in max_memory.keys() if isinstance(k, int)] + gpu_devices.sort() + # check if gpu/npu/xpu devices are available and if not, throw a warning + if is_npu_available(): + num_devices = torch.npu.device_count() + elif is_mlu_available(): + num_devices = torch.mlu.device_count() + elif is_sdaa_available(): + num_devices = torch.sdaa.device_count() + elif is_musa_available(): + num_devices = torch.musa.device_count() + elif is_xpu_available(): + num_devices = torch.xpu.device_count() + elif is_hpu_available(): + num_devices = torch.hpu.device_count() + else: + num_devices = torch.cuda.device_count() + for device in gpu_devices: + if device >= num_devices or device < 0: + logger.warning(f"Device {device} is not available, available devices are {list(range(num_devices))}") + # Add the other devices in the preset order if they are available + all_devices = gpu_devices + [k for k in ["mps", "cpu", "disk"] if k in max_memory.keys()] + # Raise an error if a device is not recognized + for k in max_memory.keys(): + if k not in all_devices: + raise ValueError( + f"Device {k} is not recognized, available devices are integers(for GPU/XPU), 'mps', 'cpu' and 'disk'" + ) + max_memory = {k: max_memory[k] for k in all_devices} + + return max_memory + + +def clean_device_map(device_map: dict[str, Union[int, str, torch.device]], module_name: str = ""): + """ + Cleans a device_map by grouping all submodules that go on the same device together. + """ + # Get the value of the current module and if there is only one split across several keys, regroup it. + prefix = "" if module_name == "" else f"{module_name}." + values = [v for k, v in device_map.items() if k.startswith(prefix)] + if len(set(values)) == 1 and len(values) > 1: + for k in [k for k in device_map if k.startswith(prefix)]: + del device_map[k] + device_map[module_name] = values[0] + + # Recurse over the children + children_modules = [k for k in device_map.keys() if k.startswith(prefix) and len(k) > len(module_name)] + idx = len(module_name.split(".")) + 1 if len(module_name) > 0 else 1 + children_modules = set(".".join(k.split(".")[:idx]) for k in children_modules) + for child in children_modules: + clean_device_map(device_map, module_name=child) + + return device_map + + +def load_offloaded_weights(model, index, offload_folder): + """ + Loads the weights from the offload folder into the model. + + Args: + model (`torch.nn.Module`): + The model to load the weights into. + index (`dict`): + A dictionary containing the parameter name and its metadata for each parameter that was offloaded from the + model. + offload_folder (`str`): + The folder where the offloaded weights are stored. + """ + if index is None or len(index) == 0: + # Nothing to do + return + for param_name, metadata in index.items(): + if "SCB" in param_name: + continue + fp16_statistics = None + if "weight" in param_name and param_name.replace("weight", "SCB") in index.keys(): + weight_name = param_name.replace("weight", "SCB") + fp16_statistics = load_offloaded_weight( + os.path.join(offload_folder, f"{weight_name}.dat"), index[weight_name] + ) + tensor_file = os.path.join(offload_folder, f"{param_name}.dat") + weight = load_offloaded_weight(tensor_file, metadata) + set_module_tensor_to_device(model, param_name, "cpu", value=weight, fp16_statistics=fp16_statistics) + + +def get_module_leaves(module_sizes): + module_children = {} + for module in module_sizes: + if module == "" or "." not in module: + continue + parent = module.rsplit(".", 1)[0] + module_children[parent] = module_children.get(parent, 0) + 1 + leaves = [module for module in module_sizes if module_children.get(module, 0) == 0 and module != ""] + return leaves + + +def get_balanced_memory( + model: nn.Module, + max_memory: Optional[dict[Union[int, str], Union[int, str]]] = None, + no_split_module_classes: Optional[list[str]] = None, + dtype: Optional[Union[str, torch.dtype]] = None, + special_dtypes: Optional[dict[str, Union[str, torch.device]]] = None, + low_zero: bool = False, +): + """ + Compute a `max_memory` dictionary for [`infer_auto_device_map`] that will balance the use of each available GPU. + + + + All computation is done analyzing sizes and dtypes of the model parameters. As a result, the model can be on the + meta device (as it would if initialized within the `init_empty_weights` context manager). + + + + Args: + model (`torch.nn.Module`): + The model to analyze. + max_memory (`Dict`, *optional*): + A dictionary device identifier to maximum memory. Will default to the maximum memory available if unset. + Example: `max_memory={0: "1GB"}`. + no_split_module_classes (`List[str]`, *optional*): + A list of layer class names that should never be split across device (for instance any layer that has a + residual connection). + dtype (`str` or `torch.dtype`, *optional*): + If provided, the weights will be converted to that type when loaded. + special_dtypes (`Dict[str, Union[str, torch.device]]`, *optional*): + If provided, special dtypes to consider for some specific weights (will override dtype used as default for + all weights). + low_zero (`bool`, *optional*): + Minimizes the number of weights on GPU 0, which is convenient when it's used for other operations (like the + Transformers generate function). + """ + # Get default / clean up max_memory + user_not_set_max_memory = max_memory is None + max_memory = get_max_memory(max_memory) + + if is_npu_available(): + expected_device_type = "npu" + elif is_mlu_available(): + expected_device_type = "mlu" + elif is_sdaa_available(): + expected_device_type = "sdaa" + elif is_musa_available(): + expected_device_type = "musa" + elif is_xpu_available(): + expected_device_type = "xpu" + elif is_hpu_available(): + expected_device_type = "hpu" + elif is_mps_available(): + expected_device_type = "mps" + else: + expected_device_type = "cuda" + num_devices = len([d for d in max_memory if torch.device(d).type == expected_device_type and max_memory[d] > 0]) + + if num_devices == 0: + return max_memory + + if num_devices == 1: + # We cannot do low_zero on just one GPU, but we will still reserve some memory for the buffer + low_zero = False + # If user just asked us to handle memory usage, we should avoid OOM + if user_not_set_max_memory: + for key in max_memory.keys(): + if isinstance(key, int): + max_memory[key] *= 0.9 # 90% is a good compromise + logger.info( + f"We will use 90% of the memory on device {key} for storing the model, and 10% for the buffer to avoid OOM. " + "You can set `max_memory` in to a higher value to use more memory (at your own risk)." + ) + break # only one device + + module_sizes = compute_module_sizes(model, dtype=dtype, special_dtypes=special_dtypes) + per_gpu = module_sizes[""] // (num_devices - 1 if low_zero else num_devices) + + # We can't just set the memory to model_size // num_devices as it will end being too small: each GPU will get + # slightly less layers and some layers will end up offload at the end. So this function computes a buffer size to + # add which is the biggest of: + # - the size of no split block (if applicable) + # - the mean of the layer sizes + if no_split_module_classes is None: + no_split_module_classes = [] + elif not isinstance(no_split_module_classes, (list, tuple)): + no_split_module_classes = [no_split_module_classes] + + # Identify the size of the no_split_block modules + if len(no_split_module_classes) > 0: + no_split_children = {} + for name, size in module_sizes.items(): + if name == "": + continue + submodule = model + for submodule_name in name.split("."): + submodule = getattr(submodule, submodule_name) + class_name = submodule.__class__.__name__ + if class_name in no_split_module_classes and class_name not in no_split_children: + no_split_children[class_name] = size + + if set(no_split_children.keys()) == set(no_split_module_classes): + break + buffer = max(no_split_children.values()) if len(no_split_children) > 0 else 0 + else: + buffer = 0 + + # Compute mean of final modules. In the first dict of module sizes, leaves are the parameters + leaves = get_module_leaves(module_sizes) + module_sizes = {n: v for n, v in module_sizes.items() if n not in leaves} + # Once removed, leaves are the final modules. + leaves = get_module_leaves(module_sizes) + mean_leaves = int(sum([module_sizes[n] for n in leaves]) / max(len(leaves), 1)) + buffer = int(1.25 * max(buffer, mean_leaves)) + per_gpu += buffer + + # Sorted list of GPUs id (we may have some gpu ids not included in the our max_memory list - let's ignore them) + gpus_idx_list = list( + sorted( + device_id for device_id, device_mem in max_memory.items() if isinstance(device_id, int) and device_mem > 0 + ) + ) + # The last device is left with max_memory just in case the buffer is not enough. + for idx in gpus_idx_list[:-1]: + max_memory[idx] = min(max_memory[0] if low_zero and idx == 0 else per_gpu, max_memory[idx]) + + if low_zero: + min_zero = max(0, module_sizes[""] - sum([max_memory[i] for i in range(1, num_devices)])) + max_memory[0] = min(min_zero, max_memory[0]) + + return max_memory + + +def calculate_maximum_sizes(model: torch.nn.Module): + "Computes the total size of the model and its largest layer" + sizes = compute_module_sizes(model) + # `transformers` models store this information for us + no_split_modules = getattr(model, "_no_split_modules", None) + if no_split_modules is None: + no_split_modules = [] + + modules_to_treat = ( + list(model.named_parameters(recurse=False)) + + list(model.named_children()) + + list(model.named_buffers(recurse=False)) + ) + largest_layer = get_max_layer_size(modules_to_treat, sizes, no_split_modules) + total_size = sizes[""] + return total_size, largest_layer + + +def _init_infer_auto_device_map( + model: nn.Module, + max_memory: Optional[dict[Union[int, str], Union[int, str]]] = None, + no_split_module_classes: Optional[list[str]] = None, + dtype: Optional[Union[str, torch.dtype]] = None, + special_dtypes: Optional[dict[str, Union[str, torch.device]]] = None, +) -> tuple[ + list[Union[int, str]], + dict[Union[int, str], Union[int, str]], + list[Union[int, str]], + list[int], + dict[str, int], + list[list[str]], + list[str], + list[tuple[str, nn.Module]], +]: + """ + Initialize variables required for computing the device map for model allocation. + """ + max_memory = get_max_memory(max_memory) + if no_split_module_classes is None: + no_split_module_classes = [] + elif not isinstance(no_split_module_classes, (list, tuple)): + no_split_module_classes = [no_split_module_classes] + + devices = list(max_memory.keys()) + if "disk" not in devices: + devices.append("disk") + gpus = [device for device in devices if device not in ["cpu", "disk"]] + + # Devices that need to keep space for a potential offloaded layer. + if "mps" in gpus: + main_devices = ["mps"] + elif len(gpus) > 0: + main_devices = [gpus[0], "cpu"] + else: + main_devices = ["cpu"] + + module_sizes = compute_module_sizes(model, dtype=dtype, special_dtypes=special_dtypes) + tied_parameters = find_tied_parameters(model) + if check_tied_parameters_in_config(model) and len(tied_parameters) == 0: + logger.warning( + "The model weights are not tied. Please use the `tie_weights` method before using the `infer_auto_device` function." + ) + + # Direct submodules and parameters + modules_to_treat = ( + list(model.named_parameters(recurse=False)) + + list(model.named_children()) + + list(model.named_buffers(recurse=False)) + ) + + return ( + devices, + max_memory, + main_devices, + gpus, + module_sizes, + tied_parameters, + no_split_module_classes, + modules_to_treat, + ) + + +def get_module_size_with_ties( + tied_params, + module_size, + module_sizes, + modules_to_treat, +) -> tuple[int, list[str], list[nn.Module]]: + """ + Calculate the total size of a module, including its tied parameters. + + Args: + tied_params (`List[str]`): The list of tied parameters. + module_size (`int`): The size of the module without tied parameters. + module_sizes (`Dict[str, int]`): A dictionary mapping each layer name to its size. + modules_to_treat (`List[Tuple[str, nn.Module]]`): The list of named modules to treat. + + Returns: + `Tuple[int, List[str], List[nn.Module]]`: The total size of the module, the names of the tied modules, and the + tied modules. + """ + if len(tied_params) < 1: + return module_size, [], [] + tied_module_names = [] + tied_modules = [] + + for tied_param in tied_params: + tied_module_index = [i for i, (n, _) in enumerate(modules_to_treat) if tied_param.startswith(n + ".")][0] + tied_module_names.append(modules_to_treat[tied_module_index][0]) + tied_modules.append(modules_to_treat[tied_module_index][1]) + + module_size_with_ties = module_size + for tied_param, tied_module_name in zip(tied_params, tied_module_names): + module_size_with_ties += module_sizes[tied_module_name] - module_sizes[tied_param] + + return module_size_with_ties, tied_module_names, tied_modules + + +def fallback_allocate( + modules: list[tuple[str, nn.Module]], + module_sizes: dict[str, int], + size_limit: Union[int, str], + no_split_module_classes: Optional[list[str]] = None, + tied_parameters: Optional[list[list[str]]] = None, +) -> tuple[Optional[str], Optional[nn.Module], list[tuple[str, nn.Module]]]: + """ + Find a module that fits in the size limit using BFS and return it with its name and the remaining modules. + + Args: + modules (`List[Tuple[str, nn.Module]]`): + The list of named modules to search in. + module_sizes (`Dict[str, int]`): + A dictionary mapping each layer name to its size (as generated by `compute_module_sizes`). + size_limit (`Union[int, str]`): + The maximum size a module can have. + no_split_module_classes (`Optional[List[str]]`, *optional*): + A list of class names for layers we don't want to be split. + tied_parameters (`Optional[List[List[str]]`, *optional*): + A list of lists of parameter names being all tied together. + + Returns: + `Tuple[Optional[str], Optional[nn.Module], List[Tuple[str, nn.Module]]]`: A tuple containing: + - The name of the module that fits within the size limit. + - The module itself. + - The list of remaining modules after the found module is removed. + """ + try: + size_limit = convert_file_size_to_int(size_limit) + except ValueError: + return None, None, modules + + if no_split_module_classes is None: + no_split_module_classes = [] + + if tied_parameters is None: + tied_parameters = [] + + modules_to_search = modules.copy() + module_found = False + + while modules_to_search: + name, module = modules_to_search.pop(0) + + tied_param_groups = [ + tied_group + for tied_group in tied_parameters + if any(name + "." in k + "." for k in tied_group) and not all(name + "." in k + "." for k in tied_group) + ] + + tied_params = sum( + [[p for p in tied_group if name + "." not in p + "."] for tied_group in tied_param_groups], [] + ) + + module_size_with_ties, _, _ = get_module_size_with_ties( + tied_params, module_sizes[name], module_sizes, modules_to_search + ) + + # If the module fits in the size limit, we found it. + if module_size_with_ties <= size_limit: + module_found = True + break + + # The module is too big, we need to split it if possible. + modules_children = ( + [] + if isinstance(module, nn.Parameter) or isinstance(module, torch.Tensor) + else list(module.named_children()) + ) + + # Split fails, move to the next module + if len(modules_children) == 0 or module.__class__.__name__ in no_split_module_classes: + continue + + # split is possible, add the children to the list of modules to search + modules_children = list(module.named_parameters(recurse=False)) + modules_children + modules_to_search = [(f"{name}.{n}", v) for n, v in modules_children] + modules_to_search + + if not module_found: + return None, None, modules + + # Prepare the module list for removal of the found module + current_names = [n for n, _ in modules] + dot_idx = [i for i, c in enumerate(name) if c == "."] + + for dot_index in dot_idx: + parent_name = name[:dot_index] + if parent_name in current_names: + parent_module_idx = current_names.index(parent_name) + _, parent_module = modules[parent_module_idx] + module_children = list(parent_module.named_parameters(recurse=False)) + list( + parent_module.named_children() + ) + modules = ( + modules[:parent_module_idx] + + [(f"{parent_name}.{n}", v) for n, v in module_children] + + modules[parent_module_idx + 1 :] + ) + current_names = [n for n, _ in modules] + + # Now the target module should be directly in the list + target_idx = current_names.index(name) + name, module = modules.pop(target_idx) + + return name, module, modules + + +def infer_auto_device_map( + model: nn.Module, + max_memory: Optional[dict[Union[int, str], Union[int, str]]] = None, + no_split_module_classes: Optional[list[str]] = None, + dtype: Optional[Union[str, torch.dtype]] = None, + special_dtypes: Optional[dict[str, Union[str, torch.dtype]]] = None, + verbose: bool = False, + clean_result: bool = True, + offload_buffers: bool = False, + fallback_allocation: bool = False, +): + """ + Compute a device map for a given model giving priority to GPUs, then offload on CPU and finally offload to disk, + such that: + - we don't exceed the memory available of any of the GPU. + - if offload to the CPU is needed, there is always room left on GPU 0 to put back the layer offloaded on CPU that + has the largest size. + - if offload to the CPU is needed,we don't exceed the RAM available on the CPU. + - if offload to the disk is needed, there is always room left on the CPU to put back the layer offloaded on disk + that has the largest size. + + + + All computation is done analyzing sizes and dtypes of the model parameters. As a result, the model can be on the + meta device (as it would if initialized within the `init_empty_weights` context manager). + + + + Args: + model (`torch.nn.Module`): + The model to analyze. + max_memory (`Dict`, *optional*): + A dictionary device identifier to maximum memory. Will default to the maximum memory available if unset. + Example: `max_memory={0: "1GB"}`. + no_split_module_classes (`List[str]`, *optional*): + A list of layer class names that should never be split across device (for instance any layer that has a + residual connection). + dtype (`str` or `torch.dtype`, *optional*): + If provided, the weights will be converted to that type when loaded. + special_dtypes (`Dict[str, Union[str, torch.device]]`, *optional*): + If provided, special dtypes to consider for some specific weights (will override dtype used as default for + all weights). + verbose (`bool`, *optional*, defaults to `False`): + Whether or not to provide debugging statements as the function builds the device_map. + clean_result (`bool`, *optional*, defaults to `True`): + Clean the resulting device_map by grouping all submodules that go on the same device together. + offload_buffers (`bool`, *optional*, defaults to `False`): + In the layers that are offloaded on the CPU or the hard drive, whether or not to offload the buffers as + well as the parameters. + fallback_allocation (`bool`, *optional*, defaults to `False`): + When regular allocation fails, try to allocate a module that fits in the size limit using BFS. + """ + + # Initialize the variables + ( + devices, + max_memory, + main_devices, + gpus, + module_sizes, + tied_parameters, + no_split_module_classes, + modules_to_treat, + ) = _init_infer_auto_device_map(model, max_memory, no_split_module_classes, dtype, special_dtypes) + + device_map = OrderedDict() + current_device = 0 + device_memory_used = {device: 0 for device in devices} + device_buffer_sizes = {} + device_minimum_assignment_memory = {} + + # Initialize maximum largest layer, to know which space to keep in memory + max_layer_size, max_layer_names = get_max_layer_size(modules_to_treat, module_sizes, no_split_module_classes) + + # Ready ? This is going to be a bit messy. + while len(modules_to_treat) > 0: + name, module = modules_to_treat.pop(0) + if verbose: + print(f"\nTreating module {name}.") + # Max size in the remaining layers may have changed since we took one, so we maybe update it. + max_layer_names = [n for n in max_layer_names if n != name and not n.startswith(name + ".")] + if len(max_layer_names) == 0: + max_layer_size, max_layer_names = get_max_layer_size( + [(n, m) for n, m in modules_to_treat if isinstance(m, torch.nn.Module)], + module_sizes, + no_split_module_classes, + ) + # Assess size needed + module_size = module_sizes[name] + + # We keep relevant tied parameters only: one of the tied parameters in the group is inside the current module + # and the other is not. + # Note: If we are currently processing the name `compute.weight`, an other parameter named + # e.g. `compute.weight_submodule.parameter` + # needs to be considered outside the current module, hence the check with additional dots. + tied_param_groups = [ + tied_group + for tied_group in tied_parameters + if any(name + "." in k + "." for k in tied_group) and not all(name + "." in k + "." for k in tied_group) + ] + + if verbose and len(tied_param_groups) > 0: + print(f" Found the relevant tied param groups {tied_param_groups}") + + # Then we keep track of all the parameters that are tied to the current module, but not in the current module + tied_params = sum( + [[p for p in tied_group if name + "." not in p + "."] for tied_group in tied_param_groups], [] + ) + + if verbose and len(tied_params) > 0: + print(f" So those parameters need to be taken into account {tied_params}") + + device = devices[current_device] + current_max_size = max_memory[device] if device != "disk" else None + current_memory_reserved = 0 + # Reduce max size available by the largest layer. + if devices[current_device] in main_devices: + current_max_size = current_max_size - max_layer_size + current_memory_reserved = max_layer_size + + module_size_with_ties, tied_module_names, tied_modules = get_module_size_with_ties( + tied_params, module_size, module_sizes, modules_to_treat + ) + + # The module and its tied modules fit on the current device. + if current_max_size is None or device_memory_used[device] + module_size_with_ties <= current_max_size: + if verbose: + output = f"Putting {name}" + + if tied_module_names: + output += f" and {tied_module_names}" + else: + output += f" (size={module_size})" + + if current_max_size is not None: + output += f" (available={current_max_size - device_memory_used[device]})" + + output += f" on {device}." + print(output) + + device_memory_used[device] += module_size_with_ties + + # Assign the primary module to the device. + device_map[name] = device + + # Assign tied modules if any. + for tied_module_name in tied_module_names: + if tied_module_name in [m[0] for m in modules_to_treat]: + # Find the index of the tied module in the list + tied_module_index = next(i for i, (n, _) in enumerate(modules_to_treat) if n == tied_module_name) + # Remove the tied module from the list to prevent reprocessing + modules_to_treat.pop(tied_module_index) + + # Assign the tied module to the device + device_map[tied_module_name] = device + + # Buffer Handling + if not offload_buffers and isinstance(module, nn.Module): + # Compute the total buffer size for the module + current_buffer_size = compute_module_total_buffer_size( + module, dtype=dtype, special_dtypes=special_dtypes + ) + # Update the buffer size on the device + device_buffer_sizes[device] = device_buffer_sizes.get(device, 0) + current_buffer_size + + continue + + # The current module itself fits, so we try to split the tied modules. + if len(tied_params) > 0 and device_memory_used[device] + module_size <= current_max_size: + # can we split one of the tied modules to make it smaller or do we need to go on the next device? + if verbose: + print( + f"Not enough space on {devices[current_device]} to put {name} and {tied_module_names} (space " + f"available {current_max_size - device_memory_used[device]}, needed size {module_size_with_ties})." + ) + split_happened = False + for tied_module_name, tied_module in zip(tied_module_names, tied_modules): + tied_module_children = list(tied_module.named_children()) + if len(tied_module_children) == 0 or tied_module.__class__.__name__ in no_split_module_classes: + # can't break this one. + continue + + if verbose: + print(f"Splitting {tied_module_name}.") + tied_module_children = list(tied_module.named_parameters(recurse=False)) + tied_module_children + tied_module_children = [(f"{tied_module_name}.{n}", v) for n, v in tied_module_children] + tied_module_index = [i for i, (n, _) in enumerate(modules_to_treat) if n == tied_module_name][0] + + modules_to_treat = ( + [(name, module)] + + modules_to_treat[:tied_module_index] + + tied_module_children + + modules_to_treat[tied_module_index + 1 :] + ) + # Update the max layer size. + max_layer_size, max_layer_names = get_max_layer_size( + [(n, m) for n, m in modules_to_treat if isinstance(m, torch.nn.Module)], + module_sizes, + no_split_module_classes, + ) + split_happened = True + break + + if split_happened: + continue + + # If the tied module is not split, we go to the next device + if verbose: + print("None of the tied module can be split, going to the next device.") + + # The current module itself doesn't fit, so we have to split it or go to the next device. + if device_memory_used[device] + module_size >= current_max_size: + # Split or not split? + modules_children = ( + [] + if isinstance(module, nn.Parameter) or isinstance(module, torch.Tensor) + else list(module.named_children()) + ) + if verbose: + print( + f"Not enough space on {devices[current_device]} to put {name} (space available " + f"{current_max_size - device_memory_used[device]}, module size {module_size})." + ) + if len(modules_children) == 0 or module.__class__.__name__ in no_split_module_classes: + # -> no split, we go to the next device + if verbose: + print("This module cannot be split, going to the next device.") + + else: + # -> split, we replace the module studied by its children + parameters + if verbose: + print(f"Splitting {name}.") + modules_children = list(module.named_parameters(recurse=False)) + modules_children + modules_to_treat = [(f"{name}.{n}", v) for n, v in modules_children] + modules_to_treat + # Update the max layer size. + max_layer_size, max_layer_names = get_max_layer_size( + [(n, m) for n, m in modules_to_treat if isinstance(m, torch.nn.Module)], + module_sizes, + no_split_module_classes, + ) + continue + + # If no module is assigned to the current device, we attempt to allocate a fallback module + # if fallback_allocation is enabled. + if device_memory_used[device] == 0 and fallback_allocation and device != "disk": + # We try to allocate a module that fits in the size limit using BFS. + # Recompute the current max size as we need to consider the current module as well. + current_max_size = max_memory[device] - max(max_layer_size, module_size_with_ties) + + fallback_module_name, fallback_module, remaining_modules = fallback_allocate( + modules_to_treat, + module_sizes, + current_max_size - device_memory_used[device], + no_split_module_classes, + tied_parameters, + ) + # use the next iteration to put the fallback module on the next device to avoid code duplication + if fallback_module is not None: + modules_to_treat = [(fallback_module_name, fallback_module)] + [(name, module)] + remaining_modules + continue + + if device_memory_used[device] == 0: + device_minimum_assignment_memory[device] = module_size_with_ties + current_memory_reserved + + # Neither the current module nor any tied modules can be split, so we move to the next device. + device_memory_used[device] = device_memory_used[device] + current_memory_reserved + current_device += 1 + modules_to_treat = [(name, module)] + modules_to_treat + + device_memory_used = {device: mem for device, mem in device_memory_used.items() if mem > 0} + + if clean_result: + device_map = clean_device_map(device_map) + + non_gpu_buffer_size = device_buffer_sizes.get("cpu", 0) + device_buffer_sizes.get("disk", 0) + if non_gpu_buffer_size > 0 and not offload_buffers: + is_buffer_fit_any_gpu = False + for gpu_device, gpu_max_memory in max_memory.items(): + if gpu_device == "cpu" or gpu_device == "disk": + continue + + if not is_buffer_fit_any_gpu: + gpu_memory_used = device_memory_used.get(gpu_device, 0) + + if gpu_max_memory >= non_gpu_buffer_size + gpu_memory_used: + is_buffer_fit_any_gpu = True + + if len(gpus) > 0 and not is_buffer_fit_any_gpu: + warnings.warn( + f"Current model requires {non_gpu_buffer_size} bytes of buffer for offloaded layers, which seems does " + f"not fit any GPU's remaining memory. If you are experiencing a OOM later, please consider using " + f"offload_buffers=True." + ) + + if device_minimum_assignment_memory: + devices_info = "\n".join( + f" - {device}: {mem} bytes required" for device, mem in device_minimum_assignment_memory.items() + ) + logger.info( + f"Based on the current allocation process, no modules could be assigned to the following devices due to " + f"insufficient memory:\n" + f"{devices_info}\n" + f"These minimum requirements are specific to this allocation attempt and may vary. Consider increasing " + f"the available memory for these devices to at least the specified minimum, or adjusting the model config." + ) + return device_map + + +def check_device_map(model: nn.Module, device_map: dict[str, Union[int, str, torch.device]]): + """ + Checks a device map covers everything in a given model. + + Args: + model (`torch.nn.Module`): The model to check the device map against. + device_map (`Dict[str, Union[int, str, torch.device]]`): The device map to check. + """ + all_module_names = dict(model.named_modules()) + invalid_keys = [k for k in device_map if k != "" and k not in all_module_names] + + if invalid_keys: + warnings.warn( + f"The following device_map keys do not match any submodules in the model: {invalid_keys}", UserWarning + ) + + all_model_tensors = [name for name, _ in model.state_dict().items()] + for module_name in device_map.keys(): + if module_name == "": + all_model_tensors.clear() + break + else: + all_model_tensors = [ + name + for name in all_model_tensors + if not name == module_name and not name.startswith(module_name + ".") + ] + if len(all_model_tensors) > 0: + non_covered_params = ", ".join(all_model_tensors) + raise ValueError( + f"The device_map provided does not give any device for the following parameters: {non_covered_params}" + ) + + +def load_state_dict(checkpoint_file, device_map=None): + """ + Load a checkpoint from a given file. If the checkpoint is in the safetensors format and a device map is passed, the + weights can be fast-loaded directly on the GPU. + + Args: + checkpoint_file (`str`): The path to the checkpoint to load. + device_map (`Dict[str, Union[int, str, torch.device]]`, *optional*): + A map that specifies where each submodule should go. It doesn't need to be refined to each parameter/buffer + name, once a given module name is inside, every submodule of it will be sent to the same device. + """ + if checkpoint_file.endswith(".safetensors"): + with safe_open(checkpoint_file, framework="pt") as f: + metadata = f.metadata() + weight_names = f.keys() + + if metadata is None: + logger.warning( + f"The safetensors archive passed at {checkpoint_file} does not contain metadata. " + "Make sure to save your model with the `save_pretrained` method. Defaulting to 'pt' metadata." + ) + metadata = {"format": "pt"} + + if metadata.get("format") not in ["pt", "tf", "flax"]: + raise OSError( + f"The safetensors archive passed at {checkpoint_file} does not contain the valid metadata. Make sure " + "you save your model with the `save_pretrained` method." + ) + elif metadata["format"] != "pt": + raise ValueError(f"The checkpoint passed was saved with {metadata['format']}, we need a the pt format.") + if device_map is None: + return safe_load_file(checkpoint_file) + else: + # if we only have one device we can load everything directly + if len(set(device_map.values())) == 1: + device = list(device_map.values())[0] + target_device = device + if isinstance(device, int): + if is_npu_available(): + target_device = f"npu:{device}" + elif is_hpu_available(): + target_device = "hpu" + + return safe_load_file(checkpoint_file, device=target_device) + + devices = list(set(device_map.values()) - {"disk"}) + # cpu device should always exist as fallback option + if "cpu" not in devices: + devices.append("cpu") + + # For each device, get the weights that go there + device_weights = {device: [] for device in devices} + for module_name, device in device_map.items(): + if device in devices: + device_weights[device].extend( + [k for k in weight_names if k == module_name or k.startswith(module_name + ".")] + ) + + # all weights that haven't defined a device should be loaded on CPU + device_weights["cpu"].extend([k for k in weight_names if k not in sum(device_weights.values(), [])]) + tensors = {} + if is_tqdm_available(): + progress_bar = tqdm( + main_process_only=False, + total=sum([len(device_weights[device]) for device in devices]), + unit="w", + smoothing=0, + leave=False, + ) + else: + progress_bar = None + for device in devices: + target_device = device + if isinstance(device, int): + if is_npu_available(): + target_device = f"npu:{device}" + elif is_hpu_available(): + target_device = "hpu" + + with safe_open(checkpoint_file, framework="pt", device=target_device) as f: + for key in device_weights[device]: + if progress_bar is not None: + progress_bar.set_postfix(dev=device, refresh=False) + progress_bar.set_description(key) + tensors[key] = f.get_tensor(key) + if progress_bar is not None: + progress_bar.update() + if progress_bar is not None: + progress_bar.close() + + return tensors + else: + return torch.load(checkpoint_file, map_location=torch.device("cpu"), weights_only=True) + + +def get_state_dict_offloaded_model(model: nn.Module): + """ + Returns the state dictionary for an offloaded model via iterative onloading + + Args: + model (`torch.nn.Module`): + The offloaded model we want to save + """ + + state_dict = {} + placeholders = set() + for name, module in model.named_modules(): + if name == "": + continue + + try: + with align_module_device(module, "cpu"): + module_state_dict = module.state_dict() + except MemoryError: + raise MemoryError("Offloaded module must fit in CPU memory to call save_model!") from None + + for key in module_state_dict: + # ignore placeholder parameters that are still on the meta device + if module_state_dict[key].device == torch.device("meta"): + placeholders.add(name + f".{key}") + continue + params = module_state_dict[key] + state_dict[name + f".{key}"] = params.to("cpu") # move buffers to cpu + for key in placeholders.copy(): + if key in state_dict: + placeholders.remove(key) + if placeholders: + logger.warning(f"The following tensors were not saved because they were still on meta device: {placeholders}") + + return state_dict + + +def get_state_dict_from_offload( + module: nn.Module, + module_name: str, + state_dict: dict[str, Union[str, torch.tensor]], + device_to_put_offload: Union[int, str, torch.device] = "cpu", +): + """ + Retrieve the state dictionary (with parameters) from an offloaded module and load into a specified device (defaults + to cpu). + + Args: + module: (`torch.nn.Module`): + The module we want to retrieve a state dictionary from + module_name: (`str`): + The name of the module of interest + state_dict (`Dict[str, Union[int, str, torch.device]]`): + Dictionary of {module names: parameters} + device_to_put_offload (`Union[int, str, torch.device]`): + Device to load offloaded parameters into, defaults to the cpu. + """ + + root = module_name[: module_name.rfind(".")] # module name without .weight or .bias + + # do not move parameters if the module is not offloaded + if not has_offloaded_params(module): + device_to_put_offload = None + + # assign the device to which the offloaded parameters will be sent + with align_module_device(module, device_to_put_offload): + for m_key, params in module.state_dict().items(): + if (root + f".{m_key}") in state_dict: + state_dict[root + f".{m_key}"] = params + + return state_dict + + +def load_checkpoint_in_model( + model: nn.Module, + checkpoint: Union[str, os.PathLike], + device_map: Optional[dict[str, Union[int, str, torch.device]]] = None, + offload_folder: Optional[Union[str, os.PathLike]] = None, + dtype: Optional[Union[str, torch.dtype]] = None, + offload_state_dict: bool = False, + offload_buffers: bool = False, + keep_in_fp32_modules: list[str] = None, + offload_8bit_bnb: bool = False, + strict: bool = False, + full_state_dict: bool = True, + broadcast_from_rank0: bool = False, +): + """ + Loads a (potentially sharded) checkpoint inside a model, potentially sending weights to a given device as they are + loaded. + + + + Once loaded across devices, you still need to call [`dispatch_model`] on your model to make it able to run. To + group the checkpoint loading and dispatch in one single call, use [`load_checkpoint_and_dispatch`]. + + + + Args: + model (`torch.nn.Module`): + The model in which we want to load a checkpoint. + checkpoint (`str` or `os.PathLike`): + The folder checkpoint to load. It can be: + - a path to a file containing a whole model state dict + - a path to a `.json` file containing the index to a sharded checkpoint + - a path to a folder containing a unique `.index.json` file and the shards of a checkpoint. + - a path to a folder containing a unique pytorch_model.bin or a model.safetensors file. + device_map (`Dict[str, Union[int, str, torch.device]]`, *optional*): + A map that specifies where each submodule should go. It doesn't need to be refined to each parameter/buffer + name, once a given module name is inside, every submodule of it will be sent to the same device. + offload_folder (`str` or `os.PathLike`, *optional*): + If the `device_map` contains any value `"disk"`, the folder where we will offload weights. + dtype (`str` or `torch.dtype`, *optional*): + If provided, the weights will be converted to that type when loaded. + offload_state_dict (`bool`, *optional*, defaults to `False`): + If `True`, will temporarily offload the CPU state dict on the hard drive to avoid getting out of CPU RAM if + the weight of the CPU state dict + the biggest shard does not fit. + offload_buffers (`bool`, *optional*, defaults to `False`): + Whether or not to include the buffers in the weights offloaded to disk. + keep_in_fp32_modules(`List[str]`, *optional*): + A list of the modules that we keep in `torch.float32` dtype. + offload_8bit_bnb (`bool`, *optional*): + Whether or not to enable offload of 8-bit modules on cpu/disk. + strict (`bool`, *optional*, defaults to `False`): + Whether to strictly enforce that the keys in the checkpoint state_dict match the keys of the model's + state_dict. + full_state_dict (`bool`, *optional*, defaults to `True`): if this is set to `True`, all the tensors in the + loaded state_dict will be gathered. No ShardedTensor and DTensor will be in the loaded state_dict. + broadcast_from_rank0 (`False`, *optional*, defaults to `False`): when the option is `True`, a distributed + `ProcessGroup` must be initialized. rank0 should receive a full state_dict and will broadcast the tensors + in the state_dict one by one to other ranks. Other ranks will receive the tensors and shard (if applicable) + according to the local shards in the model. + + """ + if offload_8bit_bnb: + from .bnb import quantize_and_offload_8bit + + tied_params = find_tied_parameters(model) + + if check_tied_parameters_in_config(model) and len(tied_params) == 0: + logger.warning( + "The model weights are not tied. Please use the `tie_weights` method before using the `infer_auto_device` function." + ) + if device_map is not None: + check_tied_parameters_on_same_device(tied_params, device_map) + + if offload_folder is None and device_map is not None and "disk" in device_map.values(): + raise ValueError( + "At least one of the model submodule will be offloaded to disk, please pass along an `offload_folder`." + ) + elif offload_folder is not None and device_map is not None and "disk" in device_map.values(): + os.makedirs(offload_folder, exist_ok=True) + + if isinstance(dtype, str): + # We accept "torch.float16" or just "float16" + dtype = dtype.replace("torch.", "") + dtype = getattr(torch, dtype) + + checkpoint_files = None + index_filename = None + if os.path.isfile(checkpoint): + if str(checkpoint).endswith(".json"): + index_filename = checkpoint + else: + checkpoint_files = [checkpoint] + elif os.path.isdir(checkpoint): + # check if the whole state dict is present + potential_state_bin = [f for f in os.listdir(checkpoint) if f == WEIGHTS_NAME] + potential_state_safetensor = [f for f in os.listdir(checkpoint) if f == SAFE_WEIGHTS_NAME] + if len(potential_state_bin) == 1: + checkpoint_files = [os.path.join(checkpoint, potential_state_bin[0])] + elif len(potential_state_safetensor) == 1: + checkpoint_files = [os.path.join(checkpoint, potential_state_safetensor[0])] + else: + # otherwise check for sharded checkpoints + potential_index = [f for f in os.listdir(checkpoint) if f.endswith(".index.json")] + if len(potential_index) == 0: + raise ValueError( + f"{checkpoint} is not a folder containing a `.index.json` file or a {WEIGHTS_NAME} or a {SAFE_WEIGHTS_NAME} file" + ) + elif len(potential_index) == 1: + index_filename = os.path.join(checkpoint, potential_index[0]) + else: + raise ValueError( + f"{checkpoint} containing more than one `.index.json` file, delete the irrelevant ones." + ) + else: + raise ValueError( + "`checkpoint` should be the path to a file containing a whole state dict, or the index of a sharded " + f"checkpoint, or a folder containing a sharded checkpoint or the whole state dict, but got {checkpoint}." + ) + + if index_filename is not None: + checkpoint_folder = os.path.split(index_filename)[0] + with open(index_filename) as f: + index = json.loads(f.read()) + + if "weight_map" in index: + index = index["weight_map"] + checkpoint_files = sorted(list(set(index.values()))) + checkpoint_files = [os.path.join(checkpoint_folder, f) for f in checkpoint_files] + + # Logic for missing/unexepected keys goes here. + + offload_index = {} + if offload_state_dict: + state_dict_folder = tempfile.mkdtemp() + state_dict_index = {} + + unexpected_keys = set() + model_keys = set(model.state_dict().keys()) + buffer_names = [name for name, _ in model.named_buffers()] + model_devices = {t.device for t in model.state_dict().values() if isinstance(t, torch.Tensor)} + model_physical_devices = model_devices - {torch.device("meta")} + for checkpoint_file in checkpoint_files: + if device_map is None: + # exception for multi-device loading was made for the meta device in torch v2.7.0 + # https://github.com/pytorch/pytorch/blob/v2.6.0/torch/distributed/checkpoint/state_dict.py#L557-L563 + # https://github.com/pytorch/pytorch/blob/v2.7.0-rc2/torch/distributed/checkpoint/state_dict.py#L575-L587 + if is_torch_version(">=", "2.2.0") and ( + (is_torch_version(">=", "2.7.0") and len(model_physical_devices) <= 1) or len(model_devices) <= 1 + ): + from torch.distributed.checkpoint.state_dict import StateDictOptions, set_model_state_dict + + broadcast_from_rank0 &= is_torch_version(">=", "2.4.0") + loaded_checkpoint = ( + load_state_dict(checkpoint_file, device_map=device_map) + if not broadcast_from_rank0 or dist.get_rank() == 0 + else {} + ) + set_model_state_dict( + model, + loaded_checkpoint, + options=StateDictOptions( + full_state_dict=full_state_dict, + strict=strict, + **({"broadcast_from_rank0": broadcast_from_rank0} if is_torch_version(">=", "2.4.0") else {}), + ), + ) + else: + loaded_checkpoint = load_state_dict(checkpoint_file, device_map=device_map) + model.load_state_dict(loaded_checkpoint, strict=strict) + + unexpected_keys.update(set(loaded_checkpoint.keys()) - model_keys) + else: + loaded_checkpoint = load_state_dict(checkpoint_file, device_map=device_map) + + for param_name, param in loaded_checkpoint.items(): + # skip SCB parameter (for 8-bit serialization) + if "SCB" in param_name: + continue + + if param_name not in model_keys: + unexpected_keys.add(param_name) + if not strict: + continue # Skip loading this parameter. + + module_name = param_name + + while len(module_name) > 0 and module_name not in device_map: + module_name = ".".join(module_name.split(".")[:-1]) + if module_name == "" and "" not in device_map: + # TODO: group all errors and raise at the end. + raise ValueError(f"{param_name} doesn't have any device set.") + param_device = device_map[module_name] + new_dtype = dtype + if dtype is not None and torch.is_floating_point(param): + if keep_in_fp32_modules is not None and dtype == torch.float16: + proceed = False + for key in keep_in_fp32_modules: + if ((key in param_name) and (key + "." in param_name)) or key == param_name: + proceed = True + break + if proceed: + new_dtype = torch.float32 + + if "weight" in param_name and param_name.replace("weight", "SCB") in loaded_checkpoint.keys(): + if param.dtype == torch.int8: + fp16_statistics = loaded_checkpoint[param_name.replace("weight", "SCB")] + else: + fp16_statistics = None + + if param_device == "disk": + if offload_buffers or param_name not in buffer_names: + if new_dtype is None: + new_dtype = param.dtype + if offload_8bit_bnb: + quantize_and_offload_8bit( + model, param, param_name, new_dtype, offload_folder, offload_index, fp16_statistics + ) + continue + else: + set_module_tensor_to_device(model, param_name, "meta", dtype=new_dtype) + offload_weight(param, param_name, offload_folder, index=offload_index) + elif param_device == "cpu" and offload_state_dict: + if new_dtype is None: + new_dtype = param.dtype + if offload_8bit_bnb: + quantize_and_offload_8bit( + model, param, param_name, new_dtype, state_dict_folder, state_dict_index, fp16_statistics + ) + else: + set_module_tensor_to_device(model, param_name, "meta", dtype=new_dtype) + offload_weight(param, param_name, state_dict_folder, index=state_dict_index) + else: + set_module_tensor_to_device( + model, + param_name, + param_device, + value=param, + dtype=new_dtype, + fp16_statistics=fp16_statistics, + ) + + # Force Python to clean up. + del loaded_checkpoint + gc.collect() + + if not strict and len(unexpected_keys) > 0: + logger.warning( + f"Some weights of the model checkpoint at {checkpoint} were not used when" + f" initializing {model.__class__.__name__}: {unexpected_keys}. This may or may not be an issue - make sure that the checkpoint does not have unnecessary parameters, or that the model definition correctly corresponds to the checkpoint." + ) + + save_offload_index(offload_index, offload_folder) + + # Load back offloaded state dict on CPU + if offload_state_dict: + load_offloaded_weights(model, state_dict_index, state_dict_folder) + shutil.rmtree(state_dict_folder) + + retie_parameters(model, tied_params) + + +def get_mixed_precision_context_manager(native_amp: bool = False, autocast_kwargs: AutocastKwargs = None): + """ + Return a context manager for autocasting mixed precision + + Args: + native_amp (`bool`, *optional*, defaults to False): + Whether mixed precision is actually enabled. + cache_enabled (`bool`, *optional*, defaults to True): + Whether the weight cache inside autocast should be enabled. + """ + state = AcceleratorState() + if autocast_kwargs is None: + autocast_kwargs = {} + else: + autocast_kwargs = autocast_kwargs.to_kwargs() + if native_amp: + device_type = ( + "cuda" + if (state.distributed_type == DistributedType.XLA and is_torch_xla_available(check_is_gpu=True)) + else state.device.type + ) + if state.mixed_precision == "fp16": + return torch.autocast(device_type=device_type, dtype=torch.float16, **autocast_kwargs) + elif state.mixed_precision in ["bf16", "fp8"] and state.distributed_type in [ + DistributedType.NO, + DistributedType.MULTI_CPU, + DistributedType.MULTI_GPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_SDAA, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_NPU, + DistributedType.MULTI_XPU, + DistributedType.MULTI_HPU, + DistributedType.FSDP, + DistributedType.XLA, + ]: + return torch.autocast(device_type=device_type, dtype=torch.bfloat16, **autocast_kwargs) + else: + return torch.autocast(device_type=device_type, **autocast_kwargs) + else: + return contextlib.nullcontext() + + +def get_grad_scaler(distributed_type: DistributedType = None, **kwargs): + """ + A generic helper which will initialize the correct `GradScaler` implementation based on the environment and return + it. + + Args: + distributed_type (`DistributedType`, *optional*, defaults to None): + The type of distributed environment. + kwargs: + Additional arguments for the utilized `GradScaler` constructor. + """ + if distributed_type == DistributedType.FSDP: + from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler + + return ShardedGradScaler(**kwargs) + if is_torch_xla_available(check_is_gpu=True): + import torch_xla.amp as xamp + + return xamp.GradScaler(**kwargs) + elif is_mlu_available(): + return torch.mlu.amp.GradScaler(**kwargs) + elif is_sdaa_available(): + return torch.sdaa.amp.GradScaler(**kwargs) + elif is_musa_available(): + return torch.musa.amp.GradScaler(**kwargs) + elif is_npu_available(): + return torch.npu.amp.GradScaler(**kwargs) + elif is_hpu_available(): + return torch.amp.GradScaler("hpu", **kwargs) + elif is_xpu_available(): + return torch.amp.GradScaler("xpu", **kwargs) + else: + if is_torch_version(">=", "2.3"): + return torch.amp.GradScaler("cuda", **kwargs) + else: + return torch.cuda.amp.GradScaler(**kwargs) + + +def has_offloaded_params(module: torch.nn.Module) -> bool: + """ + Checks if a module has offloaded parameters by checking if the given module has a AlignDevicesHook attached with + offloading enabled + + Args: + module (`torch.nn.Module`): The module to check for an offload hook. + + Returns: + bool: `True` if the module has an offload hook and offloading is enabled, `False` otherwise. + """ + from ..hooks import AlignDevicesHook # avoid circular import + + return hasattr(module, "_hf_hook") and isinstance(module._hf_hook, AlignDevicesHook) and module._hf_hook.offload + + +@contextlib.contextmanager +def align_module_device(module: torch.nn.Module, execution_device: Optional[torch.device] = None): + """ + Context manager that moves a module's parameters to the specified execution device. + + Args: + module (`torch.nn.Module`): + Module with parameters to align. + execution_device (`torch.device`, *optional*): + If provided, overrides the module's execution device within the context. Otherwise, use hook execution + device or pass + """ + if has_offloaded_params(module): + if execution_device is not None: + original_device = module._hf_hook.execution_device + module._hf_hook.execution_device = execution_device + + try: + module._hf_hook.pre_forward(module) + yield + finally: + module._hf_hook.post_forward(module, None) + if execution_device is not None: + module._hf_hook.execution_device = original_device + + elif execution_device is not None: + devices = {name: param.device for name, param in module.named_parameters(recurse=False)} + try: + for name in devices: + set_module_tensor_to_device(module, name, execution_device) + yield + finally: + for name, device in devices.items(): + set_module_tensor_to_device(module, name, device) + + else: + yield diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/offload.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/offload.py new file mode 100644 index 0000000000000000000000000000000000000000..d8bff7dc6ad41ffc7f14555261d115d51b76ccec --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/offload.py @@ -0,0 +1,213 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import os +from collections.abc import Mapping +from typing import Optional, Union + +import numpy as np +import torch +from safetensors import safe_open + + +def offload_weight(weight, weight_name, offload_folder, index=None): + dtype = None + # Check the string instead of the dtype to be compatible with versions of PyTorch that don't have bfloat16. + if str(weight.dtype) == "torch.bfloat16": + # Need to reinterpret the underlined data as int16 since NumPy does not handle bfloat16s. + weight = weight.view(torch.int16) + dtype = "bfloat16" + array = weight.cpu().numpy() + tensor_file = os.path.join(offload_folder, f"{weight_name}.dat") + if index is not None: + if dtype is None: + dtype = str(array.dtype) + index[weight_name] = {"dtype": dtype, "shape": list(array.shape)} + if array.ndim == 0: + array = array[None] + file_array = np.memmap(tensor_file, dtype=array.dtype, mode="w+", shape=array.shape) + file_array[:] = array[:] + file_array.flush() + return index + + +def load_offloaded_weight(weight_file, weight_info): + shape = tuple(weight_info["shape"]) + if shape == (): + # NumPy memory-mapped arrays can't have 0 dims so it was saved as 1d tensor + shape = (1,) + + dtype = weight_info["dtype"] + if dtype == "bfloat16": + # NumPy does not support bfloat16 so this was saved as a int16 + dtype = "int16" + + weight = np.memmap(weight_file, dtype=dtype, shape=shape, mode="r") + + if len(weight_info["shape"]) == 0: + weight = weight[0] + weight = torch.tensor(weight) + if weight_info["dtype"] == "bfloat16": + weight = weight.view(torch.bfloat16) + + return weight + + +def save_offload_index(index, offload_folder): + if index is None or len(index) == 0: + # Nothing to save + return + + offload_index_file = os.path.join(offload_folder, "index.json") + if os.path.isfile(offload_index_file): + with open(offload_index_file, encoding="utf-8") as f: + current_index = json.load(f) + else: + current_index = {} + current_index.update(index) + + with open(offload_index_file, "w", encoding="utf-8") as f: + json.dump(current_index, f, indent=2) + + +def offload_state_dict(save_dir: Union[str, os.PathLike], state_dict: dict[str, torch.Tensor]): + """ + Offload a state dict in a given folder. + + Args: + save_dir (`str` or `os.PathLike`): + The directory in which to offload the state dict. + state_dict (`Dict[str, torch.Tensor]`): + The dictionary of tensors to offload. + """ + os.makedirs(save_dir, exist_ok=True) + index = {} + for name, parameter in state_dict.items(): + index = offload_weight(parameter, name, save_dir, index=index) + + # Update index + save_offload_index(index, save_dir) + + +class PrefixedDataset(Mapping): + """ + Will access keys in a given dataset by adding a prefix. + + Args: + dataset (`Mapping`): Any map with string keys. + prefix (`str`): A prefix to add when trying to access any element in the underlying dataset. + """ + + def __init__(self, dataset: Mapping, prefix: str): + self.dataset = dataset + self.prefix = prefix + + def __getitem__(self, key): + return self.dataset[f"{self.prefix}{key}"] + + def __iter__(self): + return iter([key for key in self.dataset if key.startswith(self.prefix)]) + + def __len__(self): + return len(self.dataset) + + +class OffloadedWeightsLoader(Mapping): + """ + A collection that loads weights stored in a given state dict or memory-mapped on disk. + + Args: + state_dict (`Dict[str, torch.Tensor]`, *optional*): + A dictionary parameter name to tensor. + save_folder (`str` or `os.PathLike`, *optional*): + The directory in which the weights are stored (by `offload_state_dict` for instance). + index (`Dict`, *optional*): + A dictionary from weight name to their information (`dtype`/ `shape` or safetensors filename). Will default + to the index saved in `save_folder`. + """ + + def __init__( + self, + state_dict: dict[str, torch.Tensor] = None, + save_folder: Optional[Union[str, os.PathLike]] = None, + index: Mapping = None, + device=None, + ): + if state_dict is None and save_folder is None and index is None: + raise ValueError("Need either a `state_dict`, a `save_folder` or an `index` containing offloaded weights.") + + self.state_dict = {} if state_dict is None else state_dict + self.save_folder = save_folder + if index is None and save_folder is not None: + with open(os.path.join(save_folder, "index.json")) as f: + index = json.load(f) + self.index = {} if index is None else index + self.all_keys = list(self.state_dict.keys()) + self.all_keys.extend([key for key in self.index if key not in self.all_keys]) + self.device = device + + def __getitem__(self, key: str): + # State dict gets priority + if key in self.state_dict: + return self.state_dict[key] + weight_info = self.index[key] + if weight_info.get("safetensors_file") is not None: + device = "cpu" if self.device is None else self.device + tensor = None + try: + with safe_open(weight_info["safetensors_file"], framework="pt", device=device) as f: + tensor = f.get_tensor(weight_info.get("weight_name", key)) + except TypeError: + # if failed to get_tensor on the device, such as bf16 on mps, try to load it on CPU first + with safe_open(weight_info["safetensors_file"], framework="pt", device="cpu") as f: + tensor = f.get_tensor(weight_info.get("weight_name", key)) + + if "dtype" in weight_info: + tensor = tensor.to(getattr(torch, weight_info["dtype"])) + + if tensor.device != torch.device(device): + tensor = tensor.to(device) + return tensor + + weight_file = os.path.join(self.save_folder, f"{key}.dat") + return load_offloaded_weight(weight_file, weight_info) + + def __iter__(self): + return iter(self.all_keys) + + def __len__(self): + return len(self.all_keys) + + +def extract_submodules_state_dict(state_dict: dict[str, torch.Tensor], submodule_names: list[str]): + """ + Extract the sub state-dict corresponding to a list of given submodules. + + Args: + state_dict (`Dict[str, torch.Tensor]`): The state dict to extract from. + submodule_names (`List[str]`): The list of submodule names we want to extract. + """ + result = {} + for module_name in submodule_names: + # We want to catch module_name parameter (module_name.xxx) or potentially module_name, but not any of the + # submodules that could being like module_name (transformers.h.1 and transformers.h.10 for instance) + result.update( + { + key: param + for key, param in state_dict.items() + if key == module_name or key.startswith(module_name + ".") + } + ) + return result diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/operations.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/operations.py new file mode 100644 index 0000000000000000000000000000000000000000..088c0f6efd2a8d7e64a778d70450dd0966984446 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/operations.py @@ -0,0 +1,866 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +A set of basic tensor ops compatible with tpu, gpu, and multigpu +""" + +import pickle +import warnings +from collections.abc import Mapping +from contextlib import contextmanager, nullcontext +from functools import update_wrapper, wraps +from typing import Any + +import torch + +from ..state import AcceleratorState, PartialState +from .constants import TORCH_DISTRIBUTED_OPERATION_TYPES +from .dataclasses import DistributedType, TensorInformation +from .imports import ( + is_npu_available, + is_torch_distributed_available, + is_torch_xla_available, +) + + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + +if is_torch_distributed_available(): + from torch.distributed import ReduceOp + + +def is_torch_tensor(tensor): + return isinstance(tensor, torch.Tensor) + + +def is_torch_xpu_tensor(tensor): + return isinstance( + tensor, + torch.xpu.FloatTensor, + torch.xpu.ByteTensor, + torch.xpu.IntTensor, + torch.xpu.LongTensor, + torch.xpu.HalfTensor, + torch.xpu.DoubleTensor, + torch.xpu.BFloat16Tensor, + ) + + +def is_tensor_information(tensor_info): + return isinstance(tensor_info, TensorInformation) + + +def is_namedtuple(data): + """ + Checks if `data` is a `namedtuple` or not. Can have false positives, but only if a user is trying to mimic a + `namedtuple` perfectly. + """ + return isinstance(data, tuple) and hasattr(data, "_asdict") and hasattr(data, "_fields") + + +def honor_type(obj, generator): + """ + Cast a generator to the same type as obj (list, tuple, or namedtuple) + """ + # Some objects may not be able to instantiate from a generator directly + if is_namedtuple(obj): + return type(obj)(*list(generator)) + else: + return type(obj)(generator) + + +def recursively_apply(func, data, *args, test_type=is_torch_tensor, error_on_other_type=False, **kwargs): + """ + Recursively apply a function on a data structure that is a nested list/tuple/dictionary of a given base type. + + Args: + func (`callable`): + The function to recursively apply. + data (nested list/tuple/dictionary of `main_type`): + The data on which to apply `func` + *args: + Positional arguments that will be passed to `func` when applied on the unpacked data. + main_type (`type`, *optional*, defaults to `torch.Tensor`): + The base type of the objects to which apply `func`. + error_on_other_type (`bool`, *optional*, defaults to `False`): + Whether to return an error or not if after unpacking `data`, we get on an object that is not of type + `main_type`. If `False`, the function will leave objects of types different than `main_type` unchanged. + **kwargs (additional keyword arguments, *optional*): + Keyword arguments that will be passed to `func` when applied on the unpacked data. + + Returns: + The same data structure as `data` with `func` applied to every object of type `main_type`. + """ + if isinstance(data, (tuple, list)): + return honor_type( + data, + ( + recursively_apply( + func, o, *args, test_type=test_type, error_on_other_type=error_on_other_type, **kwargs + ) + for o in data + ), + ) + elif isinstance(data, Mapping): + return type(data)( + { + k: recursively_apply( + func, v, *args, test_type=test_type, error_on_other_type=error_on_other_type, **kwargs + ) + for k, v in data.items() + } + ) + elif test_type(data): + return func(data, *args, **kwargs) + elif error_on_other_type: + raise TypeError( + f"Unsupported types ({type(data)}) passed to `{func.__name__}`. Only nested list/tuple/dicts of " + f"objects that are valid for `{test_type.__name__}` should be passed." + ) + return data + + +def send_to_device(tensor, device, non_blocking=False, skip_keys=None): + """ + Recursively sends the elements in a nested list/tuple/dictionary of tensors to a given device. + + Args: + tensor (nested list/tuple/dictionary of `torch.Tensor`): + The data to send to a given device. + device (`torch.device`): + The device to send the data to. + + Returns: + The same data structure as `tensor` with all tensors sent to the proper device. + """ + if is_torch_tensor(tensor) or hasattr(tensor, "to"): + # `torch.Tensor.to("npu")` could not find context when called for the first time (see this [issue](https://gitee.com/ascend/pytorch/issues/I8KECW?from=project-issue)). + if device == "npu": + device = "npu:0" + try: + return tensor.to(device, non_blocking=non_blocking) + except TypeError: # .to() doesn't accept non_blocking as kwarg + return tensor.to(device) + except AssertionError as error: + # `torch.Tensor.to()` is not supported by `torch_npu` (see this [issue](https://github.com/Ascend/pytorch/issues/16)). + # This call is inside the try-block since is_npu_available is not supported by torch.compile. + if is_npu_available(): + if isinstance(device, int): + device = f"npu:{device}" + else: + raise error + try: + return tensor.to(device, non_blocking=non_blocking) + except TypeError: # .to() doesn't accept non_blocking as kwarg + return tensor.to(device) + elif isinstance(tensor, (tuple, list)): + return honor_type( + tensor, (send_to_device(t, device, non_blocking=non_blocking, skip_keys=skip_keys) for t in tensor) + ) + elif isinstance(tensor, Mapping): + if isinstance(skip_keys, str): + skip_keys = [skip_keys] + elif skip_keys is None: + skip_keys = [] + return type(tensor)( + { + k: t if k in skip_keys else send_to_device(t, device, non_blocking=non_blocking, skip_keys=skip_keys) + for k, t in tensor.items() + } + ) + else: + return tensor + + +def get_data_structure(data): + """ + Recursively gathers the information needed to rebuild a nested list/tuple/dictionary of tensors. + + Args: + data (nested list/tuple/dictionary of `torch.Tensor`): + The data to send to analyze. + + Returns: + The same data structure as `data` with [`~utils.TensorInformation`] instead of tensors. + """ + + def _get_data_structure(tensor): + return TensorInformation(shape=tensor.shape, dtype=tensor.dtype) + + return recursively_apply(_get_data_structure, data) + + +def get_shape(data): + """ + Recursively gathers the shape of a nested list/tuple/dictionary of tensors as a list. + + Args: + data (nested list/tuple/dictionary of `torch.Tensor`): + The data to send to analyze. + + Returns: + The same data structure as `data` with lists of tensor shapes instead of tensors. + """ + + def _get_shape(tensor): + return list(tensor.shape) + + return recursively_apply(_get_shape, data) + + +def initialize_tensors(data_structure): + """ + Recursively initializes tensors from a nested list/tuple/dictionary of [`~utils.TensorInformation`]. + + Returns: + The same data structure as `data` with tensors instead of [`~utils.TensorInformation`]. + """ + + def _initialize_tensor(tensor_info): + return torch.empty(*tensor_info.shape, dtype=tensor_info.dtype) + + return recursively_apply(_initialize_tensor, data_structure, test_type=is_tensor_information) + + +def find_batch_size(data): + """ + Recursively finds the batch size in a nested list/tuple/dictionary of lists of tensors. + + Args: + data (nested list/tuple/dictionary of `torch.Tensor`): The data from which to find the batch size. + + Returns: + `int`: The batch size. + """ + if isinstance(data, (tuple, list, Mapping)) and (len(data) == 0): + raise ValueError(f"Cannot find the batch size from empty {type(data)}.") + + if isinstance(data, (tuple, list)): + return find_batch_size(data[0]) + elif isinstance(data, Mapping): + for k in data.keys(): + return find_batch_size(data[k]) + elif not isinstance(data, torch.Tensor): + raise TypeError(f"Can only find the batch size of tensors but got {type(data)}.") + return data.shape[0] + + +def ignorant_find_batch_size(data): + """ + Same as [`utils.operations.find_batch_size`] except will ignore if `ValueError` and `TypeErrors` are raised + + Args: + data (nested list/tuple/dictionary of `torch.Tensor`): The data from which to find the batch size. + + Returns: + `int`: The batch size. + """ + try: + return find_batch_size(data) + except (ValueError, TypeError): + pass + return None + + +def listify(data): + """ + Recursively finds tensors in a nested list/tuple/dictionary and converts them to a list of numbers. + + Args: + data (nested list/tuple/dictionary of `torch.Tensor`): The data from which to convert to regular numbers. + + Returns: + The same data structure as `data` with lists of numbers instead of `torch.Tensor`. + """ + + def _convert_to_list(tensor): + tensor = tensor.detach().cpu() + if tensor.dtype == torch.bfloat16: + # As of Numpy 1.21.4, NumPy does not support bfloat16 (see + # https://github.com/numpy/numpy/blob/a47ecdea856986cd60eabbd53265c2ca5916ad5d/doc/source/user/basics.types.rst ). + # Until Numpy adds bfloat16, we must convert float32. + tensor = tensor.to(torch.float32) + return tensor.tolist() + + return recursively_apply(_convert_to_list, data) + + +def _tpu_gather(tensor): + def _tpu_gather_one(tensor): + if tensor.ndim == 0: + tensor = tensor.clone()[None] + + # Can only gather contiguous tensors + if not tensor.is_contiguous(): + tensor = tensor.contiguous() + return xm.all_gather(tensor) + + res = recursively_apply(_tpu_gather_one, tensor, error_on_other_type=True) + xm.mark_step() + return res + + +def _gpu_gather(tensor): + state = PartialState() + gather_op = torch.distributed.all_gather_into_tensor + + # FIXME: the below 2 lines are added to work-aound a bug related to INT64 collectives in oneCCL. Remove them once pytorch-2.9 is released. + if state.device.type == "xpu": + torch.xpu.synchronize() + + def _gpu_gather_one(tensor): + if tensor.ndim == 0: + tensor = tensor.clone()[None] + + # Can only gather contiguous tensors + if not tensor.is_contiguous(): + tensor = tensor.contiguous() + + if state.backend is not None and state.backend != "gloo": + # We use `empty` as `all_gather_into_tensor` slightly + # differs from `all_gather` for better efficiency, + # and we rely on the number of items in the tensor + # rather than its direct shape + output_tensors = torch.empty( + state.num_processes * tensor.numel(), + dtype=tensor.dtype, + device=state.device, + ) + gather_op(output_tensors, tensor) + return output_tensors.view(-1, *tensor.size()[1:]) + else: + # a backend of `None` is always CPU + # also gloo does not support `all_gather_into_tensor`, + # which will result in a larger memory overhead for the op + output_tensors = [torch.empty_like(tensor) for _ in range(state.num_processes)] + torch.distributed.all_gather(output_tensors, tensor) + return torch.cat(output_tensors, dim=0) + + return recursively_apply(_gpu_gather_one, tensor, error_on_other_type=True) + + +class DistributedOperationException(Exception): + """ + An exception class for distributed operations. Raised if the operation cannot be performed due to the shape of the + tensors. + """ + + pass + + +def verify_operation(function): + """ + Verifies that `tensor` is the same shape across all processes. Only ran if `PartialState().debug` is `True`. + """ + + @wraps(function) + def wrapper(*args, **kwargs): + if PartialState().distributed_type == DistributedType.NO or not PartialState().debug: + return function(*args, **kwargs) + operation = f"{function.__module__}.{function.__name__}" + if "tensor" in kwargs: + tensor = kwargs["tensor"] + else: + tensor = args[0] + if PartialState().device.type != find_device(tensor).type: + raise DistributedOperationException( + f"One or more of the tensors passed to {operation} were not on the {tensor.device.type} while the `Accelerator` is configured for {PartialState().device.type}. " + f"Please move it to the {PartialState().device.type} before calling {operation}." + ) + shapes = get_shape(tensor) + output = gather_object([shapes]) + if output[0] is not None: + are_same = output.count(output[0]) == len(output) + if not are_same: + process_shape_str = "\n - ".join([f"Process {i}: {shape}" for i, shape in enumerate(output)]) + raise DistributedOperationException( + f"Cannot apply desired operation due to shape mismatches. " + "All shapes across devices must be valid." + f"\n\nOperation: `{operation}`\nInput shapes:\n - {process_shape_str}" + ) + return function(*args, **kwargs) + + return wrapper + + +def chained_operation(function): + """ + Checks that `verify_operation` failed and if so reports a more helpful error chaining the existing + `DistributedOperationException`. + """ + + @wraps(function) + def wrapper(*args, **kwargs): + try: + return function(*args, **kwargs) + except DistributedOperationException as e: + operation = f"{function.__module__}.{function.__name__}" + raise DistributedOperationException( + f"Error found while calling `{operation}`. Please see the earlier error for more details." + ) from e + + return wrapper + + +@verify_operation +def gather(tensor): + """ + Recursively gather tensor in a nested list/tuple/dictionary of tensors from all devices. + + Args: + tensor (nested list/tuple/dictionary of `torch.Tensor`): + The data to gather. + + Returns: + The same data structure as `tensor` with all tensors sent to the proper device. + """ + if PartialState().distributed_type == DistributedType.XLA: + return _tpu_gather(tensor) + elif PartialState().distributed_type in TORCH_DISTRIBUTED_OPERATION_TYPES: + return _gpu_gather(tensor) + else: + return tensor + + +def _gpu_gather_object(object: Any): + output_objects = [None for _ in range(PartialState().num_processes)] + torch.distributed.all_gather_object(output_objects, object) + # all_gather_object returns a list of lists, so we need to flatten it + return [x for y in output_objects for x in y] + + +def gather_object(object: Any): + """ + Recursively gather object in a nested list/tuple/dictionary of objects from all devices. + + Args: + object (nested list/tuple/dictionary of picklable object): + The data to gather. + + Returns: + The same data structure as `object` with all the objects sent to every device. + """ + if PartialState().distributed_type == DistributedType.XLA: + raise NotImplementedError("gather objects in TPU is not supported") + elif PartialState().distributed_type in TORCH_DISTRIBUTED_OPERATION_TYPES: + return _gpu_gather_object(object) + else: + return object + + +def _gpu_broadcast(data, src=0): + def _gpu_broadcast_one(tensor, src=0): + torch.distributed.broadcast(tensor, src=src) + return tensor + + return recursively_apply(_gpu_broadcast_one, data, error_on_other_type=True, src=src) + + +def _tpu_broadcast(tensor, src=0, name="broadcast tensor"): + if isinstance(tensor, (list, tuple)): + return honor_type(tensor, (_tpu_broadcast(t, name=f"{name}_{i}") for i, t in enumerate(tensor))) + elif isinstance(tensor, Mapping): + return type(tensor)({k: _tpu_broadcast(v, name=f"{name}_{k}") for k, v in tensor.items()}) + return xm.mesh_reduce(name, tensor, lambda x: x[src]) + + +TENSOR_TYPE_TO_INT = { + torch.float: 1, + torch.double: 2, + torch.half: 3, + torch.bfloat16: 4, + torch.uint8: 5, + torch.int8: 6, + torch.int16: 7, + torch.int32: 8, + torch.int64: 9, + torch.bool: 10, +} + +TENSOR_INT_TO_DTYPE = {v: k for k, v in TENSOR_TYPE_TO_INT.items()} + + +def gather_tensor_shape(tensor): + """ + Grabs the shape of `tensor` only available on one process and returns a tensor of its shape + """ + # Allocate 80 bytes to store the shape + max_tensor_dimension = 2**20 + state = PartialState() + base_tensor = torch.empty(max_tensor_dimension, dtype=torch.int, device=state.device) + + # Since PyTorch can't just send a tensor to another GPU without + # knowing its size, we store the size of the tensor with data + # in an allocation + if tensor is not None: + shape = tensor.shape + tensor_dtype = TENSOR_TYPE_TO_INT[tensor.dtype] + base_tensor[: len(shape) + 1] = torch.tensor(list(shape) + [tensor_dtype], dtype=int) + # Perform a reduction to copy the size data onto all GPUs + base_tensor = reduce(base_tensor, reduction="sum") + base_tensor = base_tensor[base_tensor.nonzero()] + # The last non-zero data contains the coded dtype the source tensor is + dtype = int(base_tensor[-1:][0]) + base_tensor = base_tensor[:-1] + return base_tensor, dtype + + +def copy_tensor_to_devices(tensor=None) -> torch.Tensor: + """ + Copys a tensor that only exists on a single device and broadcasts it to other devices. Differs from `broadcast` as + each worker doesn't need to know its shape when used (and tensor can be `None`) + + Args: + tensor (`torch.tensor`): + The tensor that should be sent to all devices. Must only have it be defined on a single device, the rest + should be `None`. + """ + state = PartialState() + shape, dtype = gather_tensor_shape(tensor) + if tensor is None: + tensor = torch.zeros(shape, dtype=TENSOR_INT_TO_DTYPE[dtype]).to(state.device) + return reduce(tensor, reduction="sum") + + +@verify_operation +def broadcast(tensor, from_process: int = 0): + """ + Recursively broadcast tensor in a nested list/tuple/dictionary of tensors to all devices. + + Args: + tensor (nested list/tuple/dictionary of `torch.Tensor`): + The data to gather. + from_process (`int`, *optional*, defaults to 0): + The process from which to send the data + + Returns: + The same data structure as `tensor` with all tensors broadcasted to the proper device. + """ + if PartialState().distributed_type == DistributedType.XLA: + return _tpu_broadcast(tensor, src=from_process, name="accelerate.utils.broadcast") + elif PartialState().distributed_type in TORCH_DISTRIBUTED_OPERATION_TYPES: + return _gpu_broadcast(tensor, src=from_process) + else: + return tensor + + +def broadcast_object_list(object_list, from_process: int = 0): + """ + Broadcast a list of picklable objects form one process to the others. + + Args: + object_list (list of picklable objects): + The list of objects to broadcast. This list will be modified inplace. + from_process (`int`, *optional*, defaults to 0): + The process from which to send the data. + + Returns: + The same list containing the objects from process 0. + """ + if PartialState().distributed_type == DistributedType.XLA: + for i, obj in enumerate(object_list): + object_list[i] = xm.mesh_reduce("accelerate.utils.broadcast_object_list", obj, lambda x: x[from_process]) + elif PartialState().distributed_type in TORCH_DISTRIBUTED_OPERATION_TYPES: + torch.distributed.broadcast_object_list(object_list, src=from_process) + return object_list + + +def slice_tensors(data, tensor_slice, process_index=None, num_processes=None): + """ + Recursively takes a slice in a nested list/tuple/dictionary of tensors. + + Args: + data (nested list/tuple/dictionary of `torch.Tensor`): + The data to slice. + tensor_slice (`slice`): + The slice to take. + + Returns: + The same data structure as `data` with all the tensors slices. + """ + + def _slice_tensor(tensor, tensor_slice): + return tensor[tensor_slice] + + return recursively_apply(_slice_tensor, data, tensor_slice) + + +def concatenate(data, dim=0): + """ + Recursively concatenate the tensors in a nested list/tuple/dictionary of lists of tensors with the same shape. + + Args: + data (nested list/tuple/dictionary of lists of tensors `torch.Tensor`): + The data to concatenate. + dim (`int`, *optional*, defaults to 0): + The dimension on which to concatenate. + + Returns: + The same data structure as `data` with all the tensors concatenated. + """ + if isinstance(data[0], (tuple, list)): + return honor_type(data[0], (concatenate([d[i] for d in data], dim=dim) for i in range(len(data[0])))) + elif isinstance(data[0], Mapping): + return type(data[0])({k: concatenate([d[k] for d in data], dim=dim) for k in data[0].keys()}) + elif not isinstance(data[0], torch.Tensor): + raise TypeError(f"Can only concatenate tensors but got {type(data[0])}") + return torch.cat(data, dim=dim) + + +class CannotPadNestedTensorWarning(UserWarning): + pass + + +@chained_operation +def pad_across_processes(tensor, dim=0, pad_index=0, pad_first=False): + """ + Recursively pad the tensors in a nested list/tuple/dictionary of tensors from all devices to the same size so they + can safely be gathered. + + Args: + tensor (nested list/tuple/dictionary of `torch.Tensor`): + The data to gather. + dim (`int`, *optional*, defaults to 0): + The dimension on which to pad. + pad_index (`int`, *optional*, defaults to 0): + The value with which to pad. + pad_first (`bool`, *optional*, defaults to `False`): + Whether to pad at the beginning or the end. + """ + + def _pad_across_processes(tensor, dim=0, pad_index=0, pad_first=False): + if getattr(tensor, "is_nested", False): + warnings.warn( + "Cannot pad nested tensors without more information. Leaving unprocessed.", + CannotPadNestedTensorWarning, + ) + return tensor + if dim >= len(tensor.shape) or dim < -len(tensor.shape): + return tensor + # Convert negative dimensions to non-negative + if dim < 0: + dim += len(tensor.shape) + + # Gather all sizes + size = torch.tensor(tensor.shape, device=tensor.device)[None] + sizes = gather(size).cpu() + # Then pad to the maximum size + max_size = max(s[dim] for s in sizes) + if max_size == tensor.shape[dim]: + return tensor + + old_size = tensor.shape + new_size = list(old_size) + new_size[dim] = max_size + new_tensor = tensor.new_zeros(tuple(new_size)) + pad_index + if pad_first: + indices = tuple( + slice(max_size - old_size[dim], max_size) if i == dim else slice(None) for i in range(len(new_size)) + ) + else: + indices = tuple(slice(0, old_size[dim]) if i == dim else slice(None) for i in range(len(new_size))) + new_tensor[indices] = tensor + return new_tensor + + return recursively_apply( + _pad_across_processes, tensor, error_on_other_type=True, dim=dim, pad_index=pad_index, pad_first=pad_first + ) + + +def pad_input_tensors(tensor, batch_size, num_processes, dim=0): + """ + Takes a `tensor` of arbitrary size and pads it so that it can work given `num_processes` needed dimensions. + + New tensors are just the last input repeated. + + E.g.: + Tensor: ([3,4,4]) Num processes: 4 Expected result shape: ([4,4,4]) + + """ + + def _pad_input_tensors(tensor, batch_size, num_processes, dim=0): + remainder = batch_size // num_processes + last_inputs = batch_size - (remainder * num_processes) + if batch_size // num_processes == 0: + to_pad = num_processes - batch_size + else: + to_pad = num_processes - (batch_size // num_processes) + # In the rare case that `to_pad` is negative, + # we need to pad the last inputs - the found `to_pad` + if last_inputs > to_pad & to_pad < 1: + to_pad = last_inputs - to_pad + old_size = tensor.shape + new_size = list(old_size) + new_size[0] = batch_size + to_pad + new_tensor = tensor.new_zeros(tuple(new_size)) + indices = tuple(slice(0, old_size[dim]) if i == dim else slice(None) for i in range(len(new_size))) + new_tensor[indices] = tensor + return new_tensor + + return recursively_apply( + _pad_input_tensors, + tensor, + error_on_other_type=True, + batch_size=batch_size, + num_processes=num_processes, + dim=dim, + ) + + +@verify_operation +def reduce(tensor, reduction="mean", scale=1.0): + """ + Recursively reduce the tensors in a nested list/tuple/dictionary of lists of tensors across all processes by the + mean of a given operation. + + Args: + tensor (nested list/tuple/dictionary of `torch.Tensor`): + The data to reduce. + reduction (`str`, *optional*, defaults to `"mean"`): + A reduction method. Can be of "mean", "sum", or "none" + scale (`float`, *optional*): + A default scaling value to be applied after the reduce, only valied on XLA. + + Returns: + The same data structure as `data` with all the tensors reduced. + """ + + def _reduce_across_processes(tensor, reduction="mean", scale=1.0): + state = PartialState() + cloned_tensor = tensor.clone() + if state.distributed_type == DistributedType.NO: + return cloned_tensor + if state.distributed_type == DistributedType.XLA: + # Some processes may have different HLO graphs than other + # processes, for example in the breakpoint API + # accelerator.set_trigger(). Use mark_step to make HLOs + # the same on all processes. + xm.mark_step() + xm.all_reduce(xm.REDUCE_SUM, [cloned_tensor], scale) + xm.mark_step() + elif state.distributed_type.value in TORCH_DISTRIBUTED_OPERATION_TYPES: + torch.distributed.all_reduce(cloned_tensor, ReduceOp.SUM) + if reduction == "mean": + cloned_tensor /= state.num_processes + return cloned_tensor + + return recursively_apply( + _reduce_across_processes, tensor, error_on_other_type=True, reduction=reduction, scale=scale + ) + + +def convert_to_fp32(tensor): + """ + Recursively converts the elements nested list/tuple/dictionary of tensors in FP16/BF16 precision to FP32. + + Args: + tensor (nested list/tuple/dictionary of `torch.Tensor`): + The data to convert from FP16/BF16 to FP32. + + Returns: + The same data structure as `tensor` with all tensors that were in FP16/BF16 precision converted to FP32. + """ + + def _convert_to_fp32(tensor): + return tensor.float() + + def _is_fp16_bf16_tensor(tensor): + return (is_torch_tensor(tensor) or hasattr(tensor, "dtype")) and tensor.dtype in ( + torch.float16, + torch.bfloat16, + ) + + return recursively_apply(_convert_to_fp32, tensor, test_type=_is_fp16_bf16_tensor) + + +class ConvertOutputsToFp32: + """ + Decorator to apply to a function outputing tensors (like a model forward pass) that ensures the outputs in FP16 + precision will be convert back to FP32. + + Args: + model_forward (`Callable`): + The function which outputs we want to treat. + + Returns: + The same function as `model_forward` but with converted outputs. + """ + + def __init__(self, model_forward): + self.model_forward = model_forward + update_wrapper(self, model_forward) + + def __call__(self, *args, **kwargs): + return convert_to_fp32(self.model_forward(*args, **kwargs)) + + def __getstate__(self): + raise pickle.PicklingError( + "Cannot pickle a prepared model with automatic mixed precision, please unwrap the model with `Accelerator.unwrap_model(model)` before pickling it." + ) + + +def convert_outputs_to_fp32(model_forward): + model_forward = ConvertOutputsToFp32(model_forward) + + def forward(*args, **kwargs): + return model_forward(*args, **kwargs) + + # To act like a decorator so that it can be popped when doing `extract_model_from_parallel` + forward.__wrapped__ = model_forward + + return forward + + +def find_device(data): + """ + Finds the device on which a nested dict/list/tuple of tensors lies (assuming they are all on the same device). + + Args: + (nested list/tuple/dictionary of `torch.Tensor`): The data we want to know the device of. + """ + if isinstance(data, Mapping): + for obj in data.values(): + device = find_device(obj) + if device is not None: + return device + elif isinstance(data, (tuple, list)): + for obj in data: + device = find_device(obj) + if device is not None: + return device + elif isinstance(data, torch.Tensor): + return data.device + + +@contextmanager +def GatheredParameters(params, modifier_rank=None, fwd_module=None, enabled=True): + """ + Wrapper around `deepspeed.runtime.zero.GatheredParameters`, but if Zero-3 is not enabled, will be a no-op context + manager. + """ + # We need to use the `AcceleratorState` here since it has access to the deepspeed plugin + if AcceleratorState().distributed_type != DistributedType.DEEPSPEED or ( + AcceleratorState().deepspeed_plugin is not None + and not AcceleratorState().deepspeed_plugin.is_zero3_init_enabled() + ): + gather_param_context = nullcontext() + else: + import deepspeed + + gather_param_context = deepspeed.zero.GatheredParameters( + params, modifier_rank=modifier_rank, fwd_module=fwd_module, enabled=enabled + ) + with gather_param_context: + yield diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/other.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/other.py new file mode 100644 index 0000000000000000000000000000000000000000..adc0ed9cbfe66fa6e5fbcfd4da623d279c837a61 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/other.py @@ -0,0 +1,560 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import collections +import platform +import re +import socket +from codecs import encode +from collections import OrderedDict +from functools import partial, reduce +from types import MethodType + +import numpy as np +import torch +from packaging.version import Version +from safetensors.torch import save_file as safe_save_file + +from ..commands.config.default import write_basic_config # noqa: F401 +from ..logging import get_logger +from ..state import PartialState +from .constants import FSDP_PYTORCH_VERSION +from .dataclasses import DistributedType +from .imports import ( + is_deepspeed_available, + is_numpy_available, + is_torch_distributed_available, + is_torch_xla_available, + is_weights_only_available, +) +from .modeling import id_tensor_storage +from .transformer_engine import convert_model +from .versions import is_torch_version + + +logger = get_logger(__name__) + + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + + +def is_compiled_module(module: torch.nn.Module) -> bool: + """ + Check whether the module was compiled with torch.compile() + """ + if not hasattr(torch, "_dynamo"): + return False + + return isinstance(module, torch._dynamo.eval_frame.OptimizedModule) + + +def has_compiled_regions(module: torch.nn.Module) -> bool: + """ + Check whether the module has submodules that were compiled with `torch.compile()`. + """ + if not hasattr(torch, "_dynamo"): + return False + + if module._modules: + for submodule in module.modules(): + if isinstance(submodule, torch._dynamo.eval_frame.OptimizedModule): + return True + + return False + + +def is_repeated_blocks(module: torch.nn.Module) -> bool: + """ + Check whether the module is a repeated block, i.e. `torch.nn.ModuleList` with all children of the same class. This + is useful to determine whether we should apply regional compilation to the module. + """ + + return isinstance(module, torch.nn.ModuleList) and all(isinstance(m, module[0].__class__) for m in module) + + +def has_repeated_blocks(module: torch.nn.Module) -> bool: + """ + Check whether the module has repeated blocks, i.e. `torch.nn.ModuleList` with all children of the same class, at + any level of the module hierarchy. This is useful to determine whether we should apply regional compilation to the + module. + """ + if module._modules: + for submodule in module.modules(): + if is_repeated_blocks(submodule): + return True + + return False + + +def compile_regions(module: torch.nn.Module, **compile_kwargs) -> torch.nn.Module: + """ + Performs regional compilation where we target repeated blocks of the same class and compile them sequentially to + hit the compiler's cache. For example, in `GPT2LMHeadModel`, the repeated block/class is `GPT2Block`, and can be + accessed as `model.transformer.h[0]`. The rest of the model (e.g. model.lm_head) is compiled separately. + + This allows us to speed up the compilation overhead / cold start of models like LLMs and Transformers in general. + See https://pytorch.org/tutorials/recipes/regional_compilation.html for more details. + + Args: + module (`torch.nn.Module`): + The model to compile. + **compile_kwargs: + Additional keyword arguments to pass to `torch.compile()`. + + Returns: + `torch.nn.Module`: A new instance of the model with some compiled regions. + + Example: + ```python + >>> from accelerate.utils import compile_regions + >>> from transformers import AutoModelForCausalLM + + >>> model = AutoModelForCausalLM.from_pretrained("gpt2") + >>> compiled_model = compile_regions(model, mode="reduce-overhead") + >>> compiled_model.transformer.h[0] + OptimizedModule( + (_orig_mod): GPT2Block( + (ln_1): LayerNorm((768,), eps=1e-05, elementwise_affine=True) + (attn): GPT2Attention( + (c_attn): Conv1D(nf=2304, nx=768) + (c_proj): Conv1D(nf=768, nx=768) + (attn_dropout): Dropout(p=0.1, inplace=False) + (resid_dropout): Dropout(p=0.1, inplace=False) + ) + (ln_2): LayerNorm((768,), eps=1e-05, elementwise_affine=True) + (mlp): GPT2MLP( + (c_fc): Conv1D(nf=3072, nx=768) + (c_proj): Conv1D(nf=768, nx=3072) + (act): NewGELUActivation() + (dropout): Dropout(p=0.1, inplace=False) + ) + ) + ) + ``` + """ + + def _compile_regions(module: torch.nn.Module, **compile_kwargs) -> torch.nn.Module: + if is_repeated_blocks(module): + new_module = torch.nn.ModuleList() + for submodule in module: + new_module.append(torch.compile(submodule, **compile_kwargs)) + elif has_repeated_blocks(module): + new_module = module.__class__.__new__(module.__class__) + new_module.__dict__.update(module.__dict__) + new_module._modules = {} + for name, submodule in module.named_children(): + new_module.add_module(name, _compile_regions(submodule, **compile_kwargs)) + else: + new_module = torch.compile(module, **compile_kwargs) + + return new_module + + new_module = _compile_regions(module, **compile_kwargs) + + if "_orig_mod" not in new_module.__dict__: + # Keeps a reference to the original module to decompile/unwrap it later + new_module.__dict__["_orig_mod"] = module + + return new_module + + +def compile_regions_deepspeed(module: torch.nn.Module, **compile_kwargs): + """ + Performs regional compilation the same way as `compile_regions`, but specifically for `DeepSpeedEngine.module`. + Since the model is wrapped in a `DeepSpeedEngine` and has many added hooks, offloaded parameters, etc that + `torch.compile(...)` interferes with, version of trgional compilation uses the inplace `module.compile()` method + instead. + + Args: + module (`torch.nn.Module`): + The model to compile. + **compile_kwargs: + Additional keyword arguments to pass to `module.compile()`. + """ + + if is_repeated_blocks(module): + for submodule in module: + submodule.compile(**compile_kwargs) + elif has_repeated_blocks(module): + for child in module.children(): + compile_regions_deepspeed(child, **compile_kwargs) + else: # leaf node + module.compile(**compile_kwargs) + + +def model_has_dtensor(model: torch.nn.Module) -> bool: + """ + Check if the model has DTensor parameters. + + Args: + model (`torch.nn.Module`): + The model to check. + + Returns: + `bool`: Whether the model has DTensor parameters. + """ + if is_torch_version(">=", "2.5.0"): + from torch.distributed.tensor import DTensor + else: + # from torch 2.0.0 (oldest supported accelerate torch version), DTensor is in torch.distributed._tensor + from torch.distributed._tensor import DTensor + + return any(isinstance(p, DTensor) for p in model.parameters()) + + +def extract_model_from_parallel( + model, keep_fp32_wrapper: bool = True, keep_torch_compile: bool = True, recursive: bool = False +): + """ + Extract a model from its distributed containers. + + Args: + model (`torch.nn.Module`): + The model to extract. + keep_fp32_wrapper (`bool`, *optional*): + Whether to remove mixed precision hooks from the model. + keep_torch_compile (`bool`, *optional*): + Whether to unwrap compiled model. + recursive (`bool`, *optional*, defaults to `False`): + Whether to recursively extract all cases of `module.module` from `model` as well as unwrap child sublayers + recursively, not just the top-level distributed containers. + + Returns: + `torch.nn.Module`: The extracted model. + """ + options = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) + + is_compiled = is_compiled_module(model) + has_compiled = has_compiled_regions(model) + + if is_compiled: + compiled_model = model + model = model._orig_mod + elif has_compiled: + compiled_model = model + model = model.__dict__["_orig_mod"] + + if is_deepspeed_available(): + from deepspeed import DeepSpeedEngine + + options += (DeepSpeedEngine,) + + if is_torch_version(">=", FSDP_PYTORCH_VERSION) and is_torch_distributed_available(): + from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP + + options += (FSDP,) + + while isinstance(model, options): + model = model.module + + if recursive: + # This is needed in cases such as using FSDPv2 on XLA + def _recursive_unwrap(module): + # Wrapped modules are standardly wrapped as `module`, similar to the cases earlier + # with DDP, DataParallel, DeepSpeed, and FSDP + if hasattr(module, "module"): + unwrapped_module = _recursive_unwrap(module.module) + else: + unwrapped_module = module + # Next unwrap child sublayers recursively + for name, child in unwrapped_module.named_children(): + setattr(unwrapped_module, name, _recursive_unwrap(child)) + return unwrapped_module + + # Start with top-level + model = _recursive_unwrap(model) + + if not keep_fp32_wrapper: + forward = model.forward + original_forward = model.__dict__.pop("_original_forward", None) + if original_forward is not None: + while hasattr(forward, "__wrapped__"): + forward = forward.__wrapped__ + if forward == original_forward: + break + model.forward = MethodType(forward, model) + if getattr(model, "_converted_to_transformer_engine", False): + convert_model(model, to_transformer_engine=False) + + if keep_torch_compile: + if is_compiled: + compiled_model._orig_mod = model + model = compiled_model + elif has_compiled: + compiled_model.__dict__["_orig_mod"] = model + model = compiled_model + + return model + + +def wait_for_everyone(): + """ + Introduces a blocking point in the script, making sure all processes have reached this point before continuing. + + + + Make sure all processes will reach this instruction otherwise one of your processes will hang forever. + + + """ + PartialState().wait_for_everyone() + + +def clean_state_dict_for_safetensors(state_dict: dict): + """ + Cleans the state dictionary from a model and removes tensor aliasing if present. + + Args: + state_dict (`dict`): + The state dictionary from a model + """ + ptrs = collections.defaultdict(list) + # When bnb serialization is used, weights in state dict can be strings + for name, tensor in state_dict.items(): + if not isinstance(tensor, str): + ptrs[id_tensor_storage(tensor)].append(name) + + # These are all pointers of tensors with shared memory + shared_ptrs = {ptr: names for ptr, names in ptrs.items() if len(names) > 1} + warn_names = set() + for names in shared_ptrs.values(): + # When not all duplicates have been cleaned, we still remove those keys but put a clear warning. + # If the link between tensors was done at runtime then `from_pretrained` will not get + # the key back leading to random tensor. A proper warning will be shown + # during reload (if applicable), but since the file is not necessarily compatible with + # the config, better show a proper warning. + found_names = [name for name in names if name in state_dict] + warn_names.update(found_names[1:]) + for name in found_names[1:]: + del state_dict[name] + if len(warn_names) > 0: + logger.warning( + f"Removed shared tensor {warn_names} while saving. This should be OK, but check by verifying that you don't receive any warning while reloading", + ) + state_dict = {k: v.contiguous() if isinstance(v, torch.Tensor) else v for k, v in state_dict.items()} + return state_dict + + +def save(obj, f, save_on_each_node: bool = False, safe_serialization: bool = False): + """ + Save the data to disk. Use in place of `torch.save()`. + + Args: + obj: + The data to save + f: + The file (or file-like object) to use to save the data + save_on_each_node (`bool`, *optional*, defaults to `False`): + Whether to only save on the global main process + safe_serialization (`bool`, *optional*, defaults to `False`): + Whether to save `obj` using `safetensors` or the traditional PyTorch way (that uses `pickle`). + """ + # When TorchXLA is enabled, it's necessary to transfer all data to the CPU before saving. + # Another issue arises with `id_tensor_storage`, which treats all XLA tensors as identical. + # If tensors remain on XLA, calling `clean_state_dict_for_safetensors` will result in only + # one XLA tensor remaining. + if PartialState().distributed_type == DistributedType.XLA: + obj = xm._maybe_convert_to_cpu(obj) + # Check if it's a model and remove duplicates + if safe_serialization: + save_func = partial(safe_save_file, metadata={"format": "pt"}) + if isinstance(obj, OrderedDict): + obj = clean_state_dict_for_safetensors(obj) + else: + save_func = torch.save + + if PartialState().is_main_process and not save_on_each_node: + save_func(obj, f) + elif PartialState().is_local_main_process and save_on_each_node: + save_func(obj, f) + + +# The following are considered "safe" globals to reconstruct various types of objects when using `weights_only=True` +# These should be added and then removed after loading in the file +np_core = np._core if is_numpy_available("2.0.0") else np.core +TORCH_SAFE_GLOBALS = [ + # numpy arrays are just numbers, not objects, so we can reconstruct them safely + np_core.multiarray._reconstruct, + np.ndarray, + # The following are needed for the RNG states + encode, + np.dtype, +] + +if is_numpy_available("1.25.0"): + TORCH_SAFE_GLOBALS.append(np.dtypes.UInt32DType) + + +def load(f, map_location=None, **kwargs): + """ + Compatible drop-in replacement of `torch.load()` which allows for `weights_only` to be used if `torch` version is + 2.4.0 or higher. Otherwise will ignore the kwarg. + + Will also add (and then remove) an exception for numpy arrays + + Args: + f: + The file (or file-like object) to use to load the data + map_location: + a function, `torch.device`, string or a dict specifying how to remap storage locations + **kwargs: + Additional keyword arguments to pass to `torch.load()`. + """ + try: + if is_weights_only_available(): + old_safe_globals = torch.serialization.get_safe_globals() + if "weights_only" not in kwargs: + kwargs["weights_only"] = True + torch.serialization.add_safe_globals(TORCH_SAFE_GLOBALS) + else: + kwargs.pop("weights_only", None) + loaded_obj = torch.load(f, map_location=map_location, **kwargs) + finally: + if is_weights_only_available(): + torch.serialization.clear_safe_globals() + if old_safe_globals: + torch.serialization.add_safe_globals(old_safe_globals) + return loaded_obj + + +def get_pretty_name(obj): + """ + Gets a pretty name from `obj`. + """ + if not hasattr(obj, "__qualname__") and not hasattr(obj, "__name__"): + obj = getattr(obj, "__class__", obj) + if hasattr(obj, "__qualname__"): + return obj.__qualname__ + if hasattr(obj, "__name__"): + return obj.__name__ + return str(obj) + + +def merge_dicts(source, destination): + """ + Recursively merges two dictionaries. + + Args: + source (`dict`): The dictionary to merge into `destination`. + destination (`dict`): The dictionary to merge `source` into. + """ + for key, value in source.items(): + if isinstance(value, dict): + node = destination.setdefault(key, {}) + merge_dicts(value, node) + else: + destination[key] = value + + return destination + + +def is_port_in_use(port: int = None) -> bool: + """ + Checks if a port is in use on `localhost`. Useful for checking if multiple `accelerate launch` commands have been + run and need to see if the port is already in use. + """ + if port is None: + port = 29500 + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + return s.connect_ex(("localhost", port)) == 0 + + +def get_free_port() -> int: + """ + Gets a free port on `localhost`. Useful for automatic port selection when port 0 is specified in distributed + training scenarios. + + Returns: + int: An available port number + """ + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("", 0)) # bind to port 0 for OS to assign a free port + return s.getsockname()[1] + + +def convert_bytes(size): + "Converts `size` from bytes to the largest possible unit" + for x in ["bytes", "KB", "MB", "GB", "TB"]: + if size < 1024.0: + return f"{round(size, 2)} {x}" + size /= 1024.0 + + return f"{round(size, 2)} PB" + + +def check_os_kernel(): + """Warns if the kernel version is below the recommended minimum on Linux.""" + # see issue #1929 + info = platform.uname() + system = info.system + if system != "Linux": + return + + _, version, *_ = re.split(r"(\d+\.\d+\.\d+)", info.release) + min_version = "5.5.0" + if Version(version) < Version(min_version): + msg = ( + f"Detected kernel version {version}, which is below the recommended minimum of {min_version}; this can " + "cause the process to hang. It is recommended to upgrade the kernel to the minimum version or higher." + ) + logger.warning(msg, main_process_only=True) + + +def recursive_getattr(obj, attr: str): + """ + Recursive `getattr`. + + Args: + obj: + A class instance holding the attribute. + attr (`str`): + The attribute that is to be retrieved, e.g. 'attribute1.attribute2'. + """ + + def _getattr(obj, attr): + return getattr(obj, attr) + + return reduce(_getattr, [obj] + attr.split(".")) + + +def get_module_children_bottom_up(model: torch.nn.Module, return_fqns: bool = False) -> list[torch.nn.Module]: + """Traverse the model in bottom-up order and return the children modules in that order. + + Args: + model (`torch.nn.Module`): the model to get the children of + + Returns: + `list[torch.nn.Module]`: a list of children modules of `model` in bottom-up order. The last element is the + `model` itself. + """ + top = model if not return_fqns else ("", model) + stack = [top] + ordered_modules = [] + while stack: + current_module = stack.pop() + if return_fqns: + current_module_name, current_module = current_module + for name, attr in current_module.named_children(): + if isinstance(attr, torch.nn.Module): + if return_fqns: + child_name = current_module_name + "." + name if current_module_name else name + stack.append((child_name, attr)) + else: + stack.append(attr) + if return_fqns: + ordered_modules.append((current_module_name, current_module)) + else: + ordered_modules.append(current_module) + return ordered_modules[::-1] diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/random.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/random.py new file mode 100644 index 0000000000000000000000000000000000000000..9dceb598cacc1c1d17b198e0a7c19789ab3b9f39 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/random.py @@ -0,0 +1,156 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import random +from typing import Optional, Union + +import numpy as np +import torch + +from ..state import AcceleratorState +from .constants import CUDA_DISTRIBUTED_TYPES +from .dataclasses import DistributedType, RNGType +from .imports import ( + is_hpu_available, + is_mlu_available, + is_musa_available, + is_npu_available, + is_sdaa_available, + is_torch_xla_available, + is_xpu_available, +) + + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + + +def set_seed(seed: int, device_specific: bool = False, deterministic: bool = False): + """ + Helper function for reproducible behavior to set the seed in `random`, `numpy`, `torch`. + + Args: + seed (`int`): + The seed to set. + device_specific (`bool`, *optional*, defaults to `False`): + Whether to differ the seed on each device slightly with `self.process_index`. + deterministic (`bool`, *optional*, defaults to `False`): + Whether to use deterministic algorithms where available. Can slow down training. + """ + if device_specific: + seed += AcceleratorState().process_index + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + if is_xpu_available(): + torch.xpu.manual_seed_all(seed) + elif is_npu_available(): + torch.npu.manual_seed_all(seed) + elif is_mlu_available(): + torch.mlu.manual_seed_all(seed) + elif is_sdaa_available(): + torch.sdaa.manual_seed_all(seed) + elif is_musa_available(): + torch.musa.manual_seed_all(seed) + elif is_hpu_available(): + torch.hpu.manual_seed_all(seed) + else: + torch.cuda.manual_seed_all(seed) + # ^^ safe to call this function even if cuda is not available + if is_torch_xla_available(): + xm.set_rng_state(seed) + + if deterministic: + torch.use_deterministic_algorithms(True) + + +def synchronize_rng_state(rng_type: Optional[RNGType] = None, generator: Optional[torch.Generator] = None): + # Get the proper rng state + if rng_type == RNGType.TORCH: + rng_state = torch.get_rng_state() + elif rng_type == RNGType.CUDA: + rng_state = torch.cuda.get_rng_state() + elif rng_type == RNGType.XLA: + assert is_torch_xla_available(), "Can't synchronize XLA seeds as torch_xla is unavailable." + rng_state = torch.tensor(xm.get_rng_state()) + elif rng_type == RNGType.NPU: + assert is_npu_available(), "Can't synchronize NPU seeds on an environment without NPUs." + rng_state = torch.npu.get_rng_state() + elif rng_type == RNGType.MLU: + assert is_mlu_available(), "Can't synchronize MLU seeds on an environment without MLUs." + rng_state = torch.mlu.get_rng_state() + elif rng_type == RNGType.SDAA: + assert is_sdaa_available(), "Can't synchronize SDAA seeds on an environment without SDAAs." + rng_state = torch.sdaa.get_rng_state() + elif rng_type == RNGType.MUSA: + assert is_musa_available(), "Can't synchronize MUSA seeds on an environment without MUSAs." + rng_state = torch.musa.get_rng_state() + elif rng_type == RNGType.XPU: + assert is_xpu_available(), "Can't synchronize XPU seeds on an environment without XPUs." + rng_state = torch.xpu.get_rng_state() + elif rng_type == RNGType.HPU: + assert is_hpu_available(), "Can't synchronize HPU seeds on an environment without HPUs." + rng_state = torch.hpu.get_rng_state() + elif rng_type == RNGType.GENERATOR: + assert generator is not None, "Need a generator to synchronize its seed." + rng_state = generator.get_state() + + # Broadcast the rng state from device 0 to other devices + state = AcceleratorState() + if state.distributed_type == DistributedType.XLA: + rng_state = rng_state.to(xm.xla_device()) + xm.collective_broadcast([rng_state]) + xm.mark_step() + rng_state = rng_state.cpu() + elif ( + state.distributed_type in CUDA_DISTRIBUTED_TYPES + or state.distributed_type == DistributedType.MULTI_MLU + or state.distributed_type == DistributedType.MULTI_SDAA + or state.distributed_type == DistributedType.MULTI_MUSA + or state.distributed_type == DistributedType.MULTI_NPU + or state.distributed_type == DistributedType.MULTI_XPU + or state.distributed_type == DistributedType.MULTI_HPU + ): + rng_state = rng_state.to(state.device) + torch.distributed.broadcast(rng_state, 0) + rng_state = rng_state.cpu() + elif state.distributed_type == DistributedType.MULTI_CPU: + torch.distributed.broadcast(rng_state, 0) + + # Set the broadcast rng state + if rng_type == RNGType.TORCH: + torch.set_rng_state(rng_state) + elif rng_type == RNGType.CUDA: + torch.cuda.set_rng_state(rng_state) + elif rng_type == RNGType.NPU: + torch.npu.set_rng_state(rng_state) + elif rng_type == RNGType.MLU: + torch.mlu.set_rng_state(rng_state) + elif rng_type == RNGType.SDAA: + torch.sdaa.set_rng_state(rng_state) + elif rng_type == RNGType.MUSA: + torch.musa.set_rng_state(rng_state) + elif rng_type == RNGType.XPU: + torch.xpu.set_rng_state(rng_state) + elif rng_state == RNGType.HPU: + torch.hpu.set_rng_state(rng_state) + elif rng_type == RNGType.XLA: + xm.set_rng_state(rng_state.item()) + elif rng_type == RNGType.GENERATOR: + generator.set_state(rng_state) + + +def synchronize_rng_states(rng_types: list[Union[str, RNGType]], generator: Optional[torch.Generator] = None): + for rng_type in rng_types: + synchronize_rng_state(RNGType(rng_type), generator=generator) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/rich.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/rich.py new file mode 100644 index 0000000000000000000000000000000000000000..2d48661b7fcef92ef1168b74cc275c6d3ccc67a1 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/rich.py @@ -0,0 +1,24 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .imports import is_rich_available + + +if is_rich_available(): + from rich.traceback import install + + install(show_locals=False) + +else: + raise ModuleNotFoundError("To use the rich extension, install rich with `pip install rich`") diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/torch_xla.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/torch_xla.py new file mode 100644 index 0000000000000000000000000000000000000000..140133926c2f88d39c70f5a9f46a08f88bed36da --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/torch_xla.py @@ -0,0 +1,51 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import importlib.metadata +import subprocess +import sys + + +def install_xla(upgrade: bool = False): + """ + Helper function to install appropriate xla wheels based on the `torch` version in Google Colaboratory. + + Args: + upgrade (`bool`, *optional*, defaults to `False`): + Whether to upgrade `torch` and install the latest `torch_xla` wheels. + + Example: + + ```python + >>> from accelerate.utils import install_xla + + >>> install_xla(upgrade=True) + ``` + """ + in_colab = False + if "IPython" in sys.modules: + in_colab = "google.colab" in str(sys.modules["IPython"].get_ipython()) + + if in_colab: + if upgrade: + torch_install_cmd = ["pip", "install", "-U", "torch"] + subprocess.run(torch_install_cmd, check=True) + # get the current version of torch + torch_version = importlib.metadata.version("torch") + torch_version_trunc = torch_version[: torch_version.rindex(".")] + xla_wheel = f"https://storage.googleapis.com/tpu-pytorch/wheels/colab/torch_xla-{torch_version_trunc}-cp37-cp37m-linux_x86_64.whl" + xla_install_cmd = ["pip", "install", xla_wheel] + subprocess.run(xla_install_cmd, check=True) + else: + raise RuntimeError("`install_xla` utility works only on google colab.") diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/tqdm.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/tqdm.py new file mode 100644 index 0000000000000000000000000000000000000000..2d4873c1573eb2ee7392162f440a76d4f07cd8ce --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/tqdm.py @@ -0,0 +1,43 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from .imports import is_tqdm_available + + +if is_tqdm_available(): + from tqdm.auto import tqdm as _tqdm + +from ..state import PartialState + + +def tqdm(*args, main_process_only: bool = True, **kwargs): + """ + Wrapper around `tqdm.tqdm` that optionally displays only on the main process. + + Args: + main_process_only (`bool`, *optional*): + Whether to display the progress bar only on the main process + """ + if not is_tqdm_available(): + raise ImportError("Accelerate's `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`.") + if len(args) > 0 and isinstance(args[0], bool): + raise ValueError( + "Passing `True` or `False` as the first argument to Accelerate's `tqdm` wrapper is unsupported. " + "Please use the `main_process_only` keyword argument instead." + ) + disable = kwargs.pop("disable", False) + if main_process_only and not disable: + disable = PartialState().local_process_index != 0 + return _tqdm(*args, **kwargs, disable=disable) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/transformer_engine.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/transformer_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..337213453b3d15f610f41ac71c5afe15e034b38c --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/transformer_engine.py @@ -0,0 +1,164 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from types import MethodType + +import torch.nn as nn + +from .imports import is_hpu_available, is_transformer_engine_available +from .operations import GatheredParameters + + +# Do not import `transformer_engine` at package level to avoid potential issues + + +def convert_model(model, to_transformer_engine=True, _convert_linear=True, _convert_ln=True): + """ + Recursively converts the linear and layernorm layers of a model to their `transformers_engine` counterpart. + """ + if not is_transformer_engine_available(): + raise ImportError("Using `convert_model` requires transformer_engine to be installed.") + + if is_hpu_available(): + import intel_transformer_engine as te + + if not hasattr(te, "LayerNorm"): + # HPU does not have a LayerNorm implementation in TE + te.LayerNorm = nn.LayerNorm + else: + import transformer_engine.pytorch as te + + for name, module in model.named_children(): + if isinstance(module, nn.Linear) and to_transformer_engine and _convert_linear: + has_bias = module.bias is not None + params_to_gather = [module.weight] + if has_bias: + params_to_gather.append(module.bias) + + with GatheredParameters(params_to_gather, modifier_rank=0): + if any(p % 16 != 0 for p in module.weight.shape): + return + te_module = te.Linear( + module.in_features, module.out_features, bias=has_bias, params_dtype=module.weight.dtype + ) + te_module.weight.copy_(module.weight) + if has_bias: + te_module.bias.copy_(module.bias) + + setattr(model, name, te_module) + # Note: @xrsrke (Phuc) found that te.LayerNorm doesn't have any real memory savings or speedups over nn.LayerNorm + elif isinstance(module, nn.LayerNorm) and to_transformer_engine and _convert_ln: + with GatheredParameters([module.weight, module.bias], modifier_rank=0): + te_module = te.LayerNorm(module.normalized_shape[0], eps=module.eps, params_dtype=module.weight.dtype) + te_module.weight.copy_(module.weight) + te_module.bias.copy_(module.bias) + + setattr(model, name, te_module) + elif isinstance(module, te.Linear) and not to_transformer_engine and _convert_linear: + has_bias = module.bias is not None + new_module = nn.Linear( + module.in_features, module.out_features, bias=has_bias, params_dtype=module.weight.dtype + ) + new_module.weight.copy_(module.weight) + if has_bias: + new_module.bias.copy_(module.bias) + + setattr(model, name, new_module) + elif isinstance(module, te.LayerNorm) and not to_transformer_engine and _convert_ln: + new_module = nn.LayerNorm(module.normalized_shape[0], eps=module.eps, params_dtype=module.weight.dtype) + new_module.weight.copy_(module.weight) + new_module.bias.copy_(module.bias) + + setattr(model, name, new_module) + else: + convert_model( + module, + to_transformer_engine=to_transformer_engine, + _convert_linear=_convert_linear, + _convert_ln=_convert_ln, + ) + + +def has_transformer_engine_layers(model): + """ + Returns whether a given model has some `transformer_engine` layer or not. + """ + if not is_transformer_engine_available(): + raise ImportError("Using `has_transformer_engine_layers` requires transformer_engine to be installed.") + + if is_hpu_available(): + import intel_transformer_engine as te + + module_cls_to_check = te.Linear + else: + import transformer_engine.pytorch as te + + module_cls_to_check = (te.LayerNorm, te.Linear, te.TransformerLayer) + + for m in model.modules(): + if isinstance(m, module_cls_to_check): + return True + + return False + + +def contextual_fp8_autocast(model_forward, fp8_recipe, use_during_eval=False): + """ + Wrapper for a model's forward method to apply FP8 autocast. Is context aware, meaning that by default it will + disable FP8 autocast during eval mode, which is generally better for more accurate metrics. + """ + if not is_transformer_engine_available(): + raise ImportError("Using `contextual_fp8_autocast` requires transformer_engine to be installed.") + + if is_hpu_available(): + from intel_transformer_engine import fp8_autocast + else: + from transformer_engine.pytorch import fp8_autocast + + def forward(self, *args, **kwargs): + enabled = use_during_eval or self.training + with fp8_autocast(enabled=enabled, fp8_recipe=fp8_recipe): + return model_forward(*args, **kwargs) + + # To act like a decorator so that it can be popped when doing `extract_model_from_parallel` + forward.__wrapped__ = model_forward + + return forward + + +def apply_fp8_autowrap(model, fp8_recipe_handler): + """ + Applies FP8 context manager to the model's forward method + """ + if not is_transformer_engine_available(): + raise ImportError("Using `apply_fp8_autowrap` requires transformer_engine to be installed.") + + if is_hpu_available(): + import intel_transformer_engine.recipe as te_recipe + else: + import transformer_engine.common.recipe as te_recipe + + kwargs = fp8_recipe_handler.to_kwargs() if fp8_recipe_handler is not None else {} + if "fp8_format" in kwargs: + kwargs["fp8_format"] = getattr(te_recipe.Format, kwargs["fp8_format"]) + use_during_eval = kwargs.pop("use_autocast_during_eval", False) + fp8_recipe = te_recipe.DelayedScaling(**kwargs) + new_forward = contextual_fp8_autocast(model.forward, fp8_recipe, use_during_eval) + + if hasattr(model.forward, "__func__"): + model.forward = MethodType(new_forward, model) + else: + model.forward = new_forward + + return model diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/versions.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/versions.py new file mode 100644 index 0000000000000000000000000000000000000000..985c918f0e057bacc70c372f6906071bb73db577 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/utils/versions.py @@ -0,0 +1,56 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import importlib.metadata +from typing import Union + +from packaging.version import Version, parse + +from .constants import STR_OPERATION_TO_FUNC + + +torch_version = parse(importlib.metadata.version("torch")) + + +def compare_versions(library_or_version: Union[str, Version], operation: str, requirement_version: str): + """ + Compares a library version to some requirement using a given operation. + + Args: + library_or_version (`str` or `packaging.version.Version`): + A library name or a version to check. + operation (`str`): + A string representation of an operator, such as `">"` or `"<="`. + requirement_version (`str`): + The version to compare the library version against + """ + if operation not in STR_OPERATION_TO_FUNC.keys(): + raise ValueError(f"`operation` must be one of {list(STR_OPERATION_TO_FUNC.keys())}, received {operation}") + operation = STR_OPERATION_TO_FUNC[operation] + if isinstance(library_or_version, str): + library_or_version = parse(importlib.metadata.version(library_or_version)) + return operation(library_or_version, parse(requirement_version)) + + +def is_torch_version(operation: str, version: str): + """ + Compares the current PyTorch version to a given reference with an operation. + + Args: + operation (`str`): + A string representation of an operator, such as `">"` or `"<="` + version (`str`): + A string version of PyTorch + """ + return compare_versions(torch_version, operation, version) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/__init__.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8568c82be1c638c0ccd34d460fd8b0f73dcbec4e --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2025 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/ds_config_zero2.json b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/ds_config_zero2.json new file mode 100644 index 0000000000000000000000000000000000000000..f031969eeb8cc01c910493a73ea3bffdff518c8c --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/ds_config_zero2.json @@ -0,0 +1,49 @@ +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "bf16": { + "enabled": "auto" + }, + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "weight_decay": "auto", + "torch_adam": true, + "adam_w_mode": true + } + }, + "scheduler": { + "type": "WarmupLR", + "params": { + "warmup_min_lr": "auto", + "warmup_max_lr": "auto", + "warmup_num_steps": "auto" + } + }, + "zero_optimization": { + "stage": 2, + "offload_optimizer": { + "device": "cpu", + "pin_memory": true + }, + "allgather_partitions": true, + "allgather_bucket_size": 2e8, + "overlap_comm": true, + "reduce_scatter": true, + "reduce_bucket_size": "auto", + "contiguous_gradients": true + }, + "gradient_accumulation_steps": 1, + "gradient_clipping": "auto", + "steps_per_print": 2000, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "wall_clock_breakdown": false +} \ No newline at end of file diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/ds_config_zero2_model_only.json b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/ds_config_zero2_model_only.json new file mode 100644 index 0000000000000000000000000000000000000000..83f31b24960299e311579a923e6cddeb4de96575 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/ds_config_zero2_model_only.json @@ -0,0 +1,32 @@ +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "bf16": { + "enabled": "auto" + }, + "zero_optimization": { + "stage": 2, + "offload_optimizer": { + "device": "cpu", + "pin_memory": true + }, + "allgather_partitions": true, + "allgather_bucket_size": 2e8, + "overlap_comm": true, + "reduce_scatter": true, + "reduce_bucket_size": "auto", + "contiguous_gradients": true + }, + "gradient_accumulation_steps": 1, + "gradient_clipping": "auto", + "steps_per_print": 2000, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "wall_clock_breakdown": false +} \ No newline at end of file diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/ds_config_zero3.json b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/ds_config_zero3.json new file mode 100644 index 0000000000000000000000000000000000000000..846cd73614802f6e6f51bce59bae93f771b3b8cd --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/ds_config_zero3.json @@ -0,0 +1,56 @@ +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "bf16": { + "enabled": "auto" + }, + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "weight_decay": "auto", + "torch_adam": true, + "adam_w_mode": true + } + }, + "scheduler": { + "type": "WarmupLR", + "params": { + "warmup_min_lr": "auto", + "warmup_max_lr": "auto", + "warmup_num_steps": "auto" + } + }, + "zero_optimization": { + "stage": 3, + "offload_optimizer": { + "device": "cpu", + "pin_memory": true + }, + "offload_param": { + "device": "cpu", + "pin_memory": true + }, + "overlap_comm": true, + "contiguous_gradients": true, + "sub_group_size": 1e9, + "reduce_bucket_size": "auto", + "stage3_prefetch_bucket_size": "auto", + "stage3_param_persistence_threshold": "auto", + "stage3_max_live_parameters": 1e9, + "stage3_max_reuse_distance": 1e9, + "stage3_gather_16bit_weights_on_model_save": "auto" + }, + "gradient_accumulation_steps": 1, + "gradient_clipping": "auto", + "steps_per_print": 2000, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "wall_clock_breakdown": false +} \ No newline at end of file diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/ds_config_zero3_model_only.json b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/ds_config_zero3_model_only.json new file mode 100644 index 0000000000000000000000000000000000000000..18e21c8086b51b0df8d213a3afa4878dcc503a5b --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/ds_config_zero3_model_only.json @@ -0,0 +1,29 @@ +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "bf16": { + "enabled": "auto" + }, + "zero_optimization": { + "stage": 3, + "offload_param": { + "device": "cpu", + "pin_memory": true + }, + "overlap_comm": true, + "sub_group_size": 1e9, + "reduce_bucket_size": 1e9, + "stage3_prefetch_bucket_size": 1e9, + "stage3_param_persistence_threshold": 1e9, + "stage3_max_live_parameters": 1e9, + "stage3_max_reuse_distance": 1e9, + "stage3_gather_16bit_weights_on_model_save": true + }, + "train_micro_batch_size_per_gpu": 1 +} \ No newline at end of file diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/test_deepspeed.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/test_deepspeed.py new file mode 100644 index 0000000000000000000000000000000000000000..b4ec28deaaad761f99d10eb5ce624588c0f12c86 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/test_deepspeed.py @@ -0,0 +1,1131 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import inspect +import itertools +import json +import os +import tempfile +from copy import deepcopy +from pathlib import Path + +import torch +from parameterized import parameterized +from torch.utils.data import BatchSampler, DataLoader, RandomSampler, SequentialSampler +from transformers import AutoConfig, AutoModel, AutoModelForCausalLM, get_scheduler + +from accelerate.accelerator import Accelerator +from accelerate.scheduler import AcceleratedScheduler +from accelerate.state import AcceleratorState +from accelerate.test_utils.testing import ( + AccelerateTestCase, + TempDirTestCase, + execute_subprocess_async, + path_in_accelerate_package, + require_deepspeed, + require_fp16, + require_huggingface_suite, + require_multi_device, + require_non_cpu, + run_first, + slow, +) +from accelerate.test_utils.training import RegressionDataset, RegressionModel +from accelerate.utils import is_bf16_available, is_fp16_available, patch_environment, set_seed +from accelerate.utils.dataclasses import DeepSpeedPlugin +from accelerate.utils.deepspeed import ( + DeepSpeedEngineWrapper, + DeepSpeedOptimizerWrapper, + DeepSpeedSchedulerWrapper, + DummyOptim, + DummyScheduler, +) +from accelerate.utils.versions import compare_versions + + +set_seed(42) + +GPT2_TINY = "sshleifer/tiny-gpt2" +MOBILEVIT = "apple/mobilevit-xx-small" +QWEN_MOE = "peft-internal-testing/tiny-random-qwen-1.5-MoE" + +ZERO2 = "zero2" +ZERO3 = "zero3" + +FP16 = "fp16" +BF16 = "bf16" + +CUSTOM_OPTIMIZER = "custom_optimizer" +CUSTOM_SCHEDULER = "custom_scheduler" +DS_OPTIMIZER = "deepspeed_optimizer" +DS_SCHEDULER = "deepspeed_scheduler" + +NO_CONFIG = "no_config" +CONFIG_WITH_NO_HIDDEN_SIZE = "config_with_no_hidden_size" +CONFIG_WITH_HIDDEN_SIZE = "config_with_hidden_size" +CONFIG_WITH_HIDDEN_SIZES = "config_with_hidden_sizes" + +stages = [ZERO2, ZERO3] +optims = [CUSTOM_OPTIMIZER, DS_OPTIMIZER] +schedulers = [CUSTOM_SCHEDULER, DS_SCHEDULER] +model_types = [NO_CONFIG, CONFIG_WITH_NO_HIDDEN_SIZE, CONFIG_WITH_HIDDEN_SIZE, CONFIG_WITH_HIDDEN_SIZES] + +dtypes = [] +if is_bf16_available(): + dtypes.append(BF16) +if is_fp16_available(): + dtypes.append(FP16) + + +def parameterized_custom_name_func(func, param_num, param): + # customize the test name generator function as we want both params to appear in the sub-test + # name, as by default it shows only the first param + param_based_name = parameterized.to_safe_name("_".join(str(x) for x in param.args)) + return f"{func.__name__}_{param_based_name}" + + +# Cartesian-product of zero stages with models to test +params = list(itertools.product(stages, dtypes)) +optim_scheduler_params = list(itertools.product(optims, schedulers)) + + +class DummyConfig: + def __init__(self): + self._name_or_path = "dummy" + + +@require_deepspeed +@require_non_cpu +class DeepSpeedConfigIntegration(AccelerateTestCase): + def setUp(self): + super().setUp() + + self._test_file_path = inspect.getfile(self.__class__) + path = Path(self._test_file_path).resolve() + self.test_file_dir_str = str(path.parents[0]) + + self.ds_config_file = dict( + zero2=f"{self.test_file_dir_str}/ds_config_zero2.json", + zero3=f"{self.test_file_dir_str}/ds_config_zero3.json", + ) + + # use self.get_config_dict(stage) to use these to ensure the original is not modified + with open(self.ds_config_file[ZERO2], encoding="utf-8") as f: + config_zero2 = json.load(f) + with open(self.ds_config_file[ZERO3], encoding="utf-8") as f: + config_zero3 = json.load(f) + # The following setting slows things down, so don't enable it by default unless needed by a test. + # It's in the file as a demo for users since we want everything to work out of the box even if slower. + config_zero3["zero_optimization"]["stage3_gather_16bit_weights_on_model_save"] = False + + self.ds_config_dict = dict(zero2=config_zero2, zero3=config_zero3) + + self.dist_env = dict( + ACCELERATE_USE_DEEPSPEED="true", + MASTER_ADDR="localhost", + MASTER_PORT="10999", + RANK="0", + LOCAL_RANK="0", + WORLD_SIZE="1", + ) + + def get_config_dict(self, stage): + # As some tests modify the dict, always make a copy + return deepcopy(self.ds_config_dict[stage]) + + @parameterized.expand(stages, name_func=parameterized_custom_name_func) + def test_deepspeed_plugin(self, stage): + # Test zero3_init_flag will be set to False when ZeRO stage != 3 + deepspeed_plugin = DeepSpeedPlugin( + gradient_accumulation_steps=1, + gradient_clipping=1.0, + zero_stage=2, + offload_optimizer_device="cpu", + offload_param_device="cpu", + zero3_save_16bit_model=True, + zero3_init_flag=True, + ) + assert not deepspeed_plugin.zero3_init_flag + deepspeed_plugin.deepspeed_config = None + + # Test zero3_init_flag will be set to True only when ZeRO stage == 3 + deepspeed_plugin = DeepSpeedPlugin( + gradient_accumulation_steps=1, + gradient_clipping=1.0, + zero_stage=3, + offload_optimizer_device="cpu", + offload_param_device="cpu", + zero3_save_16bit_model=True, + zero3_init_flag=True, + ) + assert deepspeed_plugin.zero3_init_flag + deepspeed_plugin.deepspeed_config = None + + # Test config files are loaded correctly + deepspeed_plugin = DeepSpeedPlugin(hf_ds_config=self.ds_config_file[stage], zero3_init_flag=True) + if stage == ZERO2: + assert not deepspeed_plugin.zero3_init_flag + elif stage == ZERO3: + assert deepspeed_plugin.zero3_init_flag + + # Test `gradient_accumulation_steps` is set to 1 if unavailable in config file + with tempfile.TemporaryDirectory() as dirpath: + ds_config = self.get_config_dict(stage) + del ds_config["gradient_accumulation_steps"] + with open(os.path.join(dirpath, "ds_config.json"), "w") as out_file: + json.dump(ds_config, out_file) + deepspeed_plugin = DeepSpeedPlugin(hf_ds_config=os.path.join(dirpath, "ds_config.json")) + assert deepspeed_plugin.deepspeed_config["gradient_accumulation_steps"] == 1 + deepspeed_plugin.deepspeed_config = None + + # Test `ValueError` is raised if `zero_optimization` is unavailable in config file + with tempfile.TemporaryDirectory() as dirpath: + ds_config = self.get_config_dict(stage) + del ds_config["zero_optimization"] + with open(os.path.join(dirpath, "ds_config.json"), "w") as out_file: + json.dump(ds_config, out_file) + with self.assertRaises(ValueError) as cm: + deepspeed_plugin = DeepSpeedPlugin(hf_ds_config=os.path.join(dirpath, "ds_config.json")) + assert "Please specify the ZeRO optimization config in the DeepSpeed config." in str(cm.exception) + deepspeed_plugin.deepspeed_config = None + + # Test `deepspeed_config_process` + deepspeed_plugin = DeepSpeedPlugin(hf_ds_config=self.ds_config_file[stage]) + kwargs = { + "fp16.enabled": True, + "bf16.enabled": False, + "optimizer.params.lr": 5e-5, + "optimizer.params.weight_decay": 0.0, + "scheduler.params.warmup_min_lr": 0.0, + "scheduler.params.warmup_max_lr": 5e-5, + "scheduler.params.warmup_num_steps": 0, + "train_micro_batch_size_per_gpu": 16, + "gradient_clipping": 1.0, + "train_batch_size": 16, + "zero_optimization.reduce_bucket_size": 5e5, + "zero_optimization.stage3_prefetch_bucket_size": 5e5, + "zero_optimization.stage3_param_persistence_threshold": 5e5, + "zero_optimization.stage3_gather_16bit_weights_on_model_save": False, + } + deepspeed_plugin.deepspeed_config_process(**kwargs) + for ds_key_long, value in kwargs.items(): + config, ds_key = deepspeed_plugin.hf_ds_config.find_config_node(ds_key_long) + if config.get(ds_key) is not None: + assert config.get(ds_key) == value + + # Test mismatches + mismatches = { + "optimizer.params.lr": 1e-5, + "optimizer.params.weight_decay": 1e-5, + "gradient_accumulation_steps": 2, + } + with self.assertRaises(ValueError) as cm: + new_kwargs = deepcopy(kwargs) + new_kwargs.update(mismatches) + deepspeed_plugin.deepspeed_config_process(**new_kwargs) + for key in mismatches.keys(): + assert key in str(cm.exception), f"{key} is not in the exception message: {cm.exception}" + + # Test `ValueError` is raised if some config file fields with `auto` value is missing in `kwargs` + deepspeed_plugin.deepspeed_config["optimizer"]["params"]["lr"] = "auto" + with self.assertRaises(ValueError) as cm: + del kwargs["optimizer.params.lr"] + deepspeed_plugin.deepspeed_config_process(**kwargs) + assert "`optimizer.params.lr` not found in kwargs." in str(cm.exception) + + @parameterized.expand(dtypes, name_func=parameterized_custom_name_func) + def test_accelerate_state_deepspeed(self, dtype): + AcceleratorState._reset_state(True) + deepspeed_plugin = DeepSpeedPlugin( + gradient_accumulation_steps=1, + gradient_clipping=1.0, + zero_stage=ZERO2, + offload_optimizer_device="cpu", + offload_param_device="cpu", + zero3_save_16bit_model=True, + zero3_init_flag=True, + ) + with patch_environment(**self.dist_env): + state = Accelerator(mixed_precision=dtype, deepspeed_plugin=deepspeed_plugin).state + assert state.deepspeed_plugin.deepspeed_config[dtype]["enabled"] + + def test_init_zero3(self): + deepspeed_plugin = DeepSpeedPlugin( + gradient_accumulation_steps=1, + gradient_clipping=1.0, + zero_stage=3, + offload_optimizer_device="cpu", + offload_param_device="cpu", + zero3_save_16bit_model=True, + zero3_init_flag=True, + ) + + with patch_environment(**self.dist_env): + accelerator = Accelerator(deepspeed_plugin=deepspeed_plugin) # noqa: F841 + from transformers.integrations import is_deepspeed_zero3_enabled + + assert is_deepspeed_zero3_enabled() + + @parameterized.expand(optim_scheduler_params, name_func=parameterized_custom_name_func) + @require_fp16 + def test_prepare_deepspeed(self, optim_type, scheduler_type): + # 1. Testing with one of the ZeRO Stages is enough to test the `_prepare_deepspeed` function. + # Here we test using ZeRO Stage 2 with FP16 enabled. + from deepspeed.runtime.engine import DeepSpeedEngine + + kwargs = { + "optimizer.params.lr": 5e-5, + "optimizer.params.weight_decay": 0.0, + "scheduler.params.warmup_min_lr": 0.0, + "scheduler.params.warmup_max_lr": 5e-5, + "scheduler.params.warmup_num_steps": 0, + "train_micro_batch_size_per_gpu": 16, + "gradient_clipping": 1.0, + "train_batch_size": 16, + "zero_optimization.reduce_bucket_size": 5e5, + "zero_optimization.stage3_prefetch_bucket_size": 5e5, + "zero_optimization.stage3_param_persistence_threshold": 5e5, + "zero_optimization.stage3_gather_16bit_weights_on_model_save": False, + } + + if optim_type == CUSTOM_OPTIMIZER and scheduler_type == CUSTOM_SCHEDULER: + # Test custom optimizer + custom scheduler + deepspeed_plugin = DeepSpeedPlugin( + gradient_accumulation_steps=1, + gradient_clipping=1.0, + zero_stage=2, + offload_optimizer_device="cpu", + offload_param_device="cpu", + zero3_save_16bit_model=False, + zero3_init_flag=False, + ) + with patch_environment(**self.dist_env): + accelerator = Accelerator(mixed_precision="fp16", deepspeed_plugin=deepspeed_plugin) + + train_set = RegressionDataset(length=80) + eval_set = RegressionDataset(length=20) + train_dataloader = DataLoader(train_set, batch_size=16, shuffle=True) + eval_dataloader = DataLoader(eval_set, batch_size=32, shuffle=False) + model = AutoModel.from_pretrained(GPT2_TINY) + optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5) + lr_scheduler = get_scheduler( + name="linear", + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=1000, + ) + dummy_optimizer = DummyOptim(params=model.parameters()) + dummy_lr_scheduler = DummyScheduler(dummy_optimizer) + + with self.assertRaises(ValueError) as cm: + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, dummy_optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + assert "You cannot create a `DummyOptim` without specifying an optimizer in the config file." in str( + cm.exception + ) + with self.assertRaises(ValueError) as cm: + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, dummy_lr_scheduler + ) + assert ( + "Either specify a scheduler in the config file or " + "pass in the `lr_scheduler_callable` parameter when using `accelerate.utils.DummyScheduler`." + in str(cm.exception) + ) + + with self.assertRaises(ValueError) as cm: + model, optimizer, lr_scheduler = accelerator.prepare(model, optimizer, lr_scheduler) + assert ( + "When using DeepSpeed, `accelerate.prepare()` requires you to pass at least one of training or evaluation dataloaders " + "with `batch_size` attribute returning an integer value " + "or alternatively set an integer value in `train_micro_batch_size_per_gpu` in the deepspeed config file " + "or assign integer value to `AcceleratorState().deepspeed_plugin.deepspeed_config['train_micro_batch_size_per_gpu']`." + in str(cm.exception) + ) + + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + assert accelerator.deepspeed_config["zero_allow_untested_optimizer"] + assert accelerator.deepspeed_config["train_batch_size"], 16 + assert type(model) is DeepSpeedEngine + assert type(optimizer) is DeepSpeedOptimizerWrapper + assert type(lr_scheduler) is AcceleratedScheduler + assert type(accelerator.deepspeed_engine_wrapped) is DeepSpeedEngineWrapper + + elif optim_type == DS_OPTIMIZER and scheduler_type == DS_SCHEDULER: + # Test DeepSpeed optimizer + DeepSpeed scheduler + deepspeed_plugin = DeepSpeedPlugin(hf_ds_config=self.ds_config_file[ZERO2]) + with patch_environment(**self.dist_env): + accelerator = Accelerator(deepspeed_plugin=deepspeed_plugin, mixed_precision="fp16") + train_set = RegressionDataset(length=80) + eval_set = RegressionDataset(length=20) + train_dataloader = DataLoader(train_set, batch_size=10, shuffle=True) + eval_dataloader = DataLoader(eval_set, batch_size=5, shuffle=False) + model = AutoModel.from_pretrained(GPT2_TINY) + optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5) + lr_scheduler = get_scheduler( + name="linear", + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=1000, + ) + dummy_optimizer = DummyOptim(params=model.parameters()) + dummy_lr_scheduler = DummyScheduler(dummy_optimizer) + kwargs["train_batch_size"] = ( + kwargs["train_micro_batch_size_per_gpu"] + * deepspeed_plugin.deepspeed_config["gradient_accumulation_steps"] + * accelerator.num_processes + ) + accelerator.state.deepspeed_plugin.deepspeed_config_process(**kwargs) + with self.assertRaises(ValueError) as cm: + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, dummy_lr_scheduler + ) + assert "You cannot specify an optimizer in the config file and in the code at the same time" in str( + cm.exception + ) + + with self.assertRaises(ValueError) as cm: + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, dummy_optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + assert "You cannot specify a scheduler in the config file and in the code at the same time" in str( + cm.exception + ) + + with self.assertRaises(ValueError) as cm: + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, dummy_optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + assert "You cannot specify a scheduler in the config file and in the code at the same time" in str( + cm.exception + ) + + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, dummy_optimizer, train_dataloader, eval_dataloader, dummy_lr_scheduler + ) + assert type(model) is DeepSpeedEngine + assert type(optimizer) is DeepSpeedOptimizerWrapper + assert type(lr_scheduler) is DeepSpeedSchedulerWrapper + assert type(accelerator.deepspeed_engine_wrapped) is DeepSpeedEngineWrapper + + elif optim_type == CUSTOM_OPTIMIZER and scheduler_type == DS_SCHEDULER: + # Test custom optimizer + DeepSpeed scheduler + deepspeed_plugin = DeepSpeedPlugin(hf_ds_config=self.ds_config_file[ZERO2]) + with patch_environment(**self.dist_env): + accelerator = Accelerator(deepspeed_plugin=deepspeed_plugin, mixed_precision="fp16") + train_set = RegressionDataset(length=80) + eval_set = RegressionDataset(length=20) + train_dataloader = DataLoader(train_set, batch_size=10, shuffle=True) + eval_dataloader = DataLoader(eval_set, batch_size=5, shuffle=False) + model = AutoModel.from_pretrained(GPT2_TINY) + optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5) + lr_scheduler = get_scheduler( + name="linear", + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=1000, + ) + dummy_optimizer = DummyOptim(params=model.parameters()) + dummy_lr_scheduler = DummyScheduler(dummy_optimizer) + kwargs["train_batch_size"] = ( + kwargs["train_micro_batch_size_per_gpu"] + * deepspeed_plugin.deepspeed_config["gradient_accumulation_steps"] + * accelerator.num_processes + ) + accelerator.state.deepspeed_plugin.deepspeed_config_process(**kwargs) + del accelerator.state.deepspeed_plugin.deepspeed_config["optimizer"] + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, dummy_lr_scheduler + ) + assert type(model) is DeepSpeedEngine + assert type(optimizer) is DeepSpeedOptimizerWrapper + assert type(lr_scheduler) is DeepSpeedSchedulerWrapper + assert type(accelerator.deepspeed_engine_wrapped) is DeepSpeedEngineWrapper + elif optim_type == DS_OPTIMIZER and scheduler_type is CUSTOM_SCHEDULER: + # Test deepspeed optimizer + custom scheduler + deepspeed_plugin = DeepSpeedPlugin(hf_ds_config=self.ds_config_file[ZERO2]) + with patch_environment(**self.dist_env): + accelerator = Accelerator(deepspeed_plugin=deepspeed_plugin, mixed_precision="fp16") + train_set = RegressionDataset(length=80) + eval_set = RegressionDataset(length=20) + train_dataloader = DataLoader(train_set, batch_size=10, shuffle=True) + eval_dataloader = DataLoader(eval_set, batch_size=5, shuffle=False) + model = AutoModel.from_pretrained(GPT2_TINY) + optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5) + lr_scheduler = get_scheduler( + name="linear", + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=1000, + ) + dummy_optimizer = DummyOptim(params=model.parameters()) + dummy_lr_scheduler = DummyScheduler(dummy_optimizer) + kwargs["train_batch_size"] = ( + kwargs["train_micro_batch_size_per_gpu"] + * deepspeed_plugin.deepspeed_config["gradient_accumulation_steps"] + * accelerator.num_processes + ) + accelerator.state.deepspeed_plugin.deepspeed_config_process(**kwargs) + del accelerator.state.deepspeed_plugin.deepspeed_config["scheduler"] + with self.assertRaises(ValueError) as cm: + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, dummy_optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + assert ( + "You can only specify `accelerate.utils.DummyScheduler` in the code when using `accelerate.utils.DummyOptim`." + in str(cm.exception) + ) + + # passing `DummyScheduler` without `lr_scheduler_callable` should fail + with self.assertRaises(ValueError) as cm: + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, dummy_optimizer, train_dataloader, eval_dataloader, dummy_lr_scheduler + ) + assert ( + "Either specify a scheduler in the config file or " + "pass in the `lr_scheduler_callable` parameter when using `accelerate.utils.DummyScheduler`." + in str(cm.exception) + ) + + # passing `lr_scheduler_callable` to DummyScheduler should enable DS Optim + Custom Scheduler + def _lr_scheduler_callable(optimizer): + return get_scheduler( + name="linear", + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=1000, + ) + + dummy_lr_scheduler = DummyScheduler(dummy_optimizer, lr_scheduler_callable=_lr_scheduler_callable) + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, dummy_optimizer, train_dataloader, eval_dataloader, dummy_lr_scheduler + ) + + def test_dataloader_with_batch_sampler(self): + deepspeed_plugin = DeepSpeedPlugin( + gradient_accumulation_steps=1, + gradient_clipping=1.0, + zero_stage=2, + offload_optimizer_device="cpu", + offload_param_device="cpu", + zero3_save_16bit_model=False, + zero3_init_flag=False, + ) + with patch_environment(**self.dist_env): + accelerator = Accelerator(mixed_precision="fp16", deepspeed_plugin=deepspeed_plugin) + + train_set = RegressionDataset(length=80) + eval_set = RegressionDataset(length=20) + train_dataloader = DataLoader( + train_set, batch_sampler=BatchSampler(RandomSampler(train_set), batch_size=10, drop_last=False) + ) + eval_dataloader = DataLoader( + eval_set, batch_sampler=BatchSampler(SequentialSampler(eval_set), batch_size=10, drop_last=False) + ) + model = AutoModel.from_pretrained(GPT2_TINY) + optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5) + lr_scheduler = get_scheduler( + name="linear", + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=1000, + ) + + with self.assertRaises(ValueError) as cm: + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + assert ( + "At least one of the dataloaders passed to `accelerate.prepare()` has `None` as batch size. " + "Please set an integer value in `train_micro_batch_size_per_gpu` in the deepspeed config file " + "or assign integer value to `AcceleratorState().deepspeed_plugin.deepspeed_config['train_micro_batch_size_per_gpu']`." + in str(cm.exception) + ) + + @require_fp16 + def test_save_checkpoints(self): + deepspeed_plugin = DeepSpeedPlugin( + hf_ds_config=self.ds_config_file[ZERO3], + zero3_init_flag=True, + ) + del deepspeed_plugin.deepspeed_config["bf16"] + kwargs = { + "optimizer.params.lr": 5e-5, + "optimizer.params.weight_decay": 0.0, + "scheduler.params.warmup_min_lr": 0.0, + "scheduler.params.warmup_max_lr": 5e-5, + "scheduler.params.warmup_num_steps": 0, + "train_micro_batch_size_per_gpu": 16, + "gradient_clipping": 1.0, + "train_batch_size": 16, + "zero_optimization.reduce_bucket_size": 5e5, + "zero_optimization.stage3_prefetch_bucket_size": 5e5, + "zero_optimization.stage3_param_persistence_threshold": 5e5, + "zero_optimization.stage3_gather_16bit_weights_on_model_save": False, + } + + with patch_environment(**self.dist_env): + accelerator = Accelerator(deepspeed_plugin=deepspeed_plugin, mixed_precision="fp16") + kwargs["train_batch_size"] = ( + kwargs["train_micro_batch_size_per_gpu"] + * deepspeed_plugin.deepspeed_config["gradient_accumulation_steps"] + * accelerator.num_processes + ) + accelerator.state.deepspeed_plugin.deepspeed_config_process(**kwargs) + + train_set = RegressionDataset(length=80) + eval_set = RegressionDataset(length=20) + train_dataloader = DataLoader(train_set, batch_size=16, shuffle=True) + eval_dataloader = DataLoader(eval_set, batch_size=32, shuffle=False) + model = AutoModelForCausalLM.from_pretrained("gpt2") + dummy_optimizer = DummyOptim(params=model.parameters()) + dummy_lr_scheduler = DummyScheduler(dummy_optimizer) + + model, _, train_dataloader, eval_dataloader, _ = accelerator.prepare( + model, dummy_optimizer, train_dataloader, eval_dataloader, dummy_lr_scheduler + ) + with self.assertRaises(ValueError) as cm: + accelerator.get_state_dict(model) + msg = ( + "Cannot get 16bit model weights because `stage3_gather_16bit_weights_on_model_save` in DeepSpeed config is False. " + "To save the model weights in 16bit, set `stage3_gather_16bit_weights_on_model_save` to True in DeepSpeed config file or " + "set `zero3_save_16bit_model` to True when using `accelerate config`. " + "To save the full checkpoint, run `model.save_checkpoint(save_dir)` and use `zero_to_fp32.py` to recover weights." + ) + assert msg in str(cm.exception) + + def test_autofill_dsconfig(self): + deepspeed_plugin = DeepSpeedPlugin( + hf_ds_config=self.ds_config_file[ZERO3], + zero3_init_flag=True, + ) + del deepspeed_plugin.deepspeed_config["bf16"] + del deepspeed_plugin.deepspeed_config["fp16"] + + with patch_environment(**self.dist_env): + accelerator = Accelerator(deepspeed_plugin=deepspeed_plugin) + train_set = RegressionDataset(length=80) + eval_set = RegressionDataset(length=20) + train_dataloader = DataLoader(train_set, batch_size=16, shuffle=True) + eval_dataloader = DataLoader(eval_set, batch_size=32, shuffle=False) + model = AutoModelForCausalLM.from_pretrained("gpt2") + dummy_optimizer = DummyOptim(params=model.parameters(), lr=5e-5, weight_decay=1e-4) + dummy_lr_scheduler = DummyScheduler(dummy_optimizer, warmup_num_steps=10, total_num_steps=1000) + hidden_size = model.config.hidden_size + model, _, train_dataloader, eval_dataloader, _ = accelerator.prepare( + model, dummy_optimizer, train_dataloader, eval_dataloader, dummy_lr_scheduler + ) + config = accelerator.deepspeed_config + assert config["train_micro_batch_size_per_gpu"] == 16 + assert config["train_batch_size"] == 16 + + assert config["optimizer"]["params"]["lr"] == 5e-05 + assert config["optimizer"]["params"]["weight_decay"] == 1e-4 + + assert config["scheduler"]["params"]["warmup_min_lr"] == 0.0 + assert config["scheduler"]["params"]["warmup_max_lr"] == 5e-05 + assert config["scheduler"]["params"]["warmup_num_steps"] == 10 + + assert config["gradient_clipping"] == 1.0 + assert config["zero_optimization"]["reduce_bucket_size"] == (hidden_size * hidden_size) + assert config["zero_optimization"]["stage3_prefetch_bucket_size"] == int((0.9 * hidden_size) * hidden_size) + assert config["zero_optimization"]["stage3_param_persistence_threshold"] == (10 * hidden_size) + assert not config["zero_optimization"]["stage3_gather_16bit_weights_on_model_save"] + + @parameterized.expand(model_types, name_func=parameterized_custom_name_func) + @require_fp16 + def test_autofill_comm_buffers_dsconfig(self, model_type): + deepspeed_plugin = DeepSpeedPlugin( + hf_ds_config=self.ds_config_file[ZERO3], + zero3_init_flag=True, + ) + del deepspeed_plugin.deepspeed_config["bf16"] + del deepspeed_plugin.deepspeed_config["fp16"] + del deepspeed_plugin.deepspeed_config["optimizer"] + del deepspeed_plugin.deepspeed_config["scheduler"] + with patch_environment(**self.dist_env): + accelerator = Accelerator(mixed_precision="fp16", deepspeed_plugin=deepspeed_plugin) + train_set = RegressionDataset(length=80) + eval_set = RegressionDataset(length=20) + train_dataloader = DataLoader(train_set, batch_size=16, shuffle=True) + eval_dataloader = DataLoader(eval_set, batch_size=32, shuffle=False) + model = RegressionModel() + if model_type == CONFIG_WITH_NO_HIDDEN_SIZE: + model.config = DummyConfig() + elif model_type == CONFIG_WITH_HIDDEN_SIZE: + model.config = AutoConfig.from_pretrained(GPT2_TINY) + hidden_size = model.config.hidden_size + elif model_type == CONFIG_WITH_HIDDEN_SIZES: + model.config = AutoConfig.from_pretrained(MOBILEVIT) + hidden_size = max(model.config.hidden_sizes) + optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5) + lr_scheduler = get_scheduler( + name="linear", + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=1000, + ) + + if model_type == NO_CONFIG: + with self.assertRaises(ValueError) as cm: + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + msg = "Can't find `model.config` entry" + assert msg in str(cm.exception) + elif model_type == CONFIG_WITH_NO_HIDDEN_SIZE: + with self.assertRaises(ValueError) as cm: + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + msg = "Can find neither `model.config.hidden_size` nor `model.config.hidden_sizes`" + assert msg in str(cm.exception) + else: + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + zero_opt = accelerator.deepspeed_config["zero_optimization"] + assert zero_opt["reduce_bucket_size"] == (hidden_size * hidden_size) + assert zero_opt["stage3_prefetch_bucket_size"] == int((0.9 * hidden_size) * hidden_size) + assert zero_opt["stage3_param_persistence_threshold"] == (10 * hidden_size) + + @parameterized.expand(dtypes, name_func=parameterized_custom_name_func) + def test_autofill_dsconfig_from_ds_plugin(self, dtype): + ds_config = self.ds_config_dict["zero3"] + if dtype == BF16: + del ds_config["fp16"] + else: + del ds_config["bf16"] + ds_config[dtype]["enabled"] = "auto" + ds_config["zero_optimization"]["stage"] = "auto" + ds_config["zero_optimization"]["stage3_gather_16bit_weights_on_model_save"] = "auto" + ds_config["zero_optimization"]["offload_optimizer"]["device"] = "auto" + ds_config["zero_optimization"]["offload_param"]["device"] = "auto" + ds_config["gradient_accumulation_steps"] = "auto" + ds_config["gradient_clipping"] = "auto" + + deepspeed_plugin = DeepSpeedPlugin( + hf_ds_config=ds_config, + zero3_init_flag=True, + gradient_accumulation_steps=2, + gradient_clipping=1.0, + zero_stage=2, + offload_optimizer_device="cpu", + offload_param_device="cpu", + zero3_save_16bit_model=True, + ) + + with patch_environment(**self.dist_env): + accelerator = Accelerator(deepspeed_plugin=deepspeed_plugin, mixed_precision=dtype) + config = accelerator.state.deepspeed_plugin.deepspeed_config + assert config["gradient_clipping"] == 1.0 + assert config["gradient_accumulation_steps"] == 2 + assert config["zero_optimization"]["stage"] == 2 + assert config["zero_optimization"]["offload_optimizer"]["device"] == "cpu" + assert config["zero_optimization"]["offload_param"]["device"] == "cpu" + assert config["zero_optimization"]["stage3_gather_16bit_weights_on_model_save"] + assert config[dtype]["enabled"] + + AcceleratorState._reset_state(True) + diff_dtype = "bf16" if dtype == "fp16" else "fp16" + with patch_environment(**self.dist_env): + with self.assertRaises(ValueError) as cm: + accelerator = Accelerator(deepspeed_plugin=deepspeed_plugin, mixed_precision=diff_dtype) + assert ( + f"`--mixed_precision` arg cannot be set to `{diff_dtype}` when `{dtype}` is set in the DeepSpeed config file." + in str(cm.exception) + ) + + # base case of passing in `gradient_accumulation_steps` to `DeepSpeedPlugin` + AcceleratorState._reset_state(True) + deepspeed_plugin = DeepSpeedPlugin(zero_stage=2, gradient_accumulation_steps=4) + with patch_environment(**self.dist_env): + accelerator = Accelerator(deepspeed_plugin=deepspeed_plugin, mixed_precision=dtype) + deepspeed_plugin = accelerator.state.deepspeed_plugin + assert deepspeed_plugin.deepspeed_config["gradient_accumulation_steps"] == 4 + + # filling the `auto` gradient_accumulation_steps via Accelerator's value + AcceleratorState._reset_state(True) + deepspeed_plugin = DeepSpeedPlugin( + hf_ds_config=ds_config, + zero3_init_flag=True, + gradient_clipping=1.0, + zero_stage=2, + offload_optimizer_device="cpu", + offload_param_device="cpu", + zero3_save_16bit_model=True, + ) + with patch_environment(**self.dist_env): + accelerator = Accelerator( + deepspeed_plugin=deepspeed_plugin, mixed_precision=dtype, gradient_accumulation_steps=8 + ) + train_set = RegressionDataset(length=80) + eval_set = RegressionDataset(length=20) + train_dataloader = DataLoader(train_set, batch_size=16, shuffle=True) + eval_dataloader = DataLoader(eval_set, batch_size=32, shuffle=False) + model = AutoModelForCausalLM.from_pretrained("gpt2") + dummy_optimizer = DummyOptim(params=model.parameters(), lr=5e-5, weight_decay=1e-4) + dummy_lr_scheduler = DummyScheduler(dummy_optimizer, warmup_num_steps=10, total_num_steps=1000) + model, _, train_dataloader, eval_dataloader, _ = accelerator.prepare( + model, dummy_optimizer, train_dataloader, eval_dataloader, dummy_lr_scheduler + ) + deepspeed_plugin = accelerator.state.deepspeed_plugin + assert deepspeed_plugin.deepspeed_config["gradient_accumulation_steps"] == 8 + + def test_ds_config_assertions(self): + ambiguous_env = self.dist_env.copy() + ambiguous_env["ACCELERATE_CONFIG_DS_FIELDS"] = ( + "gradient_accumulation_steps,gradient_clipping,zero_stage,offload_optimizer_device,offload_param_device,zero3_save_16bit_model,mixed_precision" + ) + + with patch_environment(**ambiguous_env): + with self.assertRaises(ValueError) as cm: + deepspeed_plugin = DeepSpeedPlugin( + hf_ds_config=self.ds_config_file[ZERO3], + zero3_init_flag=True, + gradient_accumulation_steps=1, + gradient_clipping=1.0, + zero_stage=ZERO2, + offload_optimizer_device="cpu", + offload_param_device="cpu", + zero3_save_16bit_model=True, + ) + _ = Accelerator(deepspeed_plugin=deepspeed_plugin, mixed_precision=FP16) + assert ( + "If you are using an accelerate config file, remove others config variables mentioned in the above specified list." + in str(cm.exception) + ) + + def test_ds_zero3_no_init_autofill(self): + ds_config = { + "bf16": {"enabled": True}, + "zero_optimization": { + "stage": 3, + "allgather_partitions": True, + "allgather_bucket_size": 5e8, + "overlap_comm": True, + "reduce_scatter": True, + "reduce_bucket_size": "auto", + "contiguous_gradients": True, + "stage3_gather_16bit_weights_on_model_save": False, + "offload_optimizer": {"device": "none"}, + "offload_param": {"device": "none"}, + }, + "gradient_clipping": 1.0, + "gradient_accumulation_steps": 1, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "steps_per_print": 2000000, + } + deepspeed_plugin = DeepSpeedPlugin( + hf_ds_config=ds_config, + zero3_init_flag=False, + ) + with patch_environment(**self.dist_env): + _ = Accelerator(deepspeed_plugin=deepspeed_plugin) + _ = AutoModelForCausalLM.from_pretrained("gpt2") + + @parameterized.expand(stages, name_func=parameterized_custom_name_func) + def test_ds_config(self, stage): + deepspeed_plugin = DeepSpeedPlugin( + hf_ds_config=self.ds_config_file[stage], + zero3_init_flag=True, + ) + assert deepspeed_plugin.zero_stage == int(stage.replace("zero", "")) + + @require_fp16 + def test_prepare_deepspeed_prepare_moe(self): + if compare_versions("transformers", "<", "4.40") and compare_versions("deepspeed", "<", "0.14"): + return + deepspeed_plugin = DeepSpeedPlugin( + zero3_init_flag=True, + gradient_accumulation_steps=1, + gradient_clipping=1.0, + zero_stage=3, + offload_optimizer_device="none", + offload_param_device="none", + zero3_save_16bit_model=True, + transformer_moe_cls_names="Qwen2MoeSparseMoeBlock", + ) + with patch_environment(**self.dist_env): + accelerator = Accelerator(mixed_precision="fp16", deepspeed_plugin=deepspeed_plugin) + accelerator.state.deepspeed_plugin.deepspeed_config["train_micro_batch_size_per_gpu"] = 1 + model = AutoModelForCausalLM.from_pretrained(QWEN_MOE) + model = accelerator.prepare(model) + from transformers.models.qwen2_moe.modeling_qwen2_moe import Qwen2MoeSparseMoeBlock + + for module in model.modules(): + if isinstance(module, Qwen2MoeSparseMoeBlock): + assert hasattr(module, "_z3_leaf") and module._z3_leaf + + @run_first + @require_fp16 + def test_basic_run(self): + test_file_path = path_in_accelerate_package("test_utils", "scripts", "external_deps", "test_performance.py") + with tempfile.TemporaryDirectory() as dirpath: + cmd = [ + "accelerate", + "launch", + "--num_processes=1", + "--num_machines=1", + "--machine_rank=0", + "--mixed_precision=fp16", + "--use_deepspeed", + "--gradient_accumulation_steps=1", + "--zero_stage=2", + "--offload_optimizer_device=none", + "--offload_param_device=none", + test_file_path, + "--model_name_or_path=distilbert-base-uncased", + "--num_epochs=1", + f"--output_dir={dirpath}", + ] + with patch_environment(omp_num_threads=1): + execute_subprocess_async(cmd) + + +@slow +@run_first +@require_deepspeed +@require_multi_device +class DeepSpeedIntegrationTest(TempDirTestCase): + test_scripts_folder = path_in_accelerate_package("test_utils", "scripts", "external_deps") + + def setUp(self): + super().setUp() + self._test_file_path = inspect.getfile(self.__class__) + path = Path(self._test_file_path).resolve() + self.test_file_dir_str = str(path.parents[0]) + + self.ds_config_file = dict( + zero2=f"{self.test_file_dir_str}/ds_config_zero2.json", + zero3=f"{self.test_file_dir_str}/ds_config_zero3.json", + ) + + self.stages = [1, 2, 3] + self.zero3_offload_config = False + self.performance_lower_bound = 0.82 + self.peak_memory_usage_upper_bound = { + "multi_gpu_fp16": 3200, + "deepspeed_stage_1_fp16": 1600, + "deepspeed_stage_2_fp16": 2500, + "deepspeed_stage_3_zero_init_fp16": 2800, + # Disabling below test as it overwhelms the RAM memory usage + # on CI self-hosted runner leading to tests getting killed. + # "deepspeed_stage_3_cpu_offload_fp16": 1900, + } + self.n_train = 160 + self.n_val = 160 + + @require_fp16 + def test_performance(self): + self.test_file_path = self.test_scripts_folder / "test_performance.py" + cmd = [ + "accelerate", + "launch", + "--num_processes=2", + "--num_machines=1", + "--machine_rank=0", + "--mixed_precision=fp16", + "--use_deepspeed", + "--gradient_accumulation_steps=1", + "--gradient_clipping=1", + "--zero3_init_flag=True", + "--zero3_save_16bit_model=True", + ] + for stage in self.stages: + if stage == 1: + continue + cmd_stage = cmd.copy() + cmd_stage.extend([f"--zero_stage={stage}"]) + cmd_stage.extend(["--offload_optimizer_device=none", "--offload_param_device=none"]) + if self.zero3_offload_config: + with open(self.ds_config_file[ZERO3], encoding="utf-8") as f: + ds_config = json.load(f) + del ds_config["bf16"] + del ds_config["optimizer"]["params"]["torch_adam"] + del ds_config["optimizer"]["params"]["adam_w_mode"] + ds_config["fp16"]["enabled"] = True + ds_config_path = os.path.join(self.tmpdir, "ds_config.json") + with open(ds_config_path, "w") as out_file: + json.dump(ds_config, out_file) + + cmd_stage.extend([f"--deepspeed_config_file={ds_config_path}"]) + + cmd_stage.extend( + [ + self.test_file_path, + f"--output_dir={self.tmpdir}", + f"--performance_lower_bound={self.performance_lower_bound}", + ] + ) + with patch_environment(omp_num_threads=1): + execute_subprocess_async(cmd_stage) + + @require_fp16 + def test_checkpointing(self): + self.test_file_path = self.test_scripts_folder / "test_checkpointing.py" + cmd = [ + "accelerate", + "launch", + "--num_processes=2", + "--num_machines=1", + "--machine_rank=0", + "--mixed_precision=fp16", + "--use_deepspeed", + "--gradient_accumulation_steps=1", + "--gradient_clipping=1", + "--zero3_init_flag=True", + "--zero3_save_16bit_model=True", + ] + for stage in self.stages: + if stage == 1: + continue + cmd_stage = cmd.copy() + cmd_stage.extend([f"--zero_stage={stage}"]) + cmd_stage.extend(["--offload_optimizer_device=none", "--offload_param_device=none"]) + if self.zero3_offload_config: + with open(self.ds_config_file[ZERO3], encoding="utf-8") as f: + ds_config = json.load(f) + del ds_config["bf16"] + del ds_config["optimizer"]["params"]["torch_adam"] + del ds_config["optimizer"]["params"]["adam_w_mode"] + ds_config["fp16"]["enabled"] = True + ds_config_path = os.path.join(self.tmpdir, "ds_config.json") + with open(ds_config_path, "w") as out_file: + json.dump(ds_config, out_file) + + cmd_stage.extend([f"--deepspeed_config_file={ds_config_path}"]) + + cmd_stage.extend( + [ + self.test_file_path, + f"--output_dir={self.tmpdir}", + "--partial_train_epoch=1", + ] + ) + with patch_environment(omp_num_threads=1): + execute_subprocess_async(cmd_stage) + + cmd_stage = cmd_stage[:-1] + resume_from_checkpoint = os.path.join(self.tmpdir, "epoch_0") + cmd_stage.extend( + [ + f"--resume_from_checkpoint={resume_from_checkpoint}", + ] + ) + with patch_environment(omp_num_threads=1): + execute_subprocess_async(cmd_stage) + + @require_fp16 + def test_peak_memory_usage(self): + if compare_versions("deepspeed", ">", "0.12.6"): + self.skipTest( + "The test fails when deepspeed>0.12.6. This is something that needs to be fixed on deepspeed library" + ) + + self.test_file_path = self.test_scripts_folder / "test_peak_memory_usage.py" + cmd = [ + "accelerate", + "launch", + "--num_processes=2", + "--num_machines=1", + "--machine_rank=0", + ] + for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items(): + cmd_stage = cmd.copy() + if "fp16" in spec: + cmd_stage.extend(["--mixed_precision=fp16"]) + + if "multi_gpu" in spec: + continue + else: + cmd_stage.extend( + [ + "--use_deepspeed", + "--gradient_accumulation_steps=1", + "--gradient_clipping=1", + "--zero3_init_flag=True", + "--zero3_save_16bit_model=True", + ] + ) + for i in range(3): + if f"stage_{i + 1}" in spec: + cmd_stage.extend([f"--zero_stage={i + 1}"]) + break + cmd_stage.extend( + [ + "--offload_optimizer_device=none", + "--offload_param_device=none", + "--offload_optimizer_nvme_path=none", + "--offload_param_nvme_path=none", + ] + ) + if "cpu_offload" in spec: + with open(self.ds_config_file[ZERO3], encoding="utf-8") as f: + ds_config = json.load(f) + del ds_config["bf16"] + del ds_config["fp16"] + del ds_config["optimizer"]["params"]["torch_adam"] + del ds_config["optimizer"]["params"]["adam_w_mode"] + ds_config_path = os.path.join(self.tmpdir, "ds_config.json") + with open(ds_config_path, "w") as out_file: + json.dump(ds_config, out_file) + + cmd_stage.extend([f"--deepspeed_config_file={ds_config_path}"]) + + cmd_stage.extend( + [ + self.test_file_path, + f"--output_dir={self.tmpdir}", + f"--peak_memory_upper_bound={peak_mem_upper_bound}", + f"--n_train={self.n_train}", + f"--n_val={self.n_val}", + ] + ) + with patch_environment(omp_num_threads=1): + execute_subprocess_async(cmd_stage) + + def test_lr_scheduler(self): + self.test_file_path = self.test_scripts_folder / "test_performance.py" + cmd = [ + "accelerate", + "launch", + "--num_processes=2", + "--num_machines=1", + "--machine_rank=0", + "--mixed_precision=no", + "--use_deepspeed", + "--gradient_accumulation_steps=1", + "--gradient_clipping=1", + "--zero3_init_flag=True", + "--zero3_save_16bit_model=True", + "--zero_stage=3", + "--offload_optimizer_device=none", + "--offload_param_device=none", + self.test_file_path, + f"--output_dir={self.tmpdir}", + f"--performance_lower_bound={self.performance_lower_bound}", + ] + with patch_environment(omp_num_threads=1): + execute_subprocess_async(cmd) + + @require_huggingface_suite + def test_zero3_integration(self): + self.test_file_path = self.test_scripts_folder / "test_zero3_integration.py" + cmd = ["accelerate", "launch", "--num_processes=2", "--num_machines=1", self.test_file_path] + with patch_environment(omp_num_threads=1): + execute_subprocess_async(cmd) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/test_deepspeed_gradient_accumulation.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/test_deepspeed_gradient_accumulation.py new file mode 100644 index 0000000000000000000000000000000000000000..7522badb65bf846716c2a98c185792c133a4b945 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/test_deepspeed_gradient_accumulation.py @@ -0,0 +1,240 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import json +from pathlib import Path + +import torch +from torch.utils.data import DataLoader +from transformers import AutoModel +from transformers.trainer_utils import set_seed + +from accelerate.accelerator import Accelerator +from accelerate.test_utils.testing import AccelerateTestCase, require_deepspeed +from accelerate.test_utils.training import RegressionDataset +from accelerate.utils import patch_environment +from accelerate.utils.dataclasses import DeepSpeedPlugin + + +set_seed(42) + +GPT2_TINY = "hf-internal-testing/tiny-random-gpt2" +ZERO2 = "zero2" +ZERO3 = "zero3" +FP16 = "fp16" + + +@require_deepspeed +class DeepSpeedGradientAccumulationTest(AccelerateTestCase): + def setUp(self): + super().setUp() + + self._test_file_path = inspect.getfile(self.__class__) + path = Path(self._test_file_path).resolve() + self.test_file_dir_str = str(path.parents[0]) + + self.ds_config_file = dict( + zero2=f"{self.test_file_dir_str}/ds_config_zero2.json", + zero3=f"{self.test_file_dir_str}/ds_config_zero3.json", + ) + + # Load config files + with open(self.ds_config_file[ZERO2], encoding="utf-8") as f: + config_zero2 = json.load(f) + with open(self.ds_config_file[ZERO3], encoding="utf-8") as f: + config_zero3 = json.load(f) + config_zero3["zero_optimization"]["stage3_gather_16bit_weights_on_model_save"] = False + + self.ds_config_dict = dict(zero2=config_zero2, zero3=config_zero3) + + self.dist_env = dict( + ACCELERATE_USE_DEEPSPEED="true", + MASTER_ADDR="localhost", + MASTER_PORT="10999", + RANK="0", + LOCAL_RANK="0", + WORLD_SIZE="1", + ) + + def test_gradient_accumulation_boundary_integration(self): + """Test that gradient accumulation boundaries are automatically handled by DeepSpeed integration.""" + gradient_accumulation_steps = 4 + + deepspeed_plugin = DeepSpeedPlugin( + gradient_accumulation_steps=gradient_accumulation_steps, + gradient_clipping=1.0, + zero_stage=2, + offload_optimizer_device="cpu", + offload_param_device="cpu", + zero3_save_16bit_model=False, + zero3_init_flag=False, + ) + + with patch_environment(**self.dist_env): + accelerator = Accelerator(mixed_precision="fp16", deepspeed_plugin=deepspeed_plugin) + + # Setup simple training components + train_set = RegressionDataset(length=80) + train_dataloader = DataLoader(train_set, batch_size=16, shuffle=True) + model = AutoModel.from_pretrained(GPT2_TINY) + optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5) + + model, optimizer, train_dataloader = accelerator.prepare(model, optimizer, train_dataloader) + + model.train() + + # Test gradient accumulation with accumulate context manager + batch_data = next(iter(train_dataloader)) + # Create proper input format for GPT2 model (RegressionDataset returns {"x": scalar, "y": scalar}) + # We need to create dummy input_ids for the GPT2 model + batch_size = batch_data["x"].shape[0] if isinstance(batch_data["x"], torch.Tensor) else 1 + + # Create dummy input_ids for GPT2 model and move to same device as model + device = next(model.parameters()).device + input_ids = torch.randint(0, 1000, (batch_size, 10), device=device) # batch_size x sequence_length + inputs = {"input_ids": input_ids} + + # Track sync_gradients values to verify correct gradient accumulation behavior + sync_values = [] + + # Simulate gradient accumulation steps + for micro_step in range(gradient_accumulation_steps): + with accelerator.accumulate(model): + sync_values.append(accelerator.sync_gradients) + outputs = model(**inputs) + # Use the last hidden state and create a simple loss + prediction = outputs.last_hidden_state.mean() + loss = prediction.sum() # Simple scalar loss + + # This should automatically handle gradient accumulation boundaries + accelerator.backward(loss) + + if accelerator.sync_gradients: + optimizer.step() + optimizer.zero_grad() + + # Verify gradient accumulation pattern was correct + # Should be False for first 3 steps, True for the last step + expected_sync = [False, False, False, True] + self.assertEqual(sync_values, expected_sync) + + # Reset step counter for accelerator + accelerator.step = 0 + + def test_clip_grad_norm_returns_deepspeed_grad_norm(self): + """Test that clip_grad_norm_ works with DeepSpeed and returns gradient norm when available.""" + deepspeed_plugin = DeepSpeedPlugin( + gradient_accumulation_steps=1, + gradient_clipping=1.0, + zero_stage=2, + offload_optimizer_device="cpu", + offload_param_device="cpu", + zero3_save_16bit_model=False, + zero3_init_flag=False, + ) + + with patch_environment(**self.dist_env): + accelerator = Accelerator(mixed_precision="fp16", deepspeed_plugin=deepspeed_plugin) + + # Setup simple model + model = AutoModel.from_pretrained(GPT2_TINY) + optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5) + + # Create a simple dataloader for prepare to work + train_set = RegressionDataset(length=16) + train_dataloader = DataLoader(train_set, batch_size=16, shuffle=True) + + model, optimizer, train_dataloader = accelerator.prepare(model, optimizer, train_dataloader) + + # Perform a forward and backward pass to generate gradients + batch_data = next(iter(train_dataloader)) + batch_size = len(batch_data["x"]) if isinstance(batch_data["x"], torch.Tensor) else 1 + + # Create dummy input_ids for GPT2 model and move to same device as model + device = next(model.parameters()).device + input_ids = torch.randint(0, 1000, (batch_size, 10), device=device) + inputs = {"input_ids": input_ids} + + # Forward pass + outputs = model(**inputs) + prediction = outputs.last_hidden_state.mean() + loss = prediction.sum() + + # Backward pass to generate gradients + accelerator.backward(loss) + + # Test that gradient clipping works and returns a value + grad_norm = accelerator.clip_grad_norm_(model.parameters(), max_norm=1.0) + # After backward pass, we should get a valid gradient norm (either from DeepSpeed or fallback) + self.assertIsInstance(grad_norm, (int, float, type(None))) + if grad_norm is not None: + self.assertGreaterEqual(grad_norm, 0.0) + + def test_accelerator_backward_passes_sync_gradients(self): + """Test that Accelerator.backward() passes sync_gradients to DeepSpeed wrapper.""" + deepspeed_plugin = DeepSpeedPlugin( + gradient_accumulation_steps=2, + gradient_clipping=1.0, + zero_stage=2, + offload_optimizer_device="cpu", + offload_param_device="cpu", + zero3_save_16bit_model=False, + zero3_init_flag=False, + ) + + with patch_environment(**self.dist_env): + accelerator = Accelerator(mixed_precision="fp16", deepspeed_plugin=deepspeed_plugin) + + # Setup simple model and data + model = AutoModel.from_pretrained(GPT2_TINY) + optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5) + train_set = RegressionDataset(length=16) + train_dataloader = DataLoader(train_set, batch_size=8, shuffle=True) + + model, optimizer, train_dataloader = accelerator.prepare(model, optimizer, train_dataloader) + + # Track sync_gradients values during backward calls + sync_values = [] + + # Test two gradient accumulation steps + batch_data = next(iter(train_dataloader)) + # Create proper input format for GPT2 model + batch_size = len(batch_data["x"]) if isinstance(batch_data["x"], torch.Tensor) else 1 + + # Create dummy input_ids for GPT2 model and move to same device as model + device = next(model.parameters()).device + input_ids = torch.randint(0, 1000, (batch_size, 10), device=device) + inputs = {"input_ids": input_ids} + + # First step - should have sync_gradients=False + with accelerator.accumulate(model): + sync_values.append(accelerator.sync_gradients) + outputs = model(**inputs) + prediction = outputs.last_hidden_state.mean() + loss = prediction # Simple loss + accelerator.backward(loss) + + # Second step - should have sync_gradients=True + with accelerator.accumulate(model): + sync_values.append(accelerator.sync_gradients) + outputs = model(**inputs) + prediction = outputs.last_hidden_state.mean() + loss = prediction # Simple loss + accelerator.backward(loss) + + # Verify sync_gradients pattern was correct + self.assertEqual(len(sync_values), 2) + self.assertFalse(sync_values[0]) # First step: not syncing + self.assertTrue(sync_values[1]) # Second step: syncing diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/test_deepspeed_multiple_model.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/test_deepspeed_multiple_model.py new file mode 100644 index 0000000000000000000000000000000000000000..bfa7a3e00c60109d97075bc109e326d42c35bf5c --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/deepspeed/test_deepspeed_multiple_model.py @@ -0,0 +1,183 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import json +from functools import partial +from pathlib import Path + +import torch +from transformers import AutoModelForCausalLM + +from accelerate import Accelerator, DeepSpeedPlugin +from accelerate.commands.launch import launch_command, launch_command_parser +from accelerate.test_utils.testing import ( + AccelerateTestCase, + path_in_accelerate_package, + require_deepspeed, + require_huggingface_suite, + require_multi_device, + require_non_cpu, + run_first, + slow, +) +from accelerate.test_utils.training import RegressionDataset +from accelerate.utils import patch_environment +from accelerate.utils.deepspeed import DummyOptim, DummyScheduler, get_active_deepspeed_plugin + + +GPT2_TINY = "hf-internal-testing/tiny-random-gpt2" + + +@require_deepspeed +@require_non_cpu +class DeepSpeedConfigIntegration(AccelerateTestCase): + parser = launch_command_parser() + test_scripts_folder = path_in_accelerate_package("test_utils", "scripts", "external_deps") + + def setUp(self): + super().setUp() + + self.dist_env = dict( + ACCELERATE_USE_DEEPSPEED="true", + MASTER_ADDR="localhost", + MASTER_PORT="10999", + RANK="0", + LOCAL_RANK="0", + WORLD_SIZE="1", + ) + + self._test_file_path = inspect.getfile(self.__class__) + path = Path(self._test_file_path).resolve() + self.test_file_dir_str = str(path.parents[0]) + + self.ds_config_file = dict( + zero2=f"{self.test_file_dir_str}/ds_config_zero2.json", + zero3_inference=f"{self.test_file_dir_str}/ds_config_zero3_model_only.json", + zero3_training=f"{self.test_file_dir_str}/ds_config_zero3.json", + ) + + with open(self.ds_config_file["zero2"], encoding="utf-8") as f: + self.config_zero2 = json.load(f) + with open(self.ds_config_file["zero3_training"], encoding="utf-8") as f: + self.config_zero3 = json.load(f) + with open(self.ds_config_file["zero3_inference"], encoding="utf-8") as f: + self.config_zero3_inference = json.load(f) + + self.model_init = partial(AutoModelForCausalLM.from_pretrained, GPT2_TINY) + + def get_ds_plugins(self, zero3_inference=False): + ds_zero2 = DeepSpeedPlugin( + hf_ds_config=self.config_zero2, + ) + ds_zero3 = DeepSpeedPlugin( + hf_ds_config=self.config_zero3 if not zero3_inference else self.config_zero3_inference, + ) + return {"zero2": ds_zero2, "zero3": ds_zero3} + + def test_select_plugin(self): + ds_plugins = self.get_ds_plugins() + ds_zero2, ds_zero3 = ds_plugins.values() + accelerator = Accelerator( + deepspeed_plugin=ds_plugins, + ) + # Accelerator's constructor should automatically enable the first plugin + assert ds_zero2.selected + assert not ds_zero3.selected + assert get_active_deepspeed_plugin(accelerator.state) == ds_zero2 + assert accelerator.deepspeed_plugin == ds_zero2 + assert accelerator.state.get_deepspeed_plugin("zero2") == ds_zero2 + accelerator.state.select_deepspeed_plugin("zero3") + assert not ds_zero2.selected + assert ds_zero3.selected + assert get_active_deepspeed_plugin(accelerator.state) == ds_zero3 + assert accelerator.deepspeed_plugin == ds_zero3 + assert accelerator.state.get_deepspeed_plugin("zero3") == ds_zero3 + accelerator.state.select_deepspeed_plugin("zero2") + assert not ds_zero3.selected + assert ds_zero2.selected + assert get_active_deepspeed_plugin(accelerator.state) == ds_zero2 + assert accelerator.deepspeed_plugin == ds_zero2 + assert accelerator.state.get_deepspeed_plugin("zero2") == ds_zero2 + + @require_huggingface_suite + def test_config_reference_update(self): + # Make sure that the transformers weakref is updating when we update the config + ds_plugins = self.get_ds_plugins(zero3_inference=True) + zero2, zero3 = ds_plugins.values() + accelerator = Accelerator(deepspeed_plugin=ds_plugins) + from transformers.integrations.deepspeed import deepspeed_config + + # Note that these have `auto` values being set so we need to adjust + assert accelerator.deepspeed_plugin is zero2 + zero2.deepspeed_config["train_micro_batch_size_per_gpu"] = 1 + zero2.deepspeed_config.pop("train_batch_size") + assert deepspeed_config() == accelerator.deepspeed_plugin.hf_ds_config.config + + accelerator.state.select_deepspeed_plugin("zero3") + assert accelerator.deepspeed_plugin is zero3 + assert deepspeed_config() == accelerator.deepspeed_plugin.hf_ds_config.config + + def test_enable_disable_manually_set(self): + ds_plugins = self.get_ds_plugins() + ds_zero2, _ = ds_plugins.values() + with self.assertRaises(ValueError): + ds_zero2.select() + accelerator = Accelerator(deepspeed_plugin=ds_plugins) + accelerator.state.select_deepspeed_plugin("zero2") + with self.assertRaises(NotImplementedError): + ds_zero2.selected = False + assert ds_zero2.selected + + def test_multiple_accelerators(self): + ds_plugins = self.get_ds_plugins() + ds_zero2, ds_zero3 = ds_plugins.values() + _ = Accelerator( + deepspeed_plugin=ds_zero2, + ) + with self.assertRaises(NotImplementedError): + _ = Accelerator(deepspeed_plugin=ds_zero3) + + def test_prepare_multiple_models_zero3_inference(self): + with patch_environment(**self.dist_env): + ds_plugins = self.get_ds_plugins(zero3_inference=True) + accelerator = Accelerator(deepspeed_plugin=ds_plugins) + # Using Zero-2 first + model1 = self.model_init() + optimizer = DummyOptim(model1.parameters()) + scheduler = DummyScheduler(optimizer) + + dataset = RegressionDataset() + dataloader = torch.utils.data.DataLoader(dataset, batch_size=1) + model1, optimizer, scheduler, dataloader = accelerator.prepare(model1, optimizer, scheduler, dataloader) + accelerator.state.select_deepspeed_plugin("zero3") + model2 = self.model_init() + with self.assertLogs(level="WARNING") as captured: + model2 = accelerator.prepare(model2) + self.assertIn( + "A wrapped DeepSpeed engine reference is currently tied for this `Accelerator()` instance.", + captured.output[0], + ) + + assert accelerator.deepspeed_engine_wrapped.engine is model1 + + @run_first + @require_huggingface_suite + @require_multi_device + @slow + def test_train_multiple_models(self): + self.test_file_path = self.test_scripts_folder / "test_ds_multiple_model.py" + args = ["--num_processes=2", "--num_machines=1", str(self.test_file_path)] + args = self.parser.parse_args(args) + launch_command(args) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/fsdp/test_fsdp.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/fsdp/test_fsdp.py new file mode 100644 index 0000000000000000000000000000000000000000..26c8972963272af07d6aafc9f24237775dc43043 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/fsdp/test_fsdp.py @@ -0,0 +1,617 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import functools +import os +from contextlib import nullcontext + +import torch +from transformers import AutoModel + +from accelerate.accelerator import Accelerator +from accelerate.state import AcceleratorState +from accelerate.test_utils.testing import ( + AccelerateTestCase, + TempDirTestCase, + execute_subprocess_async, + get_launch_command, + path_in_accelerate_package, + require_fp16, + require_fsdp2, + require_multi_device, + require_non_cpu, + require_non_torch_xla, + run_first, + slow, +) +from accelerate.utils import is_bf16_available, is_fp16_available, is_hpu_available, patch_environment, set_seed +from accelerate.utils.constants import ( + FSDP2_STATE_DICT_TYPE, + FSDP_AUTO_WRAP_POLICY, + FSDP_BACKWARD_PREFETCH, + FSDP_SHARDING_STRATEGY, + FSDP_STATE_DICT_TYPE, +) +from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin +from accelerate.utils.fsdp_utils import disable_fsdp_ram_efficient_loading, enable_fsdp_ram_efficient_loading + + +set_seed(42) + + +BERT_BASE_CASED = "bert-base-cased" +LLAMA_TESTING = "hf-internal-testing/tiny-random-LlamaForCausalLM" +FP16 = "fp16" +BF16 = "bf16" + +dtypes = [] +if is_fp16_available(): + dtypes.append(FP16) +if is_bf16_available(): + dtypes.append(BF16) + + +@require_non_cpu +@require_non_torch_xla +class FSDPPluginIntegration(AccelerateTestCase): + def setUp(self): + super().setUp() + + self.dist_env = dict( + MASTER_ADDR="localhost", + MASTER_PORT="10999", + RANK="0", + LOCAL_RANK="0", + WORLD_SIZE="1", + ) + + self.fsdp1_env = dict(ACCELERATE_USE_FSDP="true", **self.dist_env) + self.fsdp2_env = dict(ACCELERATE_USE_FSDP="true", **self.dist_env, FSDP_VERSION="2") + + self.fsdp_envs = { + 1: self.fsdp1_env, + 2: self.fsdp2_env, + } + + self.current_fsdp_version = 1 + + def test_sharding_strategy(self): + from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy + + SHARDING_STRATEGIES = { + 1: FSDP_SHARDING_STRATEGY, + 2: [True, False], + } + + SHARDING_STRATEGY_NAMES = { + 1: "FSDP_SHARDING_STRATEGY", + 2: "FSDP_RESHARD_AFTER_FORWARD", + } + + # check that giving enums works fine + # Only supported in FSDP1 + for i, strategy in enumerate(FSDP_SHARDING_STRATEGY): + env = self.fsdp_envs[1].copy() + env["FSDP_SHARDING_STRATEGY"] = f"{i + 1}" + with patch_environment(**env): + fsdp_plugin = FullyShardedDataParallelPlugin() + assert fsdp_plugin.sharding_strategy == ShardingStrategy(i + 1) + fsdp_plugin = FullyShardedDataParallelPlugin(sharding_strategy=ShardingStrategy(i + 1)) + assert fsdp_plugin.sharding_strategy == ShardingStrategy(i + 1) + + # check that giving names works fine, also needed for FSDP2 + fsdp_version = self.current_fsdp_version + for i, strategy in enumerate(SHARDING_STRATEGIES[fsdp_version]): + env = self.fsdp_envs[fsdp_version].copy() + env[SHARDING_STRATEGY_NAMES[fsdp_version]] = strategy + with patch_environment(**env): + fsdp_plugin = FullyShardedDataParallelPlugin() + if fsdp_version == 1: + assert fsdp_plugin.sharding_strategy == ShardingStrategy(i + 1) + assert fsdp_plugin.reshard_after_forward is None + else: + assert fsdp_plugin.reshard_after_forward == strategy + assert fsdp_plugin.sharding_strategy is None + + env = self.fsdp_envs[fsdp_version].copy() + with patch_environment(**env): + if fsdp_version == 1: + fsdp_plugin = FullyShardedDataParallelPlugin(sharding_strategy=ShardingStrategy(i + 1)) + assert fsdp_plugin.sharding_strategy == ShardingStrategy(i + 1) + assert fsdp_plugin.reshard_after_forward is None + else: + fsdp_plugin = FullyShardedDataParallelPlugin(reshard_after_forward=strategy) + assert fsdp_plugin.reshard_after_forward == strategy + assert fsdp_plugin.sharding_strategy is None + + def test_backward_prefetch(self): + from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch + + _warning_message_fsdp2 = "backward_prefetch is not supported in FSDP2. Setting backward prefetch to None." + + fsdp_version = self.current_fsdp_version + for i, prefetch_policy in enumerate(FSDP_BACKWARD_PREFETCH): + # FSDP2 warns about backward prefetch and sets to None + ctx = ( + self.assertLogs("accelerate.utils.dataclasses", level="WARNING") + if fsdp_version == 2 and prefetch_policy != "NO_PREFETCH" + else nullcontext() + ) + expected_value = ( + None if (prefetch_policy == "NO_PREFETCH" or fsdp_version == 2) else BackwardPrefetch(i + 1) + ) + env = self.fsdp_envs[fsdp_version].copy() + env["FSDP_BACKWARD_PREFETCH"] = prefetch_policy + with patch_environment(**env), ctx as cm: + fsdp_plugin = FullyShardedDataParallelPlugin() + assert fsdp_plugin.backward_prefetch == expected_value, ( + f"Actual: {fsdp_plugin.backward_prefetch} != Expected: {expected_value}" + ) + if cm: + self.assertTrue(any(_warning_message_fsdp2 in out for out in cm.output)) + + # Check if torch enum works + env = self.fsdp_envs[fsdp_version].copy() + with patch_environment(**env), ctx as cm: + if prefetch_policy != "NO_PREFETCH": + fsdp_plugin = FullyShardedDataParallelPlugin(backward_prefetch=BackwardPrefetch(i + 1)) + assert fsdp_plugin.backward_prefetch == expected_value + if cm: + self.assertTrue(any(_warning_message_fsdp2 in out for out in cm.output)) + + # Check if name works + with patch_environment(**env), ctx as cm: + fsdp_plugin = FullyShardedDataParallelPlugin(backward_prefetch=prefetch_policy) + assert fsdp_plugin.backward_prefetch == expected_value + if cm: + self.assertTrue(any(_warning_message_fsdp2 in out for out in cm.output)) + + def test_state_dict_type(self): + from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType + + fsdp_version = self.current_fsdp_version + for i, state_dict_type in enumerate(FSDP_STATE_DICT_TYPE): + cm = ( + self.assertRaises(ValueError) + if (fsdp_version == 2 and state_dict_type not in FSDP2_STATE_DICT_TYPE) + else nullcontext() + ) + env = self.fsdp_envs[fsdp_version].copy() + env["FSDP_STATE_DICT_TYPE"] = state_dict_type + with patch_environment(**env), cm: + fsdp_plugin = FullyShardedDataParallelPlugin() + assert fsdp_plugin.state_dict_type == StateDictType(i + 1) + if state_dict_type == "FULL_STATE_DICT": + assert fsdp_plugin.state_dict_config.offload_to_cpu + assert fsdp_plugin.state_dict_config.rank0_only + + env = self.fsdp_envs[fsdp_version].copy() + with patch_environment(**env), cm: + fsdp_plugin = FullyShardedDataParallelPlugin(state_dict_type=StateDictType(i + 1)) + assert fsdp_plugin.state_dict_type == StateDictType(i + 1) + if state_dict_type == "FULL_STATE_DICT": + assert fsdp_plugin.state_dict_config.offload_to_cpu + assert fsdp_plugin.state_dict_config.rank0_only + + # We can also override the state_dict_type, + # typical case: user trains with sharded, but final save is with full + fsdp_plugin = FullyShardedDataParallelPlugin(state_dict_type="FULL_STATE_DICT") + fsdp_plugin.set_state_dict_type("SHARDED_STATE_DICT") + assert fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT + + def test_auto_wrap_policy(self): + fsdp_version = self.current_fsdp_version + for model_name in [LLAMA_TESTING, BERT_BASE_CASED]: + model = AutoModel.from_pretrained(model_name) + layer_to_wrap = "LlamaDecoderLayer" if model_name == LLAMA_TESTING else "BertLayer" + for policy in FSDP_AUTO_WRAP_POLICY: + env = self.fsdp_envs[fsdp_version].copy() + env["FSDP_AUTO_WRAP_POLICY"] = policy + transformer_cls_to_wrap = None + min_num_params = None + env.pop("FSDP_TRANSFORMER_CLS_TO_WRAP", None) + env.pop("FSDP_MIN_NUM_PARAMS", None) + if policy == "TRANSFORMER_BASED_WRAP": + env["FSDP_TRANSFORMER_CLS_TO_WRAP"] = layer_to_wrap + transformer_cls_to_wrap = layer_to_wrap + elif policy == "SIZE_BASED_WRAP": + env["FSDP_MIN_NUM_PARAMS"] = "2000" + min_num_params = 2000 + # First test via env + with patch_environment(**env): + fsdp_plugin = FullyShardedDataParallelPlugin() + fsdp_plugin.set_auto_wrap_policy(model) + if policy == "NO_WRAP": + assert fsdp_plugin.auto_wrap_policy is None + else: + assert isinstance(fsdp_plugin.auto_wrap_policy, functools.partial) + + # Then manually set the policy + env = self.fsdp_envs[fsdp_version].copy() + with patch_environment(**env): + fsdp_plugin = FullyShardedDataParallelPlugin( + auto_wrap_policy=policy, + transformer_cls_names_to_wrap=transformer_cls_to_wrap, + min_num_params=min_num_params, + ) + fsdp_plugin.set_auto_wrap_policy(model) + if policy == "NO_WRAP": + assert fsdp_plugin.auto_wrap_policy is None + else: + assert isinstance(fsdp_plugin.auto_wrap_policy, functools.partial) + + env = self.fsdp_envs[fsdp_version].copy() + env["FSDP_AUTO_WRAP_POLICY"] = "TRANSFORMER_BASED_WRAP" + env["FSDP_TRANSFORMER_CLS_TO_WRAP"] = "T5Layer" + with patch_environment(**env): + fsdp_plugin = FullyShardedDataParallelPlugin() + with self.assertRaises(Exception) as cm: + fsdp_plugin.set_auto_wrap_policy(model) + assert "Could not find the transformer layer class T5Layer in the model." in str(cm.exception) + + env = self.fsdp_envs[fsdp_version].copy() + with patch_environment(**env): + fsdp_plugin = FullyShardedDataParallelPlugin( + auto_wrap_policy="TRANSFORMER_BASED_WRAP", + transformer_cls_names_to_wrap="T5Layer", + ) + with self.assertRaises(Exception) as cm: + fsdp_plugin.set_auto_wrap_policy(model) + assert "Could not find the transformer layer class T5Layer in the model." in str(cm.exception) + + env = self.fsdp_envs[fsdp_version].copy() + env["FSDP_AUTO_WRAP_POLICY"] = "SIZE_BASED_WRAP" + env["FSDP_MIN_NUM_PARAMS"] = "0" + with patch_environment(**env): + fsdp_plugin = FullyShardedDataParallelPlugin() + fsdp_plugin.set_auto_wrap_policy(model) + assert fsdp_plugin.auto_wrap_policy is None + + env = self.fsdp_envs[fsdp_version].copy() + with patch_environment(**env): + fsdp_plugin = FullyShardedDataParallelPlugin( + auto_wrap_policy="SIZE_BASED_WRAP", + min_num_params=0, + ) + fsdp_plugin.set_auto_wrap_policy(model) + assert fsdp_plugin.auto_wrap_policy is None + + def test_mixed_precision(self): + fsdp_version = self.current_fsdp_version + if fsdp_version == 2: + from torch.amp.grad_scaler import GradScaler as Scaler + from torch.distributed.fsdp import MixedPrecisionPolicy as MP + else: + from torch.distributed.fsdp import MixedPrecision as MP + from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler as Scaler + + for mp_dtype in dtypes: + env = self.fsdp_envs[fsdp_version].copy() + env["ACCELERATE_MIXED_PRECISION"] = mp_dtype + extra_arg = "buffer_dtype" if fsdp_version == 1 else "output_dtype" + with patch_environment(**env): + accelerator = Accelerator() + if mp_dtype == "fp16": + dtype = torch.float16 + elif mp_dtype == "bf16": + dtype = torch.bfloat16 + mp_policy = MP(param_dtype=dtype, reduce_dtype=dtype, **{extra_arg: dtype}) + assert accelerator.state.fsdp_plugin.mixed_precision_policy == mp_policy + if mp_dtype == FP16: + assert isinstance(accelerator.scaler, Scaler) + elif mp_dtype == BF16: + assert accelerator.scaler is None + AcceleratorState._reset_state(True) + + env = self.fsdp_envs[fsdp_version].copy() + with patch_environment(**env): + plugin = FullyShardedDataParallelPlugin( + mixed_precision_policy={"param_dtype": dtype, "reduce_dtype": dtype, **{extra_arg: dtype}} + ) + assert plugin.mixed_precision_policy == mp_policy + with patch_environment(**env): + accelerator = Accelerator(fsdp_plugin=plugin) + assert accelerator.state.fsdp_plugin.mixed_precision_policy == mp_policy + AcceleratorState._reset_state(True) + + def test_mixed_precision_buffer_autocast_override(self): + from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision + from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler + + if self.current_fsdp_version == 2: + return + + # We're not testing this for FSDP2 because FSDP2 doesn't support `buffer_dtype` rather only `output_dtype` + # TODO(s1ro1): what should we do if `buffer_autocast` is set to True in FSDP2? + + for mp_dtype in dtypes: + if mp_dtype == "fp16": + dtype = torch.float16 + elif mp_dtype == "bf16": + dtype = torch.bfloat16 + mp_policy = MixedPrecision(param_dtype=dtype, reduce_dtype=dtype, buffer_dtype=torch.float32) + + env = self.fsdp_envs[1].copy() + env["ACCELERATE_MIXED_PRECISION"] = mp_dtype + with patch_environment(**env): + accelerator = Accelerator() + accelerator.state.fsdp_plugin.set_mixed_precision(dtype, buffer_autocast=True, override=True) + assert accelerator.state.fsdp_plugin.mixed_precision_policy == mp_policy + if mp_dtype == FP16: + assert isinstance(accelerator.scaler, ShardedGradScaler) + elif mp_dtype == BF16: + assert accelerator.scaler is None + AcceleratorState._reset_state(True) + + def test_cpu_offload(self): + fsdp_version = self.current_fsdp_version + if fsdp_version == 2: + from torch.distributed.fsdp import CPUOffloadPolicy, OffloadPolicy + else: + from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload + + for flag in [True, False]: + env = self.fsdp_envs[fsdp_version].copy() + env["FSDP_OFFLOAD_PARAMS"] = str(flag).lower() + + # FSDP2 has a different class for not offloading, therefore we need to check for both cases + if fsdp_version == 2 and flag: + expected_value = CPUOffloadPolicy() + elif fsdp_version == 2 and not flag: + expected_value = OffloadPolicy() + else: + expected_value = CPUOffload(offload_params=flag) + with patch_environment(**env): + fsdp_plugin = FullyShardedDataParallelPlugin() + assert fsdp_plugin.cpu_offload == expected_value + + env = self.fsdp_envs[fsdp_version].copy() + with patch_environment(**env): + fsdp_plugin = FullyShardedDataParallelPlugin(cpu_offload=flag) + assert fsdp_plugin.cpu_offload == expected_value + + def test_cpu_ram_efficient_loading(self): + fsdp_version = self.current_fsdp_version + env = self.fsdp_envs[fsdp_version].copy() + enable_fsdp_ram_efficient_loading() + with patch_environment(**env): + fsdp_plugin = FullyShardedDataParallelPlugin() + assert fsdp_plugin.cpu_ram_efficient_loading is True + assert os.environ.get("FSDP_CPU_RAM_EFFICIENT_LOADING") == "True" + + disable_fsdp_ram_efficient_loading() + env = self.fsdp_envs[fsdp_version].copy() + with patch_environment(**env): + fsdp_plugin = FullyShardedDataParallelPlugin() + assert fsdp_plugin.cpu_ram_efficient_loading is False + assert os.environ.get("FSDP_CPU_RAM_EFFICIENT_LOADING") == "False" + + +@require_fsdp2 +@require_non_cpu +@require_non_torch_xla +class FSDP2PluginIntegration(FSDPPluginIntegration): + def setUp(self): + super().setUp() + self.current_fsdp_version = 2 + + +@run_first +# Skip this test when TorchXLA is available because accelerate.launch does not support TorchXLA FSDP. +@require_non_torch_xla +@require_multi_device +@slow +class FSDPIntegrationTest(TempDirTestCase): + test_scripts_folder = path_in_accelerate_package("test_utils", "scripts", "external_deps") + + def setUp(self): + super().setUp() + self.performance_lower_bound = 0.70 if is_hpu_available() else 0.82 + self.fsdp1_performance_configs = [ + "fsdp_shard_grad_op_transformer_based_wrap", + "fsdp_full_shard_transformer_based_wrap", + ] + # FSDP2 doesn't currently support other than full_shard/no_shard equivalents + self.fsdp2_performance_configs = ["fsdp_full_shard_transformer_based_wrap"] + self.performance_configs = { + 1: self.fsdp1_performance_configs, + 2: self.fsdp2_performance_configs, + } + + self.fsdp1_peak_memory_usage_upper_bound = { + "multi_gpu_fp16": 3200, + "fsdp_shard_grad_op_transformer_based_wrap_fp16": 2000, + "fsdp_full_shard_transformer_based_wrap_fp16": 1900, + # Disabling below test as it overwhelms the RAM memory usage + # on CI self-hosted runner leading to tests getting killed. + # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500, # fp16 was leading to indefinite hang + } + self.fsdp2_peak_memory_usage_upper_bound = { + "multi_gpu_fp16": 3200, + "fsdp_full_shard_transformer_based_wrap_fp16": 1900, + } + self.peak_memory_usage_upper_bound = { + 1: self.fsdp1_peak_memory_usage_upper_bound, + 2: self.fsdp2_peak_memory_usage_upper_bound, + } + self.n_train = 160 + self.n_val = 160 + + self.current_fsdp_version = 1 + + @require_fp16 + def test_performance(self): + self.test_file_path = self.test_scripts_folder / "test_performance.py" + fsdp_version = self.current_fsdp_version + cmd = get_launch_command( + num_processes=2, num_machines=1, machine_rank=0, use_fsdp=True, fsdp_version=self.current_fsdp_version + ) + for config in self.performance_configs[fsdp_version]: + cmd_config = cmd.copy() + cmd_config.append(f"--fsdp_version={fsdp_version}") + for i, strategy in enumerate(FSDP_SHARDING_STRATEGY): + if fsdp_version == 2 and strategy != "FULL_SHARD": + continue + if strategy.lower() in config: + if fsdp_version == 1: + cmd_config.append(f"--fsdp_sharding_strategy={strategy}") + else: + # FSDP2 uses `reshard_after_forward` instead of `sharding_strategy` and is true unless we test `NO_SHARD` (we don't) + cmd_config.append("--fsdp_reshard_after_forward=true") + break + + if "fp32" in config: + cmd_config.append("--mixed_precision=no") + else: + cmd_config.append("--mixed_precision=fp16") + + if "cpu_offload" in config: + cmd_config.append("--fsdp_offload_params=True") + + for policy in FSDP_AUTO_WRAP_POLICY: + if policy.lower() in config: + cmd_config.append(f"--fsdp_auto_wrap_policy={policy}") + break + + if policy == "TRANSFORMER_BASED_WRAP": + cmd_config.append("--fsdp_transformer_layer_cls_to_wrap=BertLayer") + elif policy == "SIZE_BASED_WRAP": + cmd_config.append("--fsdp_min_num_params=2000") + + cmd_config.extend( + [ + self.test_file_path, + f"--output_dir={self.tmpdir}", + f"--performance_lower_bound={self.performance_lower_bound}", + ] + ) + + with patch_environment(omp_num_threads=1): + execute_subprocess_async(cmd_config) + + @require_fp16 + def test_checkpointing(self): + self.test_file_path = self.test_scripts_folder / "test_checkpointing.py" + fsdp_version = self.current_fsdp_version + cmd = get_launch_command( + num_processes=2, + num_machines=1, + machine_rank=0, + use_fsdp=True, + mixed_precision="fp16", + fsdp_transformer_layer_cls_to_wrap="BertLayer", + fsdp_version=fsdp_version, + ) + + for i, strategy in enumerate(FSDP_SHARDING_STRATEGY): + fsdp_state_dict_types = FSDP_STATE_DICT_TYPE if fsdp_version == 1 else FSDP2_STATE_DICT_TYPE + cmd_config = cmd.copy() + if fsdp_version == 1: + cmd_config.append(f"--fsdp_sharding_strategy={strategy}") + else: + cmd_config.append("--fsdp_reshard_after_forward=true") + if strategy != "FULL_SHARD": + continue + state_dict_config_index = len(cmd_config) + for state_dict_type in fsdp_state_dict_types: + # Todo: Currently failing for `LOCAL_STATE_DICT` with error + # Unexpected key(s) in state_dict: "_fsdp_wrapped_module._flat_param". + if state_dict_type == "LOCAL_STATE_DICT": + continue + + cmd_config = cmd_config[:state_dict_config_index] + cmd_config.append(f"--fsdp_state_dict_type={state_dict_type}") + cmd_config.extend( + [ + self.test_file_path, + f"--output_dir={self.tmpdir}", + "--partial_train_epoch=1", + ] + ) + with patch_environment(omp_num_threads=1): + execute_subprocess_async(cmd_config) + + cmd_config = cmd_config[:-1] + resume_from_checkpoint = os.path.join(self.tmpdir, "epoch_0") + cmd_config.extend( + [ + f"--resume_from_checkpoint={resume_from_checkpoint}", + ] + ) + with patch_environment(omp_num_threads=1): + execute_subprocess_async(cmd_config) + + @require_fp16 + def test_peak_memory_usage(self): + self.test_file_path = self.test_scripts_folder / "test_peak_memory_usage.py" + fsdp_version = self.current_fsdp_version + cmd = get_launch_command(num_processes=2, num_machines=1, machine_rank=0, fsdp_version=fsdp_version) + for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound[fsdp_version].items(): + cmd_config = cmd.copy() + if "fp16" in spec: + cmd_config.extend(["--mixed_precision=fp16"]) + else: + cmd_config.extend(["--mixed_precision=no"]) + + if "multi_gpu" in spec: + continue + else: + cmd_config.extend(["--use_fsdp"]) + for i, strategy in enumerate(FSDP_SHARDING_STRATEGY): + if fsdp_version == 2 and strategy != "FULL_SHARD": + continue + if strategy.lower() in spec: + if fsdp_version == 1: + cmd_config.append(f"--fsdp_sharding_strategy={strategy}") + else: + cmd_config.append("--fsdp_reshard_after_forward=true") + break + + if "cpu_offload" in spec: + cmd_config.append("--fsdp_offload_params=True") + + for policy in FSDP_AUTO_WRAP_POLICY: + if policy.lower() in spec: + cmd_config.append(f"--fsdp_auto_wrap_policy={policy}") + break + + if policy == "TRANSFORMER_BASED_WRAP": + cmd_config.append("--fsdp_transformer_layer_cls_to_wrap=BertLayer") + elif policy == "SIZE_BASED_WRAP": + cmd_config.append("--fsdp_min_num_params=2000") + + cmd_config.extend( + [ + self.test_file_path, + f"--output_dir={self.tmpdir}", + f"--peak_memory_upper_bound={peak_mem_upper_bound}", + f"--n_train={self.n_train}", + f"--n_val={self.n_val}", + ] + ) + with patch_environment(omp_num_threads=1): + execute_subprocess_async(cmd_config) + + +@require_fsdp2 +@run_first +# Skip this test when TorchXLA is available because accelerate.launch does not support TorchXLA FSDP. +@require_non_torch_xla +@require_multi_device +@slow +class FSDP2IntegrationTest(FSDPIntegrationTest): + def setUp(self): + super().setUp() + self.current_fsdp_version = 2 diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/tasksmith_behavior.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/tasksmith_behavior.py new file mode 100644 index 0000000000000000000000000000000000000000..0d98ba81267178717c7860b7381676994533f8d6 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/tasksmith_behavior.py @@ -0,0 +1,225 @@ +import pytest +from unittest.mock import Mock, patch + + +def _mesh_factory(device_type, mesh_shape, mesh_dim_names): + """Minimal mock matching the real init_device_mesh signature.""" + mesh = Mock() + mesh.device_type = device_type + mesh.shape = mesh_shape + mesh.mesh_dim_names = mesh_dim_names + mesh.flattened_dims = [] + + def mock_getitem(key): + submesh = Mock() + submesh._flatten = Mock() + return submesh + + mesh.__getitem__ = Mock(side_effect=mock_getitem) + mesh.size = Mock(return_value=1) + return mesh + + +class TestGetDeviceMesh: + def test_initial_device_mesh_is_none(self): + from accelerate.parallelism_config import ParallelismConfig + + config = ParallelismConfig(dp_replicate_size=8) + assert config.device_mesh is None + + def test_get_device_mesh_builds_on_first_call(self): + from accelerate.parallelism_config import ParallelismConfig + + config = ParallelismConfig(dp_replicate_size=8) + with patch("accelerate.parallelism_config.init_device_mesh", side_effect=_mesh_factory): + mesh = config.get_device_mesh("cpu") + assert mesh is not None + assert config.device_mesh is mesh + + def test_get_device_mesh_caches_result(self): + from accelerate.parallelism_config import ParallelismConfig + + call_count = [0] + + def counting_factory(device_type, mesh_shape, mesh_dim_names): + call_count[0] += 1 + return _mesh_factory(device_type, mesh_shape, mesh_dim_names) + + with patch("accelerate.parallelism_config.init_device_mesh", side_effect=counting_factory): + config = ParallelismConfig(dp_replicate_size=8) + assert config.device_mesh is None + assert call_count[0] == 0 + mesh1 = config.get_device_mesh("cpu") + assert mesh1 is not None + assert config.device_mesh is mesh1 + assert call_count[0] == 1 + mesh2 = config.get_device_mesh("cpu") + assert call_count[0] == 1 + assert mesh1 is mesh2 + assert call_count[0] == 1 + + other = ParallelismConfig(dp_replicate_size=8) + assert other.device_mesh is None + with patch("accelerate.parallelism_config.init_device_mesh", side_effect=counting_factory): + other_mesh = other.get_device_mesh("cpu") + assert other_mesh is not mesh1 + assert other.device_mesh is other_mesh + assert config.device_mesh is mesh1 + assert call_count[0] == 2 + + def test_get_device_mesh_raises_on_type_mismatch(self): + from accelerate.parallelism_config import ParallelismConfig + + config = ParallelismConfig(dp_replicate_size=8) + with patch("accelerate.parallelism_config.init_device_mesh", side_effect=_mesh_factory): + config.get_device_mesh("cpu") + with pytest.raises(ValueError) as exc_info: + config.get_device_mesh("cuda") + message = str(exc_info.value) + assert "cpu" in message + assert "cuda" in message + + def test_build_device_mesh_returns_none_for_empty_config(self): + from accelerate.parallelism_config import ParallelismConfig + + config = ParallelismConfig() # all sizes default to 1 + with patch("accelerate.parallelism_config.init_device_mesh", side_effect=_mesh_factory): + result = config.build_device_mesh("cpu") + assert result is None + + +class TestParallelismIntegration: + @pytest.fixture(autouse=True) + def isolated_state(self): + import os + from accelerate.state import AcceleratorState, GradientState + + with patch.dict(os.environ, {}, clear=True): + AcceleratorState._reset_state(reset_partial_state=True) + GradientState._reset_state() + try: + yield + finally: + AcceleratorState._reset_state(reset_partial_state=True) + GradientState._reset_state() + + @staticmethod + def assert_partial_has_no_parallelism(partial): + assert not hasattr(partial, "parallelism_config") + assert not hasattr(partial, "device_mesh") + + def test_configuration_selection_and_ownership(self): + import os + from accelerate import Accelerator, ParallelismConfig + from accelerate.state import AcceleratorState, PartialState + from accelerate.utils import TorchTensorParallelPlugin + + for mode in ("default", "disabled", "environment", "explicit", "legacy"): + AcceleratorState._reset_state(reset_partial_state=True) + environment = {} + if mode == "disabled": + environment["ACCELERATE_USE_PARALLELISM_CONFIG"] = "false" + elif mode == "environment": + environment["ACCELERATE_USE_PARALLELISM_CONFIG"] = "true" + with patch.dict(os.environ, environment, clear=True): + partial = PartialState(cpu=True) + self.assert_partial_has_no_parallelism(partial) + kwargs = {} + explicit = None + if mode == "explicit": + explicit = ParallelismConfig() + kwargs["parallelism_config"] = explicit + elif mode == "legacy": + # The legacy plugin is only a configuration carrier here; + # tp_size=1 needs neither transformers nor a process group. + plugin = Mock(spec=TorchTensorParallelPlugin) + plugin.tp_size = 1 + kwargs["torch_tp_plugin"] = plugin + + accelerator = Accelerator(cpu=True, **kwargs) + assert isinstance(accelerator.state, AcceleratorState) + if mode in ("default", "disabled"): + assert accelerator.parallelism_config is None + assert accelerator.state.parallelism_config is None + else: + config = accelerator.parallelism_config + assert isinstance(config, ParallelismConfig) + assert accelerator.state.parallelism_config is config + assert config.total_size == 1 + if explicit is not None: + assert config is explicit + if mode == "legacy": + assert config.tp_size == plugin.tp_size + assert accelerator.state.device_mesh is None + self.assert_partial_has_no_parallelism(partial) + self.assert_partial_has_no_parallelism(PartialState()) + + saved_config = accelerator.state.parallelism_config + PartialState._reset_state() + self.assert_partial_has_no_parallelism(PartialState(cpu=True)) + assert accelerator.state.parallelism_config is saved_config + assert accelerator.state.device_mesh is None + + def test_cached_mesh_survives_state_reconstruction(self, tmp_path): + import os + import subprocess + import sys + code = """ +import os, sys +from datetime import timedelta +from unittest.mock import patch +import torch +import torch.distributed as dist +from accelerate import Accelerator, ParallelismConfig +from accelerate.state import AcceleratorState, PartialState +rank = int(os.environ['RANK']) +torch.cuda.set_device(rank) +dist.init_process_group('nccl', init_method='file://' + sys.argv[1], + rank=rank, world_size=2, timeout=timedelta(seconds=60)) +try: + config = ParallelismConfig(dp_replicate_size=2) + with patch.object(config, 'build_device_mesh', wraps=config.build_device_mesh) as build: + mesh = config.get_device_mesh('cuda') + assert mesh.size() == 2 and build.call_count == 1 + build.reset_mock() + first = Accelerator(parallelism_config=config) + assert first.state.parallelism_config is config + assert first.state.device_mesh is mesh + assert not hasattr(PartialState(), 'parallelism_config') + assert not hasattr(PartialState(), 'device_mesh') + build.assert_not_called() + PartialState._reset_state() + partial = PartialState() + assert not hasattr(partial, 'parallelism_config') + assert not hasattr(partial, 'device_mesh') + assert first.state.parallelism_config is config + assert first.state.device_mesh is mesh + AcceleratorState._reset_state(reset_partial_state=True) + second = Accelerator(parallelism_config=config) + assert second.state.parallelism_config is config + assert second.state.device_mesh is mesh + assert config.device_mesh is mesh + assert not hasattr(PartialState(), 'parallelism_config') + assert not hasattr(PartialState(), 'device_mesh') + build.assert_not_called() +finally: + AcceleratorState._reset_state(reset_partial_state=True) + dist.destroy_process_group() +""" + processes = [] + try: + for rank in range(2): + env = dict(os.environ, RANK=str(rank), LOCAL_RANK=str(rank), + WORLD_SIZE='2', LOCAL_WORLD_SIZE='2', OMP_NUM_THREADS='1', + MASTER_ADDR='127.0.0.1', MASTER_PORT='29519', + NCCL_SOCKET_IFNAME='lo', GLOO_SOCKET_IFNAME='lo') + processes.append(subprocess.Popen([sys.executable, '-c', code, + str(tmp_path / 'rendezvous')], env=env, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)) + results = [(p.communicate(timeout=100)[0], p.returncode) for p in processes] + assert all(code == 0 for output, code in results), results + finally: + for p in processes: + if p.poll() is None: + p.kill() + p.communicate() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_accelerator.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_accelerator.py new file mode 100644 index 0000000000000000000000000000000000000000..98a2a765d02db3d5cb0762c77fa86bfa20020ad8 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_accelerator.py @@ -0,0 +1,861 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import itertools +import json +import os +import pickle +import tempfile +import time +from unittest.mock import patch + +import psutil +import torch +from parameterized import parameterized +from torch.utils.data import DataLoader, TensorDataset + +from accelerate import DistributedType, infer_auto_device_map, init_empty_weights, load_checkpoint_and_dispatch +from accelerate.accelerator import Accelerator +from accelerate.data_loader import DataLoaderDispatcher, DataLoaderShard, skip_first_batches +from accelerate.state import GradientState, PartialState +from accelerate.test_utils import ( + require_bnb, + require_cuda_or_xpu, + require_fp8, + require_fp16, + require_huggingface_suite, + require_multi_device, + require_non_cpu, + require_non_hpu, + require_transformer_engine, + slow, + torch_device, +) +from accelerate.test_utils.testing import ( + AccelerateTestCase, + require_cuda, + require_non_torch_xla, + require_torchdata_stateful_dataloader, +) +from accelerate.utils import FP8RecipeKwargs, is_torchdata_stateful_dataloader_available, patch_environment +from accelerate.utils.dataclasses import DataLoaderConfiguration +from accelerate.utils.modeling import get_state_dict_from_offload, load_checkpoint_in_model +from accelerate.utils.random import set_seed + + +if is_torchdata_stateful_dataloader_available(): + from torchdata.stateful_dataloader import StatefulDataLoader + + +class ModelWithTiedWeights(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear1 = torch.nn.Linear(2, 4) + self.linear2 = torch.nn.Linear(4, 2) + self.linear2.weight = self.linear1.weight + self.linear2.bias = self.linear1.bias + + def forward(self, x): + return self.linear2(self.linear1(x)) + + +def create_components(tied_weights=False): + model = ModelWithTiedWeights() if tied_weights else torch.nn.Linear(2, 4) + optimizer = torch.optim.AdamW(model.parameters(), lr=1.0) + scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=0.01, steps_per_epoch=2, epochs=1) + train_dl = DataLoader(TensorDataset(torch.tensor([1, 2, 3]))) + valid_dl = DataLoader(TensorDataset(torch.tensor([4, 5, 6]))) + return model, optimizer, scheduler, train_dl, valid_dl + + +class ModelForTest(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear1 = torch.nn.Linear(3, 4) + self.batchnorm = torch.nn.BatchNorm1d(4) + self.linear2 = torch.nn.Linear(4, 5) + + def forward(self, x): + return self.linear2(self.batchnorm(self.linear1(x))) + + +def create_dataloaders_for_test(batch_size=3, n_train_batches: int = 12, n_valid_batches: int = 2, num_workers=0): + "Generates a tuple of dummy DataLoaders to test with" + + def get_dataset(n_batches): + x = torch.randn(batch_size * n_batches, 3) + y = torch.randn(batch_size * n_batches, 5) + return TensorDataset(x, y) + + train_dataset = get_dataset(n_train_batches) + valid_dataset = get_dataset(n_valid_batches) + train_dataloader = DataLoader(train_dataset, batch_size=batch_size, num_workers=num_workers) + valid_dataloader = DataLoader(valid_dataset, batch_size=batch_size, num_workers=num_workers) + return (train_dataloader, valid_dataloader) + + +def get_signature(model): + return sum(param.abs().sum().item() for param in model.parameters()) + + +def load_random_weights(model): + if isinstance(model, torch.nn.Linear): + state = torch.nn.Linear(*tuple(model.weight.T.shape)).state_dict() + elif isinstance(model, ModelWithTiedWeights): + state = ModelWithTiedWeights().state_dict() + model.load_state_dict(state) + + +def parameterized_custom_name_func(func, param_num, param): + # customize the test name generator function as we want both params to appear in the sub-test + # name, as by default it shows only the first param + param_based_name = "use_safetensors" if param.args[0] is True else "use_pytorch" + if len(param.args) > 1: + param_based_name += "_tied_weights" if param.args[1] is True else "" + if len(param.args) > 2: + param_based_name += f"_num_workers_{param.args[2]}" + if len(param.args) > 3: + param_based_name += "_dispatch_batches" if param.args[3] is True else "_no_dispatch_batches" + return f"{func.__name__}_{param_based_name}" + + +class AcceleratorTester(AccelerateTestCase): + def test_partial_state_after_reset(self): + # Verifies that custom getattr errors will be thrown + # if the state is reset, but only if trying to + # get expected attributes + state = PartialState() + assert state.num_processes > 0 + + with self.assertRaises(AttributeError) as cm: + state.someotherthing + assert "'PartialState' object has no attribute" in str(cm.exception) + assert "This happens if `PartialState._reset_state()`" not in str(cm.exception) + + with self.assertRaises(AttributeError) as cm: + state._reset_state() + state.num_processes + assert "`PartialState` object has no attribute" in str(cm.exception) + assert "This happens if `PartialState._reset_state()`" in str(cm.exception) + + state.someotherthing = "MyValue" + assert state.someotherthing == "MyValue" + + def test_accelerator_state_after_reset(self): + # Verifies that custom getattr errors will be thrown + # if the state is reset, but only if trying to + # get expected attributes + accelerator = Accelerator() + assert accelerator.num_processes > 0 + + with self.assertRaises(AttributeError) as cm: + accelerator.state.someotherthing + assert "'AcceleratorState' object has no attribute" in str(cm.exception) + assert "This happens if `AcceleratorState._reset_state()`" not in str(cm.exception) + + with self.assertRaises(AttributeError) as cm: + accelerator.state._reset_state() + accelerator.num_processes + assert "`AcceleratorState` object has no attribute" in str(cm.exception) + assert "This happens if `AcceleratorState._reset_state()`" in str(cm.exception) + + accelerator.state.someotherthing = "MyValue" + assert accelerator.state.someotherthing == "MyValue" + + @require_non_cpu + def test_accelerator_can_be_reinstantiated(self): + _ = Accelerator() + assert PartialState._shared_state["_cpu"] is False + assert PartialState._shared_state["device"].type in ["cuda", "mps", "npu", "xpu", "xla", "hpu"] + with self.assertRaises(ValueError): + _ = Accelerator(cpu=True) + + @require_cuda + def test_setting_cpu_affinity(self): + with patch_environment(accelerate_cpu_affinity=1, accelerate_debug_mode=1): + with self.assertLogs("accelerate.utils.environment", level="INFO") as cm: + _ = Accelerator() + assert any("Assigning" in log for log in cm.output) + assert any("cpu cores to process" in log for log in cm.output) + + def test_mutable_states(self): + accelerator = Accelerator() + state = GradientState() + assert state.num_steps == 1 + accelerator.gradient_accumulation_steps = 4 + assert state.num_steps == 4 + + assert state.sync_gradients is True + accelerator.sync_gradients = False + assert state.sync_gradients is False + GradientState._reset_state() + + def test_prepared_objects_are_referenced(self): + accelerator = Accelerator() + model, optimizer, scheduler, train_dl, valid_dl = create_components() + + ( + prepared_model, + prepared_optimizer, + prepared_scheduler, + prepared_train_dl, + prepared_valid_dl, + ) = accelerator.prepare(model, optimizer, scheduler, train_dl, valid_dl) + + assert prepared_model in accelerator._models + assert prepared_optimizer in accelerator._optimizers + assert prepared_scheduler in accelerator._schedulers + assert prepared_train_dl in accelerator._dataloaders + assert prepared_valid_dl in accelerator._dataloaders + + @require_non_hpu # hpu does not support empty_cache + def test_free_memory_dereferences_prepared_components(self): + accelerator = Accelerator() + # Free up refs with empty_cache() and gc.collect() + accelerator.free_memory() + model, optimizer, scheduler, train_dl, valid_dl = create_components() + free_cpu_ram_before = psutil.virtual_memory().available // 1024 // 1024 + model, optimizer, scheduler, train_dl, valid_dl = accelerator.prepare( + model, optimizer, scheduler, train_dl, valid_dl + ) + + # Short sleep here makes this test more reliable + time.sleep(1e-3) + + model, optimizer, scheduler, train_dl, valid_dl = accelerator.free_memory( + model, optimizer, scheduler, train_dl, valid_dl + ) + + free_cpu_ram_after = psutil.virtual_memory().available // 1024 // 1024 + + assert len(accelerator._models) == 0 + assert len(accelerator._optimizers) == 0 + assert len(accelerator._schedulers) == 0 + assert len(accelerator._dataloaders) == 0 + + # The less-than comes *specifically* from CUDA CPU things/won't be present on CPU builds + assert free_cpu_ram_after <= free_cpu_ram_before + + @require_non_torch_xla + def test_env_var_device(self): + """Tests that setting the torch device with ACCELERATE_TORCH_DEVICE overrides default device.""" + PartialState._reset_state() + + # Mock torch.cuda.set_device to avoid an exception as the device doesn't exist + def noop(*args, **kwargs): + pass + + with patch("torch.cuda.set_device", noop), patch_environment(ACCELERATE_TORCH_DEVICE="cuda:64"): + accelerator = Accelerator() + assert str(accelerator.state.device) == "cuda:64" + + @parameterized.expand([(True, True), (True, False), (False, False)], name_func=parameterized_custom_name_func) + def test_save_load_model(self, use_safetensors, tied_weights): + accelerator = Accelerator() + model, optimizer, scheduler, train_dl, valid_dl = create_components(tied_weights) + accelerator.prepare(model, optimizer, scheduler, train_dl, valid_dl) + + model_signature = get_signature(model) + + with tempfile.TemporaryDirectory() as tmpdirname: + accelerator.save_state(tmpdirname, safe_serialization=use_safetensors) + + # make sure random weights don't match + load_random_weights(model) + assert abs(model_signature - get_signature(model)) > 1e-3 + + # make sure loaded weights match + accelerator.load_state(tmpdirname) + assert abs(model_signature - get_signature(model)) < 1e-3 + + @parameterized.expand([True, False], name_func=parameterized_custom_name_func) + def test_save_model(self, use_safetensors): + accelerator = Accelerator() + model = torch.nn.Linear(10, 10) + + model_signature = get_signature(model) + with tempfile.TemporaryDirectory() as tmpdirname: + accelerator.save_model(model, tmpdirname, safe_serialization=use_safetensors) + # make sure loaded weights match + load_checkpoint_in_model(model, tmpdirname) + assert abs(model_signature - get_signature(model)) < 1e-3 + + @parameterized.expand([True, False], name_func=parameterized_custom_name_func) + def test_save_sharded_model(self, use_safetensors): + accelerator = Accelerator() + inputs = torch.randn(3, 3) + model = ModelForTest() + expected = model(inputs) + + with tempfile.TemporaryDirectory() as tmpdirname: + # By setting it to 100, we will split the model int 3 shards + accelerator.save_model(model, tmpdirname, safe_serialization=use_safetensors, max_shard_size=100) + # make sure loaded weights match + load_checkpoint_in_model(model, tmpdirname) + output = model(inputs) + + assert torch.allclose(expected, output, atol=1e-5) + + @parameterized.expand([True, False], name_func=parameterized_custom_name_func) + def test_save_model_offload(self, use_safetensors): + accelerator = Accelerator() + + device_map = {"linear1": "cpu", "batchnorm": "disk", "linear2": "cpu"} + + inputs = torch.randn(3, 3) + model = ModelForTest() + expected = model(inputs) + with tempfile.TemporaryDirectory() as tmp_dir: + accelerator.save_model(model, tmp_dir, safe_serialization=use_safetensors) + # load and save offloaded model + load_checkpoint_and_dispatch(model, tmp_dir, device_map=device_map, offload_folder=tmp_dir) + accelerator.save_model(model, tmp_dir, safe_serialization=use_safetensors) + + # load weights that were saved from the offloaded model + load_checkpoint_and_dispatch(model, tmp_dir) + output = model(inputs) + assert torch.allclose(expected, output, atol=1e-5) + + @parameterized.expand([True, False], name_func=parameterized_custom_name_func) + @require_non_cpu + def test_get_state_dict_from_offload(self, use_safetensors): + accelerator = Accelerator() + + device_map = {"linear1": "cpu", "batchnorm": "disk", "linear2": "disk"} + model = ModelForTest() + offloaded_layer_weight = model.linear2.weight + with tempfile.TemporaryDirectory() as tmp_dir: + accelerator.save_model(model, tmp_dir, safe_serialization=use_safetensors) + # load model with offloaded layers + load_checkpoint_and_dispatch(model, tmp_dir, device_map=device_map, offload_folder=tmp_dir) + cpu_onloaded_layer = get_state_dict_from_offload( + model.linear2, "linear2.weight", {"linear2.weight": ""}, device_to_put_offload="cpu" + ) + device_onloaded_layer = get_state_dict_from_offload( + model.linear2, "linear2.weight", {"linear2.weight": ""}, device_to_put_offload=0 + ) + cpu_onloaded_layer_weight = cpu_onloaded_layer["linear2.weight"] + device_onloaded_layer_weight = device_onloaded_layer["linear2.weight"] + + assert torch.allclose(offloaded_layer_weight, cpu_onloaded_layer_weight) + assert torch.allclose( + offloaded_layer_weight, device_onloaded_layer_weight.to("cpu") + ) # must be on the same device for torch.allclose() + assert cpu_onloaded_layer_weight.device.type == "cpu" + assert device_onloaded_layer_weight.device.type == torch_device + + @parameterized.expand([True, False], name_func=parameterized_custom_name_func) + def test_save_load_model_with_hooks(self, use_safetensors): + accelerator = Accelerator() + model, optimizer, scheduler, train_dl, valid_dl = create_components() + accelerator.prepare(model, optimizer, scheduler, train_dl, valid_dl) + + model_signature = get_signature(model) + + # saving hook + def save_config(models, weights, output_dir): + config = {"class_name": models[0].__class__.__name__} + + with open(os.path.join(output_dir, "data.json"), "w") as f: + json.dump(config, f) + + # loading hook + def load_config(models, input_dir): + with open(os.path.join(input_dir, "data.json")) as f: + config = json.load(f) + + models[0].class_name = config["class_name"] + + save_hook = accelerator.register_save_state_pre_hook(save_config) + load_hook = accelerator.register_load_state_pre_hook(load_config) + + with tempfile.TemporaryDirectory() as tmpdirname: + accelerator.save_state(tmpdirname, safe_serialization=use_safetensors) + + # make sure random weights don't match with hooks + load_random_weights(model) + assert abs(model_signature - get_signature(model)) > 1e-3 + + # random class name to verify correct one is loaded + model.class_name = "random" + + # make sure loaded weights match with hooks + accelerator.load_state(tmpdirname) + assert abs(model_signature - get_signature(model)) < 1e-3 + + # mode.class_name is loaded from config + assert model.class_name == model.__class__.__name__ + + # remove hooks + save_hook.remove() + load_hook.remove() + + with tempfile.TemporaryDirectory() as tmpdirname: + accelerator.save_state(tmpdirname, safe_serialization=use_safetensors) + + # make sure random weights don't match with hooks removed + load_random_weights(model) + assert abs(model_signature - get_signature(model)) > 1e-3 + + # random class name to verify correct one is loaded + model.class_name = "random" + + # make sure loaded weights match with hooks removed + accelerator.load_state(tmpdirname) + assert abs(model_signature - get_signature(model)) < 1e-3 + + # mode.class_name is NOT loaded from config + assert model.class_name != model.__class__.__name__ + + def test_accelerator_none(self): + """Just test that passing None to accelerator.prepare() works.""" + accelerator = Accelerator() + model, optimizer, scheduler, train_dl, valid_dl = create_components() + dummy_obj = None + + # This should work + model, optimizer, scheduler, train_dl, valid_dl, dummy_obj = accelerator.prepare( + model, optimizer, scheduler, train_dl, valid_dl, dummy_obj + ) + assert dummy_obj is None + + def test_is_accelerator_prepared(self): + """Checks that `_is_accelerator_prepared` is set properly""" + accelerator = Accelerator() + model, optimizer, scheduler, train_dl, valid_dl = create_components() + dummy_obj = [1, 2, 3] + + # This should work + model, optimizer, scheduler, train_dl, valid_dl, dummy_obj = accelerator.prepare( + model, optimizer, scheduler, train_dl, valid_dl, dummy_obj + ) + assert getattr(dummy_obj, "_is_accelerate_prepared", False) is False, ( + "Dummy object should have `_is_accelerate_prepared` set to `True`" + ) + assert getattr(model, "_is_accelerate_prepared", False) is True, ( + "Model is missing `_is_accelerator_prepared` or is set to `False`" + ) + assert getattr(optimizer, "_is_accelerate_prepared", False) is True, ( + "Optimizer is missing `_is_accelerator_prepared` or is set to `False`" + ) + assert getattr(scheduler, "_is_accelerate_prepared", False) is True, ( + "Scheduler is missing `_is_accelerator_prepared` or is set to `False`" + ) + assert getattr(train_dl, "_is_accelerate_prepared", False) is True, ( + "Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`" + ) + assert getattr(valid_dl, "_is_accelerate_prepared", False) is True, ( + "Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`" + ) + + @require_cuda_or_xpu + @slow + @require_bnb + def test_accelerator_bnb(self): + """Tests that the accelerator can be used with the BNB library.""" + from transformers import AutoModelForCausalLM + + model = AutoModelForCausalLM.from_pretrained( + "EleutherAI/gpt-neo-125m", + load_in_8bit=True, + device_map={"": 0}, + ) + accelerator = Accelerator() + + # This should work + model = accelerator.prepare(model) + + @require_cuda_or_xpu + @slow + @require_bnb + def test_accelerator_bnb_cpu_error(self): + """Tests that the accelerator can be used with the BNB library. This should fail as we are trying to load a model + that is loaded between cpu and gpu""" + from transformers import AutoModelForCausalLM + + accelerator = Accelerator() + + with init_empty_weights(): + model = AutoModelForCausalLM.from_pretrained( + "EleutherAI/gpt-neo-125m", + ) + model.tie_weights() + device_map = infer_auto_device_map(model) + device_map["lm_head"] = "cpu" + + model = AutoModelForCausalLM.from_pretrained( + "EleutherAI/gpt-neo-125m", device_map=device_map, load_in_8bit=True, llm_int8_enable_fp32_cpu_offload=True + ) + + # This should not work and get value error + with self.assertRaises(ValueError): + model = accelerator.prepare(model) + + @require_non_torch_xla + @require_non_hpu # bnb is not supported on HPU + @slow + @require_bnb + @require_multi_device + def test_accelerator_bnb_multi_device(self): + """Tests that the accelerator can be used with the BNB library.""" + from transformers import AutoModelForCausalLM + + if torch_device == "cuda": + PartialState._shared_state = {"distributed_type": DistributedType.MULTI_GPU} + elif torch_device == "npu": + PartialState._shared_state = {"distributed_type": DistributedType.MULTI_NPU} + elif torch_device == "xpu": + PartialState._shared_state = {"distributed_type": DistributedType.MULTI_XPU} + else: + raise ValueError(f"{torch_device} is not supported in test_accelerator_bnb_multi_device.") + + with init_empty_weights(): + model = AutoModelForCausalLM.from_pretrained( + "EleutherAI/gpt-neo-125m", + ) + model.tie_weights() + device_map = infer_auto_device_map(model) + device_map["lm_head"] = 1 + + model = AutoModelForCausalLM.from_pretrained( + "EleutherAI/gpt-neo-125m", + load_in_8bit=True, + device_map=device_map, + ) + accelerator = Accelerator() + + # This should not work and get value error + with self.assertRaises(ValueError): + _ = accelerator.prepare(model) + + @require_non_torch_xla + @require_non_hpu # bnb is not supported on HPU + @slow + @require_bnb + @require_multi_device + def test_accelerator_bnb_multi_device_no_distributed(self): + """Tests that the accelerator can be used with the BNB library.""" + from transformers import AutoModelForCausalLM + + with init_empty_weights(): + model = AutoModelForCausalLM.from_pretrained( + "EleutherAI/gpt-neo-125m", + ) + device_map = infer_auto_device_map(model) + device_map["lm_head"] = 1 + + model = AutoModelForCausalLM.from_pretrained( + "EleutherAI/gpt-neo-125m", + load_in_8bit=True, + device_map=device_map, + ) + accelerator = Accelerator() + + # This should work + _ = accelerator.prepare(model) + + @require_non_cpu + def test_accelerator_cpu_flag_prepare(self): + model = torch.nn.Linear(10, 10) + sgd = torch.optim.SGD(model.parameters(), lr=0.01) + accelerator = Accelerator(cpu=True) + _ = accelerator.prepare(sgd) + + @require_fp8 + @require_transformer_engine + def test_can_unwrap_model_te(self): + model, optimizer, *_ = create_components() + fp8_recipe = FP8RecipeKwargs(backend="TE") + accelerator = Accelerator(mixed_precision="fp8", kwargs_handlers=[fp8_recipe]) + inputs = torch.randn(10, 2).to(torch_device) + model, optimizer = accelerator.prepare(model, optimizer) + model(inputs) # sanity check that this works + + model = accelerator.unwrap_model(model, keep_fp32_wrapper=False) + model(inputs) # check that this still works + + # check that pickle roundtrip works + model_loaded = pickle.loads(pickle.dumps(model)) + model_loaded(inputs) + + @require_fp16 + @require_non_cpu + def test_can_unwrap_model_fp16(self): + # test for a regression introduced in #872 + # before the fix, after unwrapping with keep_fp32_wrapper=False, there would be the following error: + # Linear.forward() missing 1 required positional argument: 'input' + model = create_components()[0] + accelerator = Accelerator(mixed_precision="fp16") + inputs = torch.randn(10, 2).to(torch_device) + model = accelerator.prepare(model) + model(inputs) # sanity check that this works + + model = accelerator.unwrap_model(model, keep_fp32_wrapper=False) + model(inputs) # check that this still works + + # check that pickle roundtrip works + model_loaded = pickle.loads(pickle.dumps(model)) + model_loaded(inputs) + + def test_can_unwrap_model(self): + model = create_components()[0] + accelerator = Accelerator(mixed_precision="no", cpu=True) + inputs = torch.randn(10, 2) + model = accelerator.prepare(model) + model(inputs) # sanity check that this works + + model = accelerator.unwrap_model(model, keep_fp32_wrapper=False) + model(inputs) # check that this still works + + # check that pickle roundtrip works + model_loaded = pickle.loads(pickle.dumps(model)) + model_loaded(inputs) + + def test_can_unwrap_distributed_compiled_model_keep_torch_compile(self): + model = create_components()[0] + accelerator = Accelerator() + + compiled_model = torch.compile(model) + + distributed_model = torch.nn.DataParallel(model) + distributed_compiled_model = torch.compile(distributed_model) + unwrapped_model = accelerator.unwrap_model(distributed_compiled_model, keep_torch_compile=True) + + assert compiled_model._orig_mod == unwrapped_model._orig_mod + + def test_can_unwrap_distributed_compiled_model_remove_torch_compile(self): + model = create_components()[0] + accelerator = Accelerator() + + compiled_model = torch.compile(model) + + distributed_model = torch.nn.DataParallel(model) + distributed_compiled_model = torch.compile(distributed_model) + unwrapped_model = accelerator.unwrap_model(distributed_compiled_model, keep_torch_compile=False) + + assert compiled_model._orig_mod == unwrapped_model + + @parameterized.expand([True, False]) + def test_can_pickle_dataloader(self, dispatch_batches): + """ + Test that pickling a prepared dataloader works. + """ + data = torch.arange(10).to(torch_device) + ds = torch.utils.data.TensorDataset(data) + dl = torch.utils.data.DataLoader(ds) + skip_dl = skip_first_batches(dl, 2) + + # Currently, StatefulDataLoader doesn't seem to support pickling, so we aren't testing that functionality + # TODO: Add support for pickling StatefulDataLoader + dataloader_config = DataLoaderConfiguration(dispatch_batches=dispatch_batches, use_stateful_dataloader=False) + accelerator = Accelerator(dataloader_config=dataloader_config) + + original_dl, _ = accelerator.prepare(dl, skip_dl) + if dispatch_batches: + assert isinstance(original_dl, DataLoaderDispatcher) + else: + assert isinstance(original_dl, DataLoaderShard) + + prepared_model_dumps = pickle.dumps(accelerator) + + model_loaded = pickle.loads(prepared_model_dumps) + assert len(model_loaded._dataloaders) == 2 + + # Assert equality of recovered and original dataloader + loaded_dl = model_loaded._dataloaders[0] + assert isinstance(loaded_dl, DataLoader) + if dispatch_batches: + assert isinstance(loaded_dl, DataLoaderDispatcher) + else: + assert isinstance(loaded_dl, DataLoaderShard) + assert len(loaded_dl) == len(original_dl) + assert [i for i in loaded_dl] == [i for i in original_dl] + + # Test skip dataloader works as expected as well + loaded_skip_dl = model_loaded._dataloaders[1] + assert isinstance(loaded_skip_dl, DataLoader) + if dispatch_batches: + assert isinstance(loaded_dl, DataLoaderDispatcher) + else: + assert isinstance(loaded_dl, DataLoaderShard) + assert len(loaded_skip_dl) == len(original_dl) - 2 + assert [i for i in loaded_skip_dl] == [i for i in original_dl][2:] + + # Ideally would be a parameterized test which works with either stateful or non-stateful dataloaders, but dependencies are a bit awkward. + @require_torchdata_stateful_dataloader + def test_prepared_objects_are_referenced_with_stateful_dataloader(self): + """Test that setting `use_stateful_dataloader=True` in `DataLoaderConfiguration` prepares a `StatefulDataLoader` object instead of a `DataLoader` object.""" + dataloader_config = DataLoaderConfiguration(use_stateful_dataloader=True) + accelerator = Accelerator(dataloader_config=dataloader_config) + model, optimizer, scheduler, train_dl, valid_dl = create_components() + + ( + prepared_model, + prepared_optimizer, + prepared_scheduler, + prepared_train_dl, + prepared_valid_dl, + ) = accelerator.prepare(model, optimizer, scheduler, train_dl, valid_dl) + + assert prepared_model in accelerator._models + assert prepared_optimizer in accelerator._optimizers + assert prepared_scheduler in accelerator._schedulers + assert prepared_train_dl in accelerator._dataloaders + assert prepared_valid_dl in accelerator._dataloaders + assert isinstance(prepared_train_dl, StatefulDataLoader) + assert isinstance(prepared_valid_dl, StatefulDataLoader) + + @parameterized.expand( + itertools.product([True, False], [True, False], [0, 2], [True, False]), + name_func=parameterized_custom_name_func, + ) + @require_torchdata_stateful_dataloader + def test_save_model_with_stateful_dataloader(self, use_safetensors, tied_weights, num_workers, dispatch_batches): + """ + Test that saving and loading a model with a stateful dataloader returns the same model, + and that the dataloader's iterator is restored properly.""" + set_seed(42) + n_train_batches = 64 # Use enough batches to ensure we can get partial iterations on large compute + dataloader_config = DataLoaderConfiguration(dispatch_batches=dispatch_batches, use_stateful_dataloader=True) + accelerator = Accelerator(dataloader_config=dataloader_config) + + model, optimizer, scheduler, train_dl, valid_dl = create_components(tied_weights) + train_dl, valid_dl = create_dataloaders_for_test(n_train_batches=n_train_batches, num_workers=num_workers) + model = ModelForTest() + + ( + prepared_model, + prepared_optimizer, + prepared_scheduler, + prepared_train_dl, + prepared_valid_dl, + ) = accelerator.prepare(model, optimizer, scheduler, train_dl, valid_dl) + + assert isinstance(prepared_train_dl, StatefulDataLoader) + assert isinstance(prepared_valid_dl, StatefulDataLoader) + + # Perform 3 training iterations to ensure the dataloader's iterator is advanced + num_batches_to_skip = 3 + model.train() + untrained_batches = [] + with tempfile.TemporaryDirectory() as tmpdirname: + for step, batch in enumerate(prepared_train_dl): + x, y = batch + outputs = prepared_model(x) + loss = torch.nn.functional.mse_loss(outputs, y) + accelerator.backward(loss) + prepared_optimizer.step() + prepared_scheduler.step() + prepared_optimizer.zero_grad() + if step == num_batches_to_skip - 1: + # Save the state once we've gone through a few batches + accelerator.save_state(f"{tmpdirname}/state", safe_serialization=use_safetensors) + if step >= num_batches_to_skip: + untrained_batches.append(batch) + + not_skipped_batches = accelerator.gather(untrained_batches) + # We then unwrap the trained model + unwrapped_model = accelerator.unwrap_model(prepared_model) + + original_linear1 = unwrapped_model.linear1.weight.clone() + original_batchnorm = unwrapped_model.batchnorm.weight.clone() + original_linear2 = unwrapped_model.linear2.weight.clone() + + # Resume the state + accelerator.load_state(f"{tmpdirname}/state") + + # Train this to the end of the DataLoader + batches_seen_with_loaded_dl = 0 + for batch in prepared_train_dl: + x, y = batch + outputs = prepared_model(x) + loss = torch.nn.functional.mse_loss(outputs, y) + accelerator.backward(loss) + prepared_optimizer.step() + prepared_scheduler.step() + prepared_optimizer.zero_grad() + batches_seen_with_loaded_dl += 1 + + unwrapped_model_2 = accelerator.unwrap_model(prepared_model) + + new_linear1 = unwrapped_model_2.linear1.weight + new_batchnorm = unwrapped_model_2.batchnorm.weight + new_linear2 = unwrapped_model_2.linear2.weight + + # Assert equalities + assert batches_seen_with_loaded_dl == len(not_skipped_batches) + assert torch.allclose(original_linear1, new_linear1) + assert torch.allclose(original_batchnorm, new_batchnorm) + assert torch.allclose(original_linear2, new_linear2) + + @require_non_cpu + @require_huggingface_suite + def test_nested_hook(self): + from transformers.modeling_utils import PretrainedConfig, PreTrainedModel + + class MyLinear(torch.nn.Module): + def __init__(self, device=None, dtype=None): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.centroid = torch.nn.Embedding(1, 2) + self.indices = torch.nn.Parameter(torch.empty((1, 2, 2), **factory_kwargs)) + + def forward(self, x): + orig_shape = x.shape + x = torch.abs(x + self.indices).long() + x = x % 2 + x = x.sum(-1) + x = (self.centroid.weight + x).reshape(orig_shape) + return x + + class MySubModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.layer = MyLinear() + + def forward(self, x): + return self.layer(x) + + class MyModel(PreTrainedModel): + def __init__(self, config): + super().__init__(config) + self.layer = torch.nn.ModuleList([MySubModel() for i in range(4)]) + + def forward(self, x): + for layer in self.layer: + x = layer(x) + return x + + with tempfile.TemporaryDirectory() as tmpdirname: + check_point = tmpdirname + offload_folder = check_point + "/offload" + os.makedirs(offload_folder, exist_ok=True) + config = PretrainedConfig() + m = MyModel(config) + m.save_pretrained(check_point) + + with init_empty_weights(): + my_model = MyModel(config) + my_model = load_checkpoint_and_dispatch( + my_model, + checkpoint=check_point, + max_memory={"cpu": 60, 0: 60}, + device_map="auto", + no_split_module_classes=["MySubModel"], + offload_folder=offload_folder, + preload_module_classes=["MyLinear"], + ) + # before fix, this would raise an error + # weight is on the meta device, we need a `value` to put in on 0 + x = torch.randn(1, 2) + my_model(x) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_big_modeling.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_big_modeling.py new file mode 100644 index 0000000000000000000000000000000000000000..7c960745565be2ac7879c359ec39e4ffb0a38db4 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_big_modeling.py @@ -0,0 +1,1099 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import copy +import gc +import itertools +import logging +import os +import unittest +from collections import OrderedDict +from tempfile import TemporaryDirectory + +import torch +import torch.nn as nn +from transformers import AutoModelForCausalLM, AutoTokenizer + +from accelerate.big_modeling import ( + cpu_offload, + cpu_offload_with_hook, + disk_offload, + dispatch_model, + init_empty_weights, + init_on_device, + load_checkpoint_and_dispatch, +) +from accelerate.hooks import remove_hook_from_submodules +from accelerate.test_utils import ( + require_bnb, + require_cuda_or_xpu, + require_multi_device, + require_multi_gpu_or_xpu, + require_non_cpu, + require_non_hpu, + require_non_torch_xla, + slow, + torch_device, +) +from accelerate.utils import is_hpu_available, offload_state_dict +from accelerate.utils.memory import clear_device_cache +from accelerate.utils.versions import is_torch_version + + +logger = logging.getLogger(__name__) +torch_device_type = torch_device +torch_device = f"{torch_device}:0" if torch_device != "cpu" else "cpu" + +if is_hpu_available(): + ATOL = 1e-4 + RTOL = 1e-4 +else: + ATOL = 1e-5 + RTOL = 1e-5 + + +class ModelForTest(nn.Module): + def __init__(self): + super().__init__() + self.linear1 = nn.Linear(3, 4) + self.batchnorm = nn.BatchNorm1d(4) + self.linear2 = nn.Linear(4, 5) + + def forward(self, x): + return self.linear2(self.batchnorm(self.linear1(x))) + + +class LinearWithNonPersistentBuffers(nn.Module): + def __init__(self, in_features: int, out_features: int, bias: bool = True, device=None, dtype=None) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.in_features = in_features + self.out_features = out_features + self.register_buffer("weight", torch.ones((out_features, in_features), **factory_kwargs)) + if bias: + self.register_buffer("bias", torch.ones(out_features, **factory_kwargs), persistent=False) + else: + self.register_buffer("bias", None) + + def forward(self, input: torch.Tensor) -> torch.Tensor: + return torch.nn.functional.linear(input, self.weight, self.bias) + + +class ModelForTestNonPersistentBuffers(nn.Module): + def __init__(self): + super().__init__() + self.linear1 = LinearWithNonPersistentBuffers(3, 4) + self.batchnorm = nn.BatchNorm1d(4) + self.linear2 = LinearWithNonPersistentBuffers(4, 5) + + def forward(self, x): + return self.linear2(self.batchnorm(self.linear1(x))) + + +class ModelForTestCopy(nn.Module): + def __init__(self, id: int): + super().__init__() + self.id = id + self.linear1 = nn.Linear(3, 4) + self.batchnorm = nn.BatchNorm1d(4) + self.linear2 = nn.Linear(4, 5) + + def forward(self, x): + return self.linear2(self.batchnorm(self.linear1(x))), self.id + + +class ModelForTestTiedWeights(nn.Module): + def __init__(self): + super().__init__() + self.linear1 = nn.Linear(4, 4) + self.batchnorm = nn.BatchNorm1d(4) + self.linear2 = nn.Linear(4, 4) + + def forward(self, x): + return self.linear2(self.batchnorm(self.linear1(x))) + + +class BiggerModelForTest(nn.Module): + def __init__(self): + super().__init__() + self.linear1 = nn.Linear(3, 4) + self.linear2 = nn.Linear(4, 5) + self.batchnorm = nn.BatchNorm1d(5) + self.linear3 = nn.Linear(5, 6) + self.linear4 = nn.Linear(6, 5) + + def forward(self, x): + return self.linear4(self.linear3(self.batchnorm(self.linear2(self.linear1(x))))) + + +# To test preload_module_classes +class ModuleWithUnusedSubModules(nn.Module): + def __init__(self, input_dim, output_dim): + super().__init__() + self.linear = nn.Linear(input_dim, output_dim) + + def forward(self, x): + return x @ self.linear.weight.t() + self.linear.bias + + +class ModelWithUnusedSubModulesForTest(nn.Module): + def __init__(self): + super().__init__() + self.linear1 = ModuleWithUnusedSubModules(3, 4) + self.linear2 = ModuleWithUnusedSubModules(4, 5) + self.batchnorm = nn.BatchNorm1d(5) + self.linear3 = ModuleWithUnusedSubModules(5, 6) + self.linear4 = ModuleWithUnusedSubModules(6, 5) + + def forward(self, x): + return self.linear4(self.linear3(self.batchnorm(self.linear2(self.linear1(x))))) + + +class BigModelingTester(unittest.TestCase): + def test_init_empty_weights(self): + # base use + with init_empty_weights(): + module = nn.Linear(4, 5) + assert module.weight.device == torch.device("meta") + + # base use with buffers, they are not touched + with init_empty_weights(): + module = nn.BatchNorm1d(4) + assert module.weight.device == torch.device("meta") + assert module.running_mean.device == torch.device("cpu") + + # Use with include_buffers=True + register_parameter_func = nn.Module.register_parameter + register_buffer_func = nn.Module.register_buffer + with init_empty_weights(include_buffers=True): + module = nn.BatchNorm1d(4) + # nn.Module.register_parameter/buffer shouldn't be changed with torch >= 2.0 + assert register_parameter_func == nn.Module.register_parameter + assert register_buffer_func == nn.Module.register_buffer + assert module.weight.device == torch.device("meta") + assert module.running_mean.device == torch.device("meta") + + # Double check we didn't break PyTorch + module = nn.BatchNorm1d(4) + assert module.weight.device == torch.device("cpu") + assert module.running_mean.device == torch.device("cpu") + + def test_init_empty_weights_very_large_model(self): + # This is a 100 billion parameters model. + with init_empty_weights(): + _ = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)]) + + @require_non_cpu + def test_init_on_device(self): + device = torch.device(torch_device) + with init_on_device(device): + model = nn.Linear(10, 10) + assert model.weight.device == device + assert model.weight.device == device + + def test_cpu_offload(self): + model = ModelForTest() + x = torch.randn(2, 3) + expected = model(x) + + device = torch.device(torch_device) + + cpu_offload(model, execution_device=device) + output = model(x) + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + # Clean up for next test. + remove_hook_from_submodules(model) + + cpu_offload(model, execution_device=device, offload_buffers=True) + output = model(x) + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + def test_cpu_offload_with_unused_submodules(self): + model = ModelWithUnusedSubModulesForTest() + x = torch.randn(2, 3) + expected = model(x) + + device = torch.device(torch_device) + + cpu_offload(model, execution_device=device, preload_module_classes=["ModuleWithUnusedSubModules"]) + output = model(x) + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + # Clean up for next test. + remove_hook_from_submodules(model) + + cpu_offload( + model, + execution_device=device, + offload_buffers=True, + preload_module_classes=["ModuleWithUnusedSubModules"], + ) + output = model(x) + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + @slow + @require_non_cpu + def test_cpu_offload_gpt2(self): + tokenizer = AutoTokenizer.from_pretrained("gpt2") + inputs = tokenizer("Hello world! My name is", return_tensors="pt").to(torch_device) + + gpt2 = AutoModelForCausalLM.from_pretrained("gpt2") + cpu_offload(gpt2, execution_device=0) + outputs = gpt2.generate(inputs["input_ids"], max_new_tokens=10) + assert tokenizer.decode(outputs[0].tolist()) == "Hello world! My name is Kiyoshi, and I'm a student at" + + def test_disk_offload(self): + model = ModelForTest() + x = torch.randn(2, 3) + expected = model(x) + + device = torch.device(torch_device) + + with TemporaryDirectory() as tmp_dir: + disk_offload(model, tmp_dir, execution_device=device) + output = model(x) + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + # Clean up for next test. + remove_hook_from_submodules(model) + + with TemporaryDirectory() as tmp_dir: + disk_offload(model, tmp_dir, execution_device=device, offload_buffers=True) + output = model(x) + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + def test_disk_offload_with_unused_submodules(self): + model = ModelWithUnusedSubModulesForTest() + x = torch.randn(2, 3) + expected = model(x) + + device = torch.device(torch_device) + + with TemporaryDirectory() as tmp_dir: + disk_offload( + model, tmp_dir, execution_device=device, preload_module_classes=["ModuleWithUnusedSubModules"] + ) + output = model(x) + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + # Clean up for next test. + remove_hook_from_submodules(model) + + with TemporaryDirectory() as tmp_dir: + disk_offload( + model, + tmp_dir, + execution_device=device, + offload_buffers=True, + preload_module_classes=["ModuleWithUnusedSubModules"], + ) + output = model(x) + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + @slow + @require_non_cpu + def test_disk_offload_gpt2(self): + tokenizer = AutoTokenizer.from_pretrained("gpt2") + inputs = tokenizer("Hello world! My name is", return_tensors="pt").to(torch_device) + + gpt2 = AutoModelForCausalLM.from_pretrained("gpt2") + with TemporaryDirectory() as tmp_dir: + disk_offload(gpt2, tmp_dir, execution_device=0) + outputs = gpt2.generate(inputs["input_ids"], max_new_tokens=10) + assert tokenizer.decode(outputs[0].tolist()) == "Hello world! My name is Kiyoshi, and I'm a student at" + + @require_non_cpu + def test_dispatch_model_and_remove_hook(self): + model = ModelForTest() + device_map = {"linear1": "cpu", "batchnorm": "cpu", "linear2": 0} + x = torch.randn(2, 3) + expected = model(x) + + with TemporaryDirectory() as tmp_dir: + dispatch_model(model, device_map, offload_dir=tmp_dir) + output = model(x) + remove_hook_from_submodules(model) + # need to check if we get any warning + with self.assertLogs(level="WARNING") as cm: + # We want to assert there are no warnings, but the 'assertLogs' method does not support that. + # Therefore, we are adding a dummy warning, and then we will assert it is the only warning. + model.to(torch_device) + logger.warning("Dummy warning") + self.assertEqual(len(cm.records), 1) + self.assertIn( + "Dummy warning", + cm.records[0].message, + ) + output_bis = model(x.to(torch_device)) + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + torch.testing.assert_close(expected, output_bis.cpu(), atol=ATOL, rtol=RTOL) + + @require_non_cpu + def test_dispatch_model(self): + model = ModelForTest() + device_map = {"linear1": "disk", "batchnorm": "cpu", "linear2": 0} + + x = torch.randn(2, 3) + expected = model(x) + + with TemporaryDirectory() as tmp_dir: + dispatch_model(model, device_map, offload_dir=tmp_dir) + output = model(x) + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + @require_non_cpu + def test_dispatch_model_with_non_persistent_buffers(self): + model = ModelForTestNonPersistentBuffers() + device_map = {"linear1": 0, "batchnorm": "cpu", "linear2": "disk"} + x = torch.randn(2, 3) + expected = model(x) + + with TemporaryDirectory() as tmp_dir: + dispatch_model(model, device_map, offload_dir=tmp_dir, offload_buffers=True) + output = model(x) + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + @require_non_cpu + def test_dispatch_model_tied_weights(self): + model = ModelForTestTiedWeights() + model.linear1.weight = model.linear2.weight + device_map = {"linear1": 0, "batchnorm": 0, "linear2": 0} + + dispatch_model(model, device_map) + assert model.linear2.weight is model.linear1.weight + + @require_multi_gpu_or_xpu + def test_dispatch_model_tied_weights_memory(self): + # Test that we do not duplicate tied weights at any point during dispatch_model call. + + torch_accelerator_module = getattr(torch, torch_device_type) + + clear_device_cache() # Needed in case we run several tests in a row. + + model = nn.Sequential( + OrderedDict( + [ + ("linear0", nn.Linear(5000, 5000, bias=False)), + ("linear1", nn.Linear(5000, 5000, bias=False)), + ("linear2", nn.Linear(5000, 5000, bias=False)), + ("linear3", nn.Linear(5000, 5000, bias=False)), + ("linear4", nn.Linear(5000, 5000, bias=False)), + ] + ) + ) + model.linear2.weight = model.linear0.weight + model.linear3.weight = model.linear0.weight + model.linear4.weight = model.linear0.weight + + x = torch.randn(5, 5000) + with torch.no_grad(): + expected = model(x) + + # We should need only 5000 * 5000 * 32 // 8 * 1e-6 = 100 MB on the device 0 for the four linear weights. + device_0 = f"{torch_device_type}:0" if torch_device != "cpu" else "cpu" + device_1 = f"{torch_device_type}:1" if torch_device != "cpu" else "cpu" + device_map = { + "linear0": device_0, + "linear1": device_1, + "linear2": device_0, + "linear3": device_0, + "linear4": device_0, + } + + # Just to initialize CUDA context. + a = torch.rand(5).to(device_0) # noqa: F841 + + free_memory_bytes = torch_accelerator_module.mem_get_info(device_0)[0] + required_memory_bytes = 5000 * 5000 * (32 // 8) + + # Leaving 50 MB of free memory for possible buffers, etc. + n_vals = (free_memory_bytes - required_memory_bytes - int(50e6)) // (32 // 8) + foo = torch.rand(n_vals, device=device_0) # noqa: F841 + + # If this does OOM: there is an issue in somewhere in dispatch_model, memory of tied weights is duplicated. + oom_error = ( + torch.OutOfMemoryError if is_torch_version(">=", "2.5.0") else torch_accelerator_module.OutOfMemoryError + ) + try: + dispatch_model(model, device_map) + except oom_error as e: + raise oom_error( + f"OOM error in dispatch_model. This is a bug and should not happen, see test_dispatch_model_tied_weights_memory. {e}" + ) + except Exception as e: + raise e + + with torch.no_grad(): + output = model(x) + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + @require_cuda_or_xpu + def test_dispatch_model_tied_weights_memory_with_nested_offload_cpu(self): + # Test that we do not duplicate tied weights at any point during dispatch_model call. + + torch_accelerator_module = getattr(torch, torch_device_type) + clear_device_cache() # Needed in case we run several tests in a row. + + class SubModule(torch.nn.Module): + def __init__(self, ref_to_parameter): + super().__init__() + self.parameter = ref_to_parameter + + def forward(self, x): + return x + torch.max(self.parameter) + + class LinearModuleAndSubModule(torch.nn.Linear): + def __init__(self, in_features, out_features): + super().__init__(in_features, out_features, bias=False) + self.weight_submodule = SubModule(self.weight) + self.weight_submodule2 = SubModule(self.weight) + self.weight_submodule3 = SubModule(self.weight) + self.weight_submodule4 = SubModule(self.weight) + + def forward(self, x): + a = torch.nn.functional.linear(self.weight_submodule(x), self.weight) + b = torch.nn.functional.linear(self.weight_submodule2(x), self.weight) + c = torch.nn.functional.linear(self.weight_submodule3(x), self.weight) + d = torch.nn.functional.linear(self.weight_submodule4(x), self.weight) + return a + b + c + d + + class ModelWithSubmodules(torch.nn.Module): + def __init__(self): + super().__init__() + self.compute = LinearModuleAndSubModule(5000, 5000) + self.compute1 = LinearModuleAndSubModule(5000, 5000) + + def forward(self, x): + a = self.compute(x) + b = self.compute1(x) + return a + b + + # We should need only 2 * 5000 * 5000 * 32 // 8 * 1e-6 = 200 MB on the device 0 for the whole model forward, and not 600 MB. + device_map = {"compute": torch_device, "compute1": "cpu"} + + model = ModelWithSubmodules() + + x = torch.randn(1, 5000) + with torch.no_grad(): + expected = model(x) + + # Just to initialize accelerator context. + a = torch.rand(5).to(torch_device) # noqa: F841 + + free_memory_bytes = torch_accelerator_module.mem_get_info(torch_device)[0] + required_memory_bytes = 2 * 5000 * 5000 * (32 // 8) # 200 MB + + # Leaving 150 MB of free memory for possible buffers, etc. + n_vals = (free_memory_bytes - required_memory_bytes - int(150e6)) // (32 // 8) + foo = torch.rand(n_vals, device=torch_device) # noqa: F841 + + free_memory_bytes_before_dispatch = torch_accelerator_module.mem_get_info(torch_device)[0] + dispatch_model(model, device_map) + free_memory_bytes_after_dispatch = torch_accelerator_module.mem_get_info(torch_device)[0] + + assert (free_memory_bytes_after_dispatch - free_memory_bytes_before_dispatch) * 1e-6 < 130 + + original_pointer = model.compute1._hf_hook.weights_map["weight"].data_ptr() + + oom_error = ( + torch.OutOfMemoryError if is_torch_version(">=", "2.5.0") else torch_accelerator_module.OutOfMemoryError + ) + with torch.no_grad(): + try: + output = model(x) + except oom_error as e: + raise oom_error( + f"OOM error in dispatch_model. This is a bug and should not happen, see test_dispatch_model_tied_weights_memory_with_nested_offload_cpu. {e}" + ) + except Exception as e: + raise e + + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + clear_device_cache() + + free_memory_bytes_after_infer = torch_accelerator_module.mem_get_info(torch_device)[0] + + # Check that we have no more references on GPU for the offloaded tied weight. + assert len(model.compute1.weight_submodule._hf_hook.tied_params_map[original_pointer]) == 0 + assert len(model.compute1._hf_hook.tied_params_map[original_pointer]) == 0 + assert (free_memory_bytes_after_infer - free_memory_bytes_after_dispatch) * 1e-6 < 130 + + # Test is flacky otherwise. + del model + gc.collect() + + # This test fails because sometimes data_ptr() of compute2.weight is the same as compute1.weight. + # I checked that the values are not the same but it gives the same address. This does not happen on my local machine. + @require_cuda_or_xpu + @unittest.skip( + "Flaky test, we should have enough coverage with test_dispatch_model_tied_weights_memory_with_nested_offload_cpu test" + ) + def test_dispatch_model_tied_weights_memory_with_nested_offload_disk(self): + # Test that we do not duplicate tied weights at any point during dispatch_model call. + + torch_accelerator_module = getattr(torch, torch_device_type) + + clear_device_cache() # Needed in case we run several tests in a row. + + class SubModule(torch.nn.Module): + def __init__(self, ref_to_parameter): + super().__init__() + self.parameter = ref_to_parameter + + def forward(self, x): + return x + torch.max(self.parameter) + + class LinearModuleAndSubModule(torch.nn.Linear): + def __init__(self, in_features, out_features): + super().__init__(in_features, out_features, bias=False) + self.weight_submodule = SubModule(self.weight) + self.weight_submodule2 = SubModule(self.weight) + self.weight_submodule3 = SubModule(self.weight) + self.weight_submodule4 = SubModule(self.weight) + + def forward(self, x): + a = torch.nn.functional.linear(self.weight_submodule(x), self.weight) + b = torch.nn.functional.linear(self.weight_submodule2(x), self.weight) + c = torch.nn.functional.linear(self.weight_submodule3(x), self.weight) + d = torch.nn.functional.linear(self.weight_submodule4(x), self.weight) + return a + b + c + d + + class ModelWithSubmodules(torch.nn.Module): + def __init__(self): + super().__init__() + self.compute = LinearModuleAndSubModule(5000, 5000) + self.compute1 = LinearModuleAndSubModule(5000, 5000) + + def forward(self, x): + a = self.compute(x) + b = self.compute1(x) + return a + b + + # We should need only 2 * 5000 * 5000 * 32 // 8 * 1e-6 = 200 MB on the device 0 for the whole model forward, and not 600 MB. + device_map = {"compute": 0, "compute1": "disk"} + + model = ModelWithSubmodules() + + x = torch.randn(1, 5000) + with torch.no_grad(): + expected = model(x) + + # Just to initialize CUDA context. + device_0 = f"{torch_device_type}:0" + a = torch.rand(5).to(device_0) # noqa: F841 + + free_memory_bytes = torch_accelerator_module.mem_get_info(device_0)[0] + required_memory_bytes = 2 * 5000 * 5000 * (32 // 8) # 200 MB + + # Leaving 150 MB of free memory for possible buffers, etc. + n_vals = (free_memory_bytes - required_memory_bytes - int(200e6)) // (32 // 8) + foo = torch.rand(n_vals, device=device_0) # noqa: F841 + + free_memory_bytes_before_dispatch = torch_accelerator_module.mem_get_info(device_0)[0] + with TemporaryDirectory() as tmp_dir: + dispatch_model(model, device_map, offload_dir=tmp_dir) + free_memory_bytes_after_dispatch = torch_accelerator_module.mem_get_info(device_0)[0] + + assert (free_memory_bytes_after_dispatch - free_memory_bytes_before_dispatch) * 1e-6 < 130 + + oom_error = ( + torch.OutOfMemoryError + if hasattr(torch, "OutOfMemoryError") + else torch_accelerator_module.OutOfMemoryError + ) + with torch.no_grad(): + try: + output = model(x) + except oom_error as e: + raise oom_error( + f"OOM error in dispatch_model. This is a bug and should not happen, see test_dispatch_model_tied_weights_memory_with_nested_offload_disk. {e}" + ) + except Exception as e: + raise e + + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + clear_device_cache() + + free_memory_bytes_after_infer = torch_accelerator_module.mem_get_info(device_0)[0] + + # Check that we have no more references on GPU for the offloaded tied weight. + n_non_empty = 0 + for pointer, pointer_dict in model.compute1.weight_submodule._hf_hook.tied_params_map.items(): + if len(pointer_dict) > 0: + n_non_empty += 1 + assert n_non_empty == 1 # `compute` layer one. + + n_non_empty = 0 + for pointer, pointer_dict in model.compute1._hf_hook.tied_params_map.items(): + if len(pointer_dict) > 0: + n_non_empty += 1 + assert n_non_empty == 1 # `compute` layer one. + + assert (free_memory_bytes_after_infer - free_memory_bytes_after_dispatch) * 1e-6 < 130 + + @require_non_hpu # hpu does not support device indexing "hpu:1" + @require_multi_device + def test_dispatch_model_multi_devices(self): + model = BiggerModelForTest() + + device_map = {"linear1": "cpu", "linear2": "disk", "batchnorm": "cpu", "linear3": 0, "linear4": 1} + + x = torch.randn(2, 3) + expected = model(x) + + with TemporaryDirectory() as tmp_dir: + dispatch_model(model, device_map, offload_dir=tmp_dir) + output = model(x) + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + @require_non_cpu + def test_dispatch_model_copy(self): + original_model = ModelForTestCopy(id=1) + device_map = {"linear1": 0, "batchnorm": "cpu", "linear2": 0} + + x = torch.randn(2, 3) + expected, original_output_id = original_model(x) + + dispatch_model(original_model, device_map) + + copied_model = copy.deepcopy(original_model) + copied_model.id = 2 + output, copied_output_id = copied_model(x) + + assert original_model.id == original_output_id + assert copied_model.id == copied_output_id + assert copied_model.linear1.forward is not original_model.linear1.forward + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + @require_non_cpu + def test_dispatch_model_move_offloaded_model(self): + model = ModelForTest() + device_map = {"linear1": "disk", "batchnorm": "cpu", "linear2": 0} + with TemporaryDirectory() as tmp_dir: + dispatch_model(model, device_map, offload_dir=tmp_dir) + with self.assertRaises(RuntimeError): + model.to(0) + + @require_non_hpu # hpu does not support device indexing "hpu:1" + @require_multi_device + def test_dispatch_model_move_model_warning(self): + model = ModelForTest() + device_map = {"linear1": 0, "batchnorm": 0, "linear2": 1} + with TemporaryDirectory() as tmp_dir: + dispatch_model(model, device_map, offload_dir=tmp_dir) + with self.assertLogs("accelerate.big_modeling", level="WARNING"): + model.to("cpu") + with self.assertLogs("accelerate.big_modeling", level="WARNING"): + model.to(torch_device) + with self.assertRaises(RuntimeError): + x = torch.randn(2, 3) + model(x) + + @slow + @require_non_hpu # hpu does not support device indexing "hpu:1" + @require_multi_device + def test_dispatch_model_gpt2_on_two_devices(self): + tokenizer = AutoTokenizer.from_pretrained("gpt2") + inputs = tokenizer("Hello world! My name is", return_tensors="pt").to(torch_device) + + gpt2 = AutoModelForCausalLM.from_pretrained("gpt2") + # Dispatch on GPUs 0 and 1 + device_map = { + "transformer.wte": 0, + "transformer.wpe": 0, + "transformer.ln_f": 1, + "lm_head": 0, + } + for i in range(12): + device_map[f"transformer.h.{i}"] = 0 if i <= 5 else 1 + + gpt2 = dispatch_model(gpt2, device_map) + outputs = gpt2.generate(inputs["input_ids"], max_new_tokens=10) + assert tokenizer.decode(outputs[0].tolist()) == "Hello world! My name is Kiyoshi, and I'm a student at" + + # Dispatch with a bit of CPU offload + gpt2 = AutoModelForCausalLM.from_pretrained("gpt2") + for i in range(4): + device_map[f"transformer.h.{i}"] = "cpu" + gpt2 = dispatch_model(gpt2, device_map) + outputs = gpt2.generate(inputs["input_ids"], max_new_tokens=10) + assert tokenizer.decode(outputs[0].tolist()) == "Hello world! My name is Kiyoshi, and I'm a student at" + # Dispatch with a bit of CPU and disk offload + gpt2 = AutoModelForCausalLM.from_pretrained("gpt2") + for i in range(2): + device_map[f"transformer.h.{i}"] = "disk" + + with TemporaryDirectory() as tmp_dir: + state_dict = { + k: p for k, p in gpt2.state_dict().items() if "transformer.h.0" in k or "transformer.h.1" in k + } + offload_state_dict(tmp_dir, state_dict) + gpt2 = dispatch_model(gpt2, device_map, offload_dir=tmp_dir) + outputs = gpt2.generate(inputs["input_ids"], max_new_tokens=10) + assert tokenizer.decode(outputs[0].tolist()) == "Hello world! My name is Kiyoshi, and I'm a student at" + + @require_non_cpu + def test_dispatch_model_with_unused_submodules(self): + model = ModelWithUnusedSubModulesForTest() + device_map = {"linear1": "cpu", "linear2": "disk", "batchnorm": "cpu", "linear3": 0, "linear4": 0} + + x = torch.randn(2, 3) + expected = model(x) + + with TemporaryDirectory() as tmp_dir: + dispatch_model( + model, device_map, offload_dir=tmp_dir, preload_module_classes=["ModuleWithUnusedSubModules"] + ) + output = model(x) + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + @require_non_hpu # hpu does not support device indexing "hpu:1" + @require_multi_device + def test_dispatch_model_with_unused_submodules_multi_device(self): + model = ModelWithUnusedSubModulesForTest() + + device_map = {"linear1": "cpu", "linear2": "disk", "batchnorm": "cpu", "linear3": 0, "linear4": 1} + + x = torch.randn(2, 3) + expected = model(x) + + with TemporaryDirectory() as tmp_dir: + dispatch_model( + model, device_map, offload_dir=tmp_dir, preload_module_classes=["ModuleWithUnusedSubModules"] + ) + output = model(x) + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + @require_non_cpu + def test_dispatch_model_force_hooks(self): + model = ModelForTest() + device_map = {"": 0} + + x = torch.randn(2, 3) + expected = model(x) + + dispatch_model(model, device_map, force_hooks=True) + output = model(x) + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + @require_non_cpu + def test_load_checkpoint_and_dispatch(self): + model = ModelForTest() + device_map = {"linear1": "cpu", "batchnorm": "cpu", "linear2": 0} + + x = torch.randn(2, 3) + expected = model(x) + + with TemporaryDirectory() as tmp_dir: + checkpoint = os.path.join(tmp_dir, "pt_model.bin") + torch.save(model.state_dict(), checkpoint) + + new_model = ModelForTest() + new_model = load_checkpoint_and_dispatch(new_model, checkpoint, device_map=device_map) + + # CPU-offloaded weights are on the meta device while waiting for the forward pass. + assert new_model.linear1.weight.device == torch.device("meta") + assert new_model.linear2.weight.device == torch.device(torch_device) + + output = new_model(x) + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + def test_load_checkpoint_and_dispatch_device_map_none(self): + model = ModelForTest() + + with TemporaryDirectory() as tmp_dir: + checkpoint = os.path.join(tmp_dir, "pt_model.bin") + torch.save(model.state_dict(), checkpoint) + + new_model = ModelForTest() + new_model = load_checkpoint_and_dispatch(new_model, checkpoint, device_map=None) + + for (name, tensor), (new_name, new_tensor) in zip( + itertools.chain(model.named_parameters(), model.named_buffers()), + itertools.chain(new_model.named_parameters(), new_model.named_buffers()), + ): + assert name == new_name + torch.testing.assert_close(tensor, new_tensor, msg=new_name) + + @require_non_hpu # hpu does not support device indexing "hpu:1" + @require_multi_device + def test_load_checkpoint_and_dispatch_multi_device(self): + model = BiggerModelForTest() + + device_map = {"linear1": "cpu", "linear2": "cpu", "batchnorm": 0, "linear3": 0, "linear4": 1} + + x = torch.randn(2, 3) + expected = model(x) + + with TemporaryDirectory() as tmp_dir: + checkpoint = os.path.join(tmp_dir, "pt_model.bin") + torch.save(model.state_dict(), checkpoint) + + new_model = BiggerModelForTest() + new_model = load_checkpoint_and_dispatch(new_model, checkpoint, device_map=device_map) + + # CPU-offloaded weights are on the meta device while waiting for the forward pass. + assert new_model.linear1.weight.device == torch.device("meta") + assert new_model.linear2.weight.device == torch.device("meta") + assert new_model.linear3.weight.device == torch.device(torch_device) + assert new_model.linear4.weight.device == torch.device(torch_device.replace(":0", ":1")) + + output = new_model(x) + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + @require_non_cpu + def test_load_checkpoint_and_dispatch_with_unused_submodules(self): + model = ModelWithUnusedSubModulesForTest() + device_map = {"linear1": "cpu", "linear2": "cpu", "batchnorm": 0, "linear3": 0, "linear4": 0} + + x = torch.randn(2, 3) + expected = model(x) + + with TemporaryDirectory() as tmp_dir: + checkpoint = os.path.join(tmp_dir, "pt_model.bin") + torch.save(model.state_dict(), checkpoint) + + new_model = ModelWithUnusedSubModulesForTest() + new_model = load_checkpoint_and_dispatch( + new_model, checkpoint, device_map=device_map, preload_module_classes=["ModuleWithUnusedSubModules"] + ) + + # CPU-offloaded weights are on the meta device while waiting for the forward pass. + assert new_model.linear1.linear.weight.device == torch.device("meta") + assert new_model.linear2.linear.weight.device == torch.device("meta") + assert new_model.linear3.linear.weight.device == torch.device(torch_device) + assert new_model.linear4.linear.weight.device == torch.device(torch_device) + + output = new_model(x) + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + @require_non_hpu # hpu does not support device indexing "hpu:1" + @require_multi_device + def test_load_checkpoint_and_dispatch_multi_device_with_unused_submodules(self): + model = ModelWithUnusedSubModulesForTest() + + device_map = {"linear1": "cpu", "linear2": "cpu", "batchnorm": 0, "linear3": 0, "linear4": 1} + + x = torch.randn(2, 3) + expected = model(x) + + with TemporaryDirectory() as tmp_dir: + checkpoint = os.path.join(tmp_dir, "pt_model.bin") + torch.save(model.state_dict(), checkpoint) + + new_model = ModelWithUnusedSubModulesForTest() + new_model = load_checkpoint_and_dispatch( + new_model, checkpoint, device_map=device_map, preload_module_classes=["ModuleWithUnusedSubModules"] + ) + + # CPU-offloaded weights are on the meta device while waiting for the forward pass. + assert new_model.linear1.linear.weight.device == torch.device("meta") + assert new_model.linear2.linear.weight.device == torch.device("meta") + assert new_model.linear3.linear.weight.device == torch.device(torch_device) + assert new_model.linear4.linear.weight.device == torch.device(torch_device.replace(":0", ":1")) + + output = new_model(x) + torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL) + + @require_non_cpu + def test_cpu_offload_with_hook(self): + model1 = torch.nn.Linear(4, 5) + model1, hook1 = cpu_offload_with_hook(model1) + assert model1.weight.device == torch.device("cpu") + + inputs = torch.randn(3, 4) + outputs = model1(inputs) + assert outputs.device == torch.device(torch_device) + assert model1.weight.device == torch.device(torch_device) + + hook1.offload() + assert model1.weight.device == torch.device("cpu") + + model2 = torch.nn.Linear(5, 5) + model2, hook2 = cpu_offload_with_hook(model2, prev_module_hook=hook1) + assert model2.weight.device == torch.device("cpu") + + outputs = model1(inputs) + assert outputs.device == torch.device(torch_device) + assert model1.weight.device == torch.device(torch_device) + + outputs = model2(outputs) + assert outputs.device == torch.device(torch_device) + assert model1.weight.device == torch.device("cpu") + assert model2.weight.device == torch.device(torch_device) + + hook2.offload() + assert model2.weight.device == torch.device("cpu") + + @slow + @require_bnb + @require_non_hpu # bnb is not supported on hpu + @require_non_torch_xla + @require_multi_device + def test_dispatch_model_bnb(self): + """Tests that `dispatch_model` quantizes int8 layers""" + from huggingface_hub import hf_hub_download + from transformers import AutoConfig, AutoModel, BitsAndBytesConfig + from transformers.utils.bitsandbytes import replace_with_bnb_linear + + with init_empty_weights(): + model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m")) + + quantization_config = BitsAndBytesConfig(load_in_8bit=True) + model = replace_with_bnb_linear( + model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config + ) + + model_path = hf_hub_download("bigscience/bloom-560m", "pytorch_model.bin") + + model = load_checkpoint_and_dispatch( + model, + checkpoint=model_path, + device_map="balanced", + ) + + assert model.h[0].self_attention.query_key_value.weight.dtype == torch.int8 + assert model.h[0].self_attention.query_key_value.weight.device.index == 0 + + assert model.h[(-1)].self_attention.query_key_value.weight.dtype == torch.int8 + assert model.h[(-1)].self_attention.query_key_value.weight.device.index == 1 + + @require_cuda_or_xpu + @slow + @require_bnb + def test_dispatch_model_int8_simple(self): + """Tests that `dispatch_model` quantizes int8 layers""" + from huggingface_hub import hf_hub_download + from transformers import AutoConfig, AutoModel, BitsAndBytesConfig + from transformers.utils.bitsandbytes import replace_with_bnb_linear + + with init_empty_weights(): + model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m")) + + quantization_config = BitsAndBytesConfig(load_in_8bit=True) + model = replace_with_bnb_linear( + model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config + ) + + model_path = hf_hub_download("bigscience/bloom-560m", "pytorch_model.bin") + + # test with auto + model = load_checkpoint_and_dispatch( + model, + checkpoint=model_path, + device_map="auto", + ) + + assert model.h[0].self_attention.query_key_value.weight.dtype == torch.int8 + assert model.h[0].self_attention.query_key_value.weight.device.index == 0 + + with init_empty_weights(): + model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m")) + + model = replace_with_bnb_linear( + model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config + ) + + # test with str device map + model = load_checkpoint_and_dispatch( + model, + checkpoint=model_path, + device_map={"": torch_device}, + ) + + assert model.h[0].self_attention.query_key_value.weight.dtype == torch.int8 + assert model.h[0].self_attention.query_key_value.weight.device.index == 0 + + with init_empty_weights(): + model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m")) + + model = replace_with_bnb_linear( + model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config + ) + + # test with torch.device device map + model = load_checkpoint_and_dispatch( + model, + checkpoint=model_path, + device_map={"": torch_device}, + ) + + assert model.h[0].self_attention.query_key_value.weight.dtype == torch.int8 + assert model.h[0].self_attention.query_key_value.weight.device.index == 0 + + @require_cuda_or_xpu + @slow + @require_bnb + def test_dipatch_model_fp4_simple(self): + """Tests that `dispatch_model` quantizes fp4 layers""" + from huggingface_hub import hf_hub_download + from transformers import AutoConfig, AutoModel, BitsAndBytesConfig + from transformers.utils.bitsandbytes import replace_with_bnb_linear + + with init_empty_weights(): + model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m")) + + quantization_config = BitsAndBytesConfig(load_in_4bit=True) + + model = replace_with_bnb_linear( + model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config + ) + + model_path = hf_hub_download("bigscience/bloom-560m", "pytorch_model.bin") + + # test with auto + model = load_checkpoint_and_dispatch( + model, + checkpoint=model_path, + device_map="auto", + ) + + assert model.h[0].self_attention.query_key_value.weight.dtype == torch.uint8 + assert model.h[0].self_attention.query_key_value.weight.device.index == 0 + + with init_empty_weights(): + model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m")) + + model = replace_with_bnb_linear( + model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config + ) + + # test with str device map + model = load_checkpoint_and_dispatch( + model, + checkpoint=model_path, + device_map={"": torch_device}, + ) + + assert model.h[0].self_attention.query_key_value.weight.dtype == torch.uint8 + assert model.h[0].self_attention.query_key_value.weight.device.index == 0 + + with init_empty_weights(): + model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m")) + + model = replace_with_bnb_linear( + model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config + ) + + # test with torch.device device map + model = load_checkpoint_and_dispatch( + model, + checkpoint=model_path, + device_map={"": torch_device}, + ) + + assert model.h[0].self_attention.query_key_value.weight.dtype == torch.uint8 + assert model.h[0].self_attention.query_key_value.weight.device.index == 0 diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_cli.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..56e6c6abe25c092cbeef116b2bb0dc67b98ad196 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_cli.py @@ -0,0 +1,643 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest +from pathlib import Path +from unittest.mock import patch + +import torch +from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError + +import accelerate.commands.test as accelerate_test_cmd +from accelerate.commands.config.config_args import BaseConfig, ClusterConfig, SageMakerConfig, load_config_from_file +from accelerate.commands.estimate import estimate_command, estimate_command_parser, gather_data +from accelerate.commands.launch import _validate_launch_command, launch_command, launch_command_parser +from accelerate.commands.to_fsdp2 import to_fsdp2_command, to_fsdp2_command_parser +from accelerate.commands.tpu import tpu_command_launcher, tpu_command_parser +from accelerate.test_utils.testing import ( + capture_call_output, + path_in_accelerate_package, + require_multi_device, + require_non_hpu, + require_timm, + require_transformers, + run_command, + run_first, +) +from accelerate.utils import patch_environment +from accelerate.utils.launch import prepare_simple_launcher_cmd_env + + +class AccelerateLauncherTester(unittest.TestCase): + """ + Test case for verifying the `accelerate launch` CLI operates correctly. + If a `default_config.yaml` file is located in the cache it will temporarily move it + for the duration of the tests. + """ + + test_file_path = path_in_accelerate_package("test_utils", "scripts", "test_cli.py") + notebook_launcher_path = path_in_accelerate_package("test_utils", "scripts", "test_notebook.py") + + config_folder = Path.home() / ".cache/huggingface/accelerate" + config_file = "default_config.yaml" + config_path = config_folder / config_file + changed_path = config_folder / "_default_config.yaml" + + test_config_path = Path("tests/test_configs") + parser = launch_command_parser() + + @classmethod + def setUpClass(cls): + if cls.config_path.is_file(): + cls.config_path.rename(cls.changed_path) + + @classmethod + def tearDownClass(cls): + if cls.changed_path.is_file(): + cls.changed_path.rename(cls.config_path) + + @run_first + def test_no_config(self): + args = ["--monitor_interval", "0.1", str(self.test_file_path)] + if torch.cuda.is_available() and (torch.cuda.device_count() > 1): + args = ["--multi_gpu"] + args + elif torch.xpu.is_available() and (torch.xpu.device_count() > 1): + args = ["--multi_gpu"] + args + args = self.parser.parse_args(["--monitor_interval", "0.1", str(self.test_file_path)]) + launch_command(args) + + @run_first + def test_config_compatibility(self): + invalid_configs = ["fp8", "invalid", "mpi", "sagemaker"] + for config in sorted(self.test_config_path.glob("**/*.yaml")): + if any(invalid_config in str(config) for invalid_config in invalid_configs): + continue + with self.subTest(config_file=config): + args = self.parser.parse_args(["--config_file", str(config), str(self.test_file_path)]) + launch_command(args) + + @run_first + def test_invalid_keys(self): + config_path = self.test_config_path / "invalid_keys.yaml" + with self.assertRaises( + ValueError, + msg="The config file at 'invalid_keys.yaml' had unknown keys ('another_invalid_key', 'invalid_key')", + ): + args = self.parser.parse_args(["--config_file", str(config_path), str(self.test_file_path)]) + launch_command(args) + + @run_first + def test_accelerate_test(self): + args = accelerate_test_cmd.test_command_parser().parse_args([]) + accelerate_test_cmd.test_command(args) + + @run_first + @require_non_hpu + @require_multi_device + def test_notebook_launcher(self): + """ + This test checks a variety of situations and scenarios + with the `notebook_launcher` + """ + cmd = ["python", self.notebook_launcher_path] + with patch_environment(omp_num_threads=1, accelerate_num_processes=2): + run_command(cmd) + + def test_mpi_multicpu_config_cmd(self): + """ + Parses a launch command with a test file and the 0_28_0_mpi.yaml config. Tests getting the command and + environment vars and verifies the mpirun command arg values. + """ + mpi_config_path = str(self.test_config_path / "0_28_0_mpi.yaml") + test_file_arg = "--cpu" + + with patch("sys.argv", ["accelerate", str(self.test_file_path), test_file_arg]): + parser = launch_command_parser() + args = parser.parse_args() + args.config_file = mpi_config_path + args, _, _ = _validate_launch_command(args) + + # Mock out the check for mpirun version to simulate Intel MPI + with patch("accelerate.utils.launch.which", return_value=True): + with patch("accelerate.utils.launch.subprocess.check_output", return_value=b"Intel MPI"): + cmd, _ = prepare_simple_launcher_cmd_env(args) + + # Verify the mpirun command args + expected_mpirun_cmd = ["mpirun", "-f", "/home/user/hostfile", "-ppn", "4", "-n", "16"] + self.assertGreater(len(cmd), len(expected_mpirun_cmd)) + generated_mpirun_cmd = cmd[0 : len(expected_mpirun_cmd)] + self.assertEqual(expected_mpirun_cmd, generated_mpirun_cmd) + + # Verify the python script and args in the mpirun command + python_script_cmd = cmd[len(expected_mpirun_cmd) :] + self.assertEqual(len(python_script_cmd), 3) + self.assertEqual(python_script_cmd[1], str(self.test_file_path)) + self.assertEqual(python_script_cmd[2], test_file_arg) + + def test_validate_launch_command(self): + """Test that the validation function combines args and defaults.""" + parser = launch_command_parser() + args = parser.parse_args( + [ + "--num-processes", + "2", + "--deepspeed_config_file", + "path/to/be/accepted", + "--config-file", + str(self.test_config_path / "validate_launch_cmd.yaml"), + "test.py", + ] + ) + self.assertFalse(args.debug) + self.assertTrue(args.fsdp_sync_module_states) + _validate_launch_command(args) + self.assertTrue(args.debug) + self.assertEqual(2, args.num_processes) + self.assertFalse(args.fsdp_sync_module_states) + self.assertEqual("path/to/be/accepted", args.deepspeed_config_file) + + +class LaunchArgTester(unittest.TestCase): + """ + Test cases revolving around the CLI wrappers + """ + + parser = launch_command_parser() + + def test_hyphen(self): + # Try a little from each cluster + args = ["--config-file", "test.yaml", "test.py"] + result = self.parser.parse_args(args) + assert result.config_file == "test.yaml" + assert result.multi_gpu is False + + args = ["--multi-gpu", "--num-processes", "4", "test.py"] + result = self.parser.parse_args(args) + assert result.multi_gpu is True + assert result.num_processes == 4 + # And use a mix + args = ["--multi-gpu", "--use-deepspeed", "--use-fsdp", "--num_processes", "4", "test.py"] + result = self.parser.parse_args(args) + assert result.multi_gpu is True + assert result.use_deepspeed is True + assert result.use_fsdp is True + assert result.num_processes == 4 + + def test_underscore(self): + # Try a little from each cluster + args = ["--config_file", "test.yaml", "test.py"] + result = self.parser.parse_args(args) + assert result.config_file == "test.yaml" + + args = ["--multi_gpu", "--num_processes", "4", "test.py"] + result = self.parser.parse_args(args) + assert result.multi_gpu is True + assert result.num_processes == 4 + # And use a mix + args = ["--multi_gpu", "--use_deepspeed", "--use_fsdp", "--num-processes", "4", "test.py"] + result = self.parser.parse_args(args) + assert result.multi_gpu is True + assert result.use_deepspeed is True + assert result.use_fsdp is True + assert result.num_processes == 4 + + def test_duplicate_entities(self): + help_return = self.parser.format_help() + args = self.parser.parse_args(["test.py"]) + for arg in args.__dict__: + if "_" in arg: + bad_arg = f"--{arg.replace('_', '-')}" + # Need an exception for `num-processes` since it's in the docstring + if bad_arg == "--num-processes": + assert help_return.count(bad_arg) == 1, f"Found {bad_arg} in `accelerate launch -h`" + else: + assert bad_arg not in help_return, f"Found {bad_arg} in `accelerate launch -h`" + + +class ClusterConfigTester(unittest.TestCase): + """ + Test case for verifying the config dataclasses work + """ + + test_config_path = Path("tests/test_configs") + + def test_base_config(self): + # Tests that all the dataclasses can be initialized + config = BaseConfig( + compute_environment="LOCAL_MACHINE", + distributed_type="NO", + mixed_precision="fp16", + debug=False, + use_cpu=False, + ) + + assert config.compute_environment == "LOCAL_MACHINE" + assert config.distributed_type == "NO" + assert config.mixed_precision == "fp16" + assert config.debug is False + + def test_cluster_config(self): + # First normally + config = ClusterConfig( + compute_environment="LOCAL_MACHINE", + distributed_type="NO", + mixed_precision="fp16", + num_processes=2, + debug=False, + use_cpu=False, + ) + + assert config.compute_environment == "LOCAL_MACHINE" + assert config.distributed_type == "NO" + assert config.mixed_precision == "fp16" + assert config.debug is False + + # Then check with other compute environments + config = ClusterConfig( + compute_environment="LOCAL_MACHINE", + distributed_type="MULTI_GPU", + mixed_precision="fp16", + debug=False, + num_processes=2, + enable_cpu_affinity=True, + use_cpu=False, + ) + + assert config.distributed_type == "MULTI_GPU" + assert config.num_processes == 2 + assert config.enable_cpu_affinity is True + + def test_sagemaker_config(self): + config = SageMakerConfig( + compute_environment="AMAZON_SAGEMAKER", + distributed_type="NO", + mixed_precision="fp16", + debug=False, + use_cpu=False, + ec2_instance_type="MY_TYPE", + iam_role_name="MY_ROLE", + ) + + assert config.compute_environment == "AMAZON_SAGEMAKER" + assert config.ec2_instance_type == "MY_TYPE" + assert config.iam_role_name == "MY_ROLE" + + config = load_config_from_file(str(self.test_config_path / "0_30_0_sagemaker.yaml")) + + +class TpuConfigTester(unittest.TestCase): + """ + Test case for verifying the `accelerate tpu-config` CLI passes the right `gcloud` command. + """ + + tpu_name = "test-tpu" + tpu_zone = "us-central1-a" + command = "ls" + cmd = ["accelerate", "tpu-config"] + base_output = "cd /usr/share" + command_file = "tests/test_samples/test_command_file.sh" + gcloud = "Running gcloud compute tpus tpu-vm ssh" + + def setUp(self): + self.parser = tpu_command_parser() + + def test_base(self): + args = self.parser.parse_args( + ["--command", self.command, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug"] + ) + output = capture_call_output(tpu_command_launcher, args) + assert f"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all" in output + + def test_base_backward_compatibility(self): + args = self.parser.parse_args( + [ + "--config_file", + "tests/test_configs/0_12_0.yaml", + "--command", + self.command, + "--tpu_zone", + self.tpu_zone, + "--tpu_name", + self.tpu_name, + "--debug", + ] + ) + output = capture_call_output(tpu_command_launcher, args) + assert f"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all" in output + + def test_with_config_file(self): + args = self.parser.parse_args(["--config_file", "tests/test_configs/latest.yaml", "--debug"]) + output = capture_call_output(tpu_command_launcher, args) + assert ( + f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all' + in output + ) + + def test_with_config_file_and_command(self): + args = self.parser.parse_args( + ["--config_file", "tests/test_configs/latest.yaml", "--command", self.command, "--debug"] + ) + output = capture_call_output(tpu_command_launcher, args) + assert f"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all" in output + + def test_with_config_file_and_multiple_command(self): + args = self.parser.parse_args( + [ + "--config_file", + "tests/test_configs/latest.yaml", + "--command", + self.command, + "--command", + 'echo "Hello World"', + "--debug", + ] + ) + output = capture_call_output(tpu_command_launcher, args) + assert ( + f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo "Hello World" --worker all' + in output + ) + + def test_with_config_file_and_command_file(self): + args = self.parser.parse_args( + ["--config_file", "tests/test_configs/latest.yaml", "--command_file", self.command_file, "--debug"] + ) + output = capture_call_output(tpu_command_launcher, args) + assert ( + f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all' + in output + ) + + def test_with_config_file_and_command_file_backward_compatibility(self): + args = self.parser.parse_args( + [ + "--config_file", + "tests/test_configs/0_12_0.yaml", + "--command_file", + self.command_file, + "--tpu_zone", + self.tpu_zone, + "--tpu_name", + self.tpu_name, + "--debug", + ] + ) + output = capture_call_output(tpu_command_launcher, args) + assert ( + f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all' + in output + ) + + def test_accelerate_install(self): + args = self.parser.parse_args( + ["--config_file", "tests/test_configs/latest.yaml", "--install_accelerate", "--debug"] + ) + output = capture_call_output(tpu_command_launcher, args) + assert ( + f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo "hello world"; echo "this is a second command" --worker all' + in output + ) + + def test_accelerate_install_version(self): + args = self.parser.parse_args( + [ + "--config_file", + "tests/test_configs/latest.yaml", + "--install_accelerate", + "--accelerate_version", + "12.0.0", + "--debug", + ] + ) + output = capture_call_output(tpu_command_launcher, args) + assert ( + f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo "hello world"; echo "this is a second command" --worker all' + in output + ) + + +class ModelEstimatorTester(unittest.TestCase): + """ + Test case for checking the output of `accelerate estimate-memory` is correct. + + - Uses `estimate_command` when trying to catch raised errors + - Uses `gather_data` when just verifying the calculations are correct + """ + + parser = estimate_command_parser() + + def test_invalid_model_name(self): + with self.assertRaises( + RepositoryNotFoundError, msg="Repo for model `somebrokenname` does not exist on the Hub" + ): + args = self.parser.parse_args(["somebrokenname"]) + estimate_command(args) + + @require_timm + def test_invalid_model_name_timm(self): + with self.assertRaises(RuntimeError, msg="Tried to load `muellerzr/dummy` with `timm` but"): + args = self.parser.parse_args(["muellerzr/dummy", "--library_name", "timm"]) + estimate_command(args) + + @require_transformers + def test_invalid_model_name_transformers(self): + with self.assertRaises(RuntimeError, msg="Tried to load `muellerzr/dummy` with `transformers` but"): + args = self.parser.parse_args(["muellerzr/dummy", "--library_name", "transformers"]) + estimate_command(args) + + def test_no_metadata(self): + with self.assertRaises( + ValueError, msg="Model `muellerzr/dummy` does not have any library metadata on the Hub" + ): + args = self.parser.parse_args(["muellerzr/dummy"]) + estimate_command(args) + + def test_gated(self): + with self.assertRaises( + (GatedRepoError, EnvironmentError), + msg="Repo for model `meta-llama/Llama-2-7b-hf` is gated or environment error occurred", + ): + args = self.parser.parse_args(["meta-llama/Llama-2-7b-hf"]) + with patch_environment(hf_hub_disable_implicit_token="1"): + estimate_command(args) + + @require_transformers + def test_remote_code(self): + # Also tests that custom `Auto` classes work + args = self.parser.parse_args(["hf-internal-testing/test_dynamic_model"]) + with self.assertRaises(ValueError, msg="--trust_remote_code"): + gather_data(args) + + # Verify it works with the flag + args = self.parser.parse_args(["hf-internal-testing/test_dynamic_model", "--trust_remote_code"]) + gather_data(args) + + @require_transformers + def test_explicit_dtypes(self): + args = self.parser.parse_args(["bert-base-cased", "--dtypes", "float32", "float16"]) + output = gather_data(args) + # The largest layer and total size of the model in bytes + largest_layer, total_size = 90669056, 433249280 + # Check that full precision -> int4 is calculating correctly + assert len(output) == 2, f"Output was missing a precision, expected 2 but received {len(output)}" + + for i, factor in enumerate([1, 2]): + precision = 32 // factor + precision_str = f"float{precision}" + largest_layer_estimate = largest_layer / factor + total_size_estimate = total_size / factor + total_training_size_estimate = total_size_estimate * 4 + + assert precision_str == output[i][0], f"Output is missing precision `{precision_str}`" + assert largest_layer_estimate == output[i][1], ( + f"Calculation for largest layer size in `{precision_str}` is incorrect." + ) + + assert total_size_estimate == output[i][2], ( + f"Calculation for total size in `{precision_str}` is incorrect." + ) + assert total_training_size_estimate == max(output[i][3].values()), ( + f"Calculation for total training size in `{precision_str}` is incorrect." + ) + + @require_transformers + def test_transformers_model(self): + args = self.parser.parse_args(["bert-base-cased", "--dtypes", "float32"]) + output = gather_data(args) + # The largest layer and total size of the model in bytes + largest_layer, total_size = 90669056, 433249280 + assert largest_layer == output[0][1], ( + f"Calculation for largest layer size in `fp32` is incorrect, expected {largest_layer} but received {output[0][1]}" + ) + assert total_size == output[0][2], ( + f"Calculation for total size in `fp32` is incorrect, expected {total_size} but received {output[0][2]}" + ) + + @require_transformers + def test_no_split_modules(self): + # idefics-80b-instruct has ["IdeficsDecoderLayer", "IdeficsGatedCrossAttentionLayer"] + args = self.parser.parse_args(["HuggingFaceM4/idefics-80b-instruct", "--dtypes", "float32"]) + output = gather_data(args) + # without factoring in `no_split` modules, the largest layer is 721420288 bytes + assert output[0][1] != 721420288, "Largest layer calculation incorrect, did not factor in `no_split` modules." + # the real answer is 3240165632 bytes + assert output[0][1] == 3240165632 + + @require_timm + def test_timm_model(self): + args = self.parser.parse_args(["timm/resnet50.a1_in1k", "--library_name", "timm"]) + output = gather_data(args) + # The largest layer and total size of the model in bytes + largest_layer, total_size = 9437184, 102441032 + assert largest_layer == output[0][1], ( + f"Calculation for largest layer size in `fp32` is incorrect, expected {largest_layer} but received {output[0][1]}" + ) + assert total_size == output[0][2], ( + f"Calculation for total size in `fp32` is incorrect, expected {total_size} but received {output[0][2]}" + ) + + +class ToFSDP2Tester(unittest.TestCase): + """ + Test case for verifying the `accelerate to-fsdp2` CLI outputs. + """ + + parser = to_fsdp2_command_parser() + test_config_path = Path("tests/test_configs") + + @classmethod + def setUpClass(cls): + if (cls.test_config_path / "latest_fsdp.yaml").exists(): + cls.original_config = load_config_from_file(str(cls.test_config_path / "latest_fsdp.yaml")) + + @classmethod + def tearDownClass(cls): + if cls.original_config is not None: + cls.original_config.to_yaml_file(str(cls.test_config_path / "latest_fsdp.yaml")) + + def tearDown(self): + if (self.test_config_path / "output.yaml").exists(): + (self.test_config_path / "output.yaml").unlink() + + def test_nonexistent_config_file(self): + with self.assertRaises(FileNotFoundError, msg="Config file `nonexistent.yaml` not found"): + args = self.parser.parse_args(["--config_file", "nonexistent.yaml"]) + to_fsdp2_command(args) + + def test_no_output_without_overwrite(self): + with self.assertRaises(ValueError, msg="If --overwrite is not set, --output_file must be provided"): + args = self.parser.parse_args(["--config_file", str(self.test_config_path / "latest_fsdp.yaml")]) + to_fsdp2_command(args) + + @patch("pathlib.Path.exists") + def test_overwrite_when_output_file_exists(self, mock_exists): + mock_exists.side_effect = ( + lambda: str(mock_exists._mock_self) == "output.yaml" or mock_exists._mock_self.exists() + ) + + with self.assertRaises( + FileExistsError, msg="Output file `output.yaml` already exists and --overwrite is not set" + ): + args = self.parser.parse_args( + ["--config_file", str(self.test_config_path / "latest_fsdp.yaml"), "--output_file", "output.yaml"] + ) + to_fsdp2_command(args) + + def test_fsdp2_config(self): + args = self.parser.parse_args( + [ + "--config_file", + str(self.test_config_path / "latest_fsdp.yaml"), + "--output_file", + str(self.test_config_path / "output.yaml"), + ] + ) + to_fsdp2_command(args) + + config = load_config_from_file(str(self.test_config_path / "output.yaml")) + assert isinstance(config, ClusterConfig) + assert config.fsdp_config["fsdp_version"] == 2 + + def test_config_already_fsdp2(self): + args = self.parser.parse_args( + [ + "--config_file", + str(self.test_config_path / "latest_fsdp.yaml"), + "--output_file", + str(self.test_config_path / "output.yaml"), + ] + ) + + mock_config = {"fsdp_config": {"fsdp_version": 2}} + + with patch("accelerate.commands.to_fsdp2.load_config", return_value=mock_config): + with self.assertLogs(level="WARNING") as cm: + to_fsdp2_command(args) + + assert "Config already specfies FSDP2, skipping conversion..." in cm.output[0] + + # Has to be the last test because it overwrites the config file + def test_fsdp2_overwrite(self): + args = self.parser.parse_args( + [ + "--config_file", + str(self.test_config_path / "latest_fsdp.yaml"), + "--overwrite", + ] + ) + to_fsdp2_command(args) + + config = load_config_from_file(str(self.test_config_path / "latest_fsdp.yaml")) + assert isinstance(config, ClusterConfig) + assert config.fsdp_config["fsdp_version"] == 2 diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_compile.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b63b84bda72df929a750f1ff4bb7c85b308c37 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_compile.py @@ -0,0 +1,145 @@ +# Copyright 2025 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import unittest + +import torch +from torch.utils.benchmark import Timer + +from accelerate.test_utils import require_huggingface_suite, require_non_cpu, require_non_hpu, slow, torch_device +from accelerate.utils import compile_regions, extract_model_from_parallel, release_memory + + +MODEL_ID = "gpt2" + +COMPILE_ITERS = 2 +INFERENCE_ITERS = 100 + +INFRENCE_STMT = "model(input_ids, use_cache=False)" +COMPILE_STMT = f"torch._dynamo.reset(); torch._inductor.utils.clear_inductor_caches(); {INFRENCE_STMT}" + +if torch_device == "hpu": + backend = "hpu_backend" +else: + backend = "inductor" + + +@require_huggingface_suite +class RegionalCompilationTester(unittest.TestCase): + def _get_model_and_inputs(self): + from transformers import AutoConfig, AutoModelForCausalLM + + with torch.device(torch_device): + config = AutoConfig.from_pretrained(MODEL_ID) + model = AutoModelForCausalLM.from_config(config) + input_ids = torch.randint(0, 1000, (4, 128), dtype=torch.int64) + + return model, input_ids + + def test_regions_are_compiled(self): + model, _ = self._get_model_and_inputs() + compiled_model = compile_regions(model, mode="reduce-overhead", backend=backend) + + # Check that the compiled model keeps a reference to the original model + assert hasattr(compiled_model, "_orig_mod") + assert compiled_model._orig_mod is model + + # Check that the compiled_model.transformer.h[i] and compiled_model.lm_head are compiled separately + assert isinstance(compiled_model.transformer.h[0], torch._dynamo.eval_frame.OptimizedModule) + assert isinstance(compiled_model.lm_head, torch._dynamo.eval_frame.OptimizedModule) + assert compiled_model.transformer.h[0]._orig_mod is model.transformer.h[0] + assert compiled_model.lm_head._orig_mod is model.lm_head + + def test_extract_model_keep_torch_compile(self): + model, _ = self._get_model_and_inputs() + compiled_model = compile_regions(model, mode="reduce-overhead", backend=backend) + + distributed_model = torch.nn.parallel.DataParallel(model) + distributed_compiled_model = compile_regions(distributed_model, mode="reduce-overhead", backend=backend) + compiled_model_unwrapped = extract_model_from_parallel(distributed_compiled_model, keep_torch_compile=True) + + assert compiled_model._orig_mod is compiled_model_unwrapped._orig_mod + + def test_extract_model_remove_torch_compile(self): + model, _ = self._get_model_and_inputs() + compiled_model = compile_regions(model, mode="reduce-overhead", backend=backend) + + distributed_model = torch.nn.parallel.DataParallel(model) + distributed_compiled_model = compile_regions(distributed_model, mode="reduce-overhead", backend=backend) + compiled_model_unwrapped = extract_model_from_parallel(distributed_compiled_model, keep_torch_compile=False) + + assert compiled_model._orig_mod is compiled_model_unwrapped + + @require_non_cpu + @require_huggingface_suite + def test_regional_compilation_cold_start(self): + model, input_ids = self._get_model_and_inputs() + + regional_compilation_model = compile_regions(model, backend=backend) + regional_compilation_cold_start = ( + Timer(stmt=COMPILE_STMT, globals={"model": regional_compilation_model, "input_ids": input_ids}) + .timeit(COMPILE_ITERS) + .median + ) + + full_compilation_model = torch.compile(model, backend=backend) + full_compilation_cold_start = ( + Timer(stmt=COMPILE_STMT, globals={"model": full_compilation_model, "input_ids": input_ids}) + .timeit(COMPILE_ITERS) + .median + ) + + self.assertLess( + regional_compilation_cold_start, + full_compilation_cold_start, + "Regional compilation should have a faster cold start than full compilation", + ) + + release_memory(model, full_compilation_model, regional_compilation_model) + + @slow + @require_non_hpu + @require_non_cpu + @require_huggingface_suite + def test_regional_compilation_inference_speedup(self): + model, input_ids = self._get_model_and_inputs() + + baseline_inference_latency = ( + Timer(stmt=INFRENCE_STMT, globals={"model": model, "input_ids": input_ids}).timeit(INFERENCE_ITERS).median + ) + + regional_compilation_model = compile_regions(model, backend=backend) + regional_compilation_inference_latency = ( + Timer(stmt=INFRENCE_STMT, globals={"model": regional_compilation_model, "input_ids": input_ids}) + .timeit(INFERENCE_ITERS) + .median + ) + + full_compilation_model = torch.compile(model, backend=backend) + full_compilation_inference_latency = ( + Timer(stmt=INFRENCE_STMT, globals={"model": full_compilation_model, "input_ids": input_ids}) + .timeit(INFERENCE_ITERS) + .median + ) + + full_compilation_inference_speedup = baseline_inference_latency / full_compilation_inference_latency + regional_compilation_inference_speedup = baseline_inference_latency / regional_compilation_inference_latency + + self.assertAlmostEqual( + regional_compilation_inference_speedup, + full_compilation_inference_speedup, + delta=0.1, + msg="Regional compilation should have a similar speedup to full compilation", + ) + + release_memory(model, full_compilation_model, regional_compilation_model) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/0_11_0.yaml b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/0_11_0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9ef829e6b53811462f6ffc457312b48e2055ffad --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/0_11_0.yaml @@ -0,0 +1,12 @@ +compute_environment: LOCAL_MACHINE +deepspeed_config: {} +distributed_type: 'NO' +fsdp_config: {} +machine_rank: 0 +main_process_ip: null +main_process_port: null +main_training_function: main +mixed_precision: 'no' +num_machines: 1 +num_processes: 1 +use_cpu: false \ No newline at end of file diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/0_12_0.yaml b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/0_12_0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..00d06aab98f2a5489d7a1505dc8e1107fcc20762 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/0_12_0.yaml @@ -0,0 +1,13 @@ +compute_environment: LOCAL_MACHINE +deepspeed_config: {} +distributed_type: 'NO' +downcast_bf16: 'no' +fsdp_config: {} +machine_rank: 0 +main_process_ip: null +main_process_port: null +main_training_function: main +mixed_precision: 'no' +num_machines: 1 +num_processes: 1 +use_cpu: false \ No newline at end of file diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/0_28_0_mpi.yaml b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/0_28_0_mpi.yaml new file mode 100644 index 0000000000000000000000000000000000000000..afb05eb25798d4eb8acd2c936197a8e3921fa912 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/0_28_0_mpi.yaml @@ -0,0 +1,22 @@ +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: MULTI_CPU +downcast_bf16: 'no' +ipex_config: + ipex: true +machine_rank: 0 +main_process_ip: 127.0.0.1 +main_process_port: 29500 +main_training_function: main +mixed_precision: 'no' +mpirun_config: + mpirun_ccl: '1' + mpirun_hostfile: /home/user/hostfile +num_machines: 4 +num_processes: 16 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: true diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/0_30_0_sagemaker.yaml b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/0_30_0_sagemaker.yaml new file mode 100644 index 0000000000000000000000000000000000000000..197055fe6da5af66c365b01d5db0b50593a94db8 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/0_30_0_sagemaker.yaml @@ -0,0 +1,8 @@ +compute_environment: AMAZON_SAGEMAKER +debug: false +distributed_type: NO +mixed_precision: fp16 +debug: false +use_cpu: false +ec2_instance_type: MY_TYPE +iam_role_name: MY_ROLE diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/0_34_0_fp8.yaml b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/0_34_0_fp8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4c414b004789d347f2a59e2d5e7f0bc0a0b4b514 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/0_34_0_fp8.yaml @@ -0,0 +1,26 @@ +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: MULTI_GPU +downcast_bf16: 'no' +enable_cpu_affinity: false +fp8_config: + amax_compute_algo: max + amax_history_len: 1024 + backend: TE + fp8_format: E4M3 + interval: 1 + margin: 0 + override_linear_precision: (false, false, false) + use_autocast_during_eval: false +gpu_ids: all +machine_rank: 0 +main_training_function: main +mixed_precision: fp8 +num_machines: 1 +num_processes: 2 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/README.md b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fd88d066c5dfdb82fe5067a8c5644fffa3054d99 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/README.md @@ -0,0 +1,2 @@ +This folder contains test configs for `accelerate config`. These should be generated for each major version +and are written based on `accelerate config` and selecting the "No distributed training" option. \ No newline at end of file diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/invalid_keys.yaml b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/invalid_keys.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3e58ce77be655709f12a95c4935c391e1cc077c2 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/invalid_keys.yaml @@ -0,0 +1,15 @@ +compute_environment: LOCAL_MACHINE +deepspeed_config: {} +distributed_type: 'NO' +downcast_bf16: 'no' +fsdp_config: {} +machine_rank: 0 +main_process_ip: null +main_process_port: null +main_training_function: main +mixed_precision: 'no' +num_machines: 1 +num_processes: 1 +use_cpu: false +invalid_key: "invalid_value" +another_invalid_key: "another_invalid_value" \ No newline at end of file diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/latest.yaml b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/latest.yaml new file mode 100644 index 0000000000000000000000000000000000000000..456348ef9e6d01326d727b71c1dddd4177f89861 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/latest.yaml @@ -0,0 +1,21 @@ +compute_environment: LOCAL_MACHINE +deepspeed_config: {} +distributed_type: 'NO' +downcast_bf16: 'no' +fsdp_config: {} +gpu_ids: all +machine_rank: 0 +main_process_ip: null +main_process_port: null +main_training_function: main +megatron_lm_config: {} +mixed_precision: 'no' +num_machines: 1 +num_processes: 1 +rdzv_backend: static +same_network: true +use_cpu: false +tpu_name: 'test-tpu' +tpu_zone: 'us-central1-a' +commands: null +command_file: tests/test_samples/test_command_file.sh \ No newline at end of file diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/latest_fsdp.yaml b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/latest_fsdp.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d66c0ca1a972e7731d618f6553f6561acf2c5d21 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/latest_fsdp.yaml @@ -0,0 +1,29 @@ +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: FSDP +downcast_bf16: 'no' +enable_cpu_affinity: false +fsdp_config: + fsdp_activation_checkpointing: false + fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP + fsdp_backward_prefetch: BACKWARD_PRE + fsdp_cpu_ram_efficient_loading: true + fsdp_forward_prefetch: false + fsdp_offload_params: false + fsdp_sharding_strategy: FULL_SHARD + fsdp_state_dict_type: SHARDED_STATE_DICT + fsdp_sync_module_states: true + fsdp_transformer_layer_cls_to_wrap: BertLayer + fsdp_use_orig_params: true + fsdp_ignored_modules: null +machine_rank: 0 +main_training_function: main +mixed_precision: 'no' +num_machines: 1 +num_processes: 1 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/validate_launch_cmd.yaml b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/validate_launch_cmd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8f01f9faba0dd62020914ed8ff62a7c8c8f99820 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_configs/validate_launch_cmd.yaml @@ -0,0 +1,8 @@ +compute_environment: LOCAL_MACHINE +debug: true +num_processes: 1 +distributed_type: 'NO' +fsdp_config: + fsdp_sync_module_states: false +deepspeed_config: + deepspeed_config_file: path/to/be/ignored diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_cpu.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_cpu.py new file mode 100644 index 0000000000000000000000000000000000000000..d328575a181e79dc3ae231e10aa16ebe4db4bfc7 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_cpu.py @@ -0,0 +1,27 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +from accelerate import debug_launcher +from accelerate.test_utils import require_cpu, test_ops, test_script + + +@require_cpu +class MultiCPUTester(unittest.TestCase): + def test_cpu(self): + debug_launcher(test_script.main) + + def test_ops(self): + debug_launcher(test_ops.main) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_data_loader.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_data_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..afb4b27db4e61fe710cb1a1b197c4baea2aaacaf --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_data_loader.py @@ -0,0 +1,897 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import random +import weakref + +import pytest +import torch +from parameterized import parameterized +from torch.utils.data import BatchSampler, DataLoader, IterableDataset + +from accelerate import Accelerator, PartialState +from accelerate.data_loader import ( + BatchSamplerShard, + DataLoaderDispatcher, + DataLoaderShard, + DataLoaderStateMixin, + IterableDatasetShard, + SkipBatchSampler, + SkipDataLoader, + prepare_data_loader, + skip_first_batches, +) +from accelerate.state import GradientState +from accelerate.test_utils.testing import AccelerateTestCase, require_torchdata_stateful_dataloader +from accelerate.utils import is_torchdata_stateful_dataloader_available, set_seed + + +if is_torchdata_stateful_dataloader_available(): + from torchdata.stateful_dataloader import ( + StatefulDataLoader, + ) + + +def parameterized_custom_name_func(func, param_num, param): + # customize the test name generator function as we want both params to appear in the sub-test + # name, as by default it shows only the first param + param_based_name = f"num_workers_{param.args[0]}" + return f"{func.__name__}_{param_based_name}" + + +class RandomIterableDataset(IterableDataset): + # For testing, an iterable dataset of random length + def __init__(self, p_stop=0.01, max_length=1000): + self.p_stop = p_stop + self.max_length = max_length + + def __iter__(self): + count = 0 + stop = False + while not stop and count < self.max_length: + yield count + count += 1 + stop = random.random() < self.p_stop + + +class SimpleIterableDataset(IterableDataset): + def __init__(self, num_samples=1000): + self.num_samples = num_samples + + def __iter__(self): + for _ in range(self.num_samples): + yield torch.rand(1) + + def __len__(self): + return self.num_samples + + def set_epoch(self, epoch): + self.epoch = epoch + + +class SimpleBatchSampler(BatchSampler): + def __init__(self, sampler, batch_size, drop_last, generator, seed): + super().__init__(sampler, batch_size, drop_last) + self.generator = generator + self.seed = seed + self.epoch = 0 + + def __iter__(self): + self.generator.manual_seed(self.seed + self.epoch) + return super().__iter__() + + def set_epoch(self, epoch): + self.epoch = epoch + + +class DataLoaderTester(AccelerateTestCase): + def check_batch_sampler_shards(self, batch_sampler, expected, split_batches=False, even_batches=True): + batch_sampler_shards = [ + BatchSamplerShard(batch_sampler, 2, i, split_batches=split_batches, even_batches=even_batches) + for i in range(2) + ] + batch_sampler_lists = [list(batch_sampler_shard) for batch_sampler_shard in batch_sampler_shards] + if not split_batches: + assert [len(shard) for shard in batch_sampler_shards] == [len(e) for e in expected] + assert batch_sampler_lists == expected + + def test_batch_sampler_shards_with_no_splits(self): + # Check the shards when the dataset is a round multiple of total batch size. + batch_sampler = BatchSampler(range(24), batch_size=3, drop_last=False) + expected = [ + [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], + [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], + ] + self.check_batch_sampler_shards(batch_sampler, expected) + + batch_sampler = BatchSampler(range(24), batch_size=3, drop_last=True) + # Expected shouldn't change + self.check_batch_sampler_shards(batch_sampler, expected) + + # Check the shards when the dataset is a round multiple of batch size but not total batch size. + batch_sampler = BatchSampler(range(21), batch_size=3, drop_last=False) + expected = [ + [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], + [[3, 4, 5], [9, 10, 11], [15, 16, 17], [0, 1, 2]], + ] + self.check_batch_sampler_shards(batch_sampler, expected) + + batch_sampler = BatchSampler(range(21), batch_size=3, drop_last=True) + expected = [ + [[0, 1, 2], [6, 7, 8], [12, 13, 14]], + [[3, 4, 5], [9, 10, 11], [15, 16, 17]], + ] + self.check_batch_sampler_shards(batch_sampler, expected) + + # Check the shards when the dataset is not a round multiple of batch size but has a multiple of + # num_processes batch. + batch_sampler = BatchSampler(range(22), batch_size=3, drop_last=False) + expected = [ + [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], + [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 0, 1]], + ] + self.check_batch_sampler_shards(batch_sampler, expected) + + batch_sampler = BatchSampler(range(22), batch_size=3, drop_last=True) + expected = [ + [[0, 1, 2], [6, 7, 8], [12, 13, 14]], + [[3, 4, 5], [9, 10, 11], [15, 16, 17]], + ] + self.check_batch_sampler_shards(batch_sampler, expected) + + # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of + # num_processes batch. + batch_sampler = BatchSampler(range(20), batch_size=3, drop_last=False) + expected = [ + [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 0]], + [[3, 4, 5], [9, 10, 11], [15, 16, 17], [1, 2, 3]], + ] + self.check_batch_sampler_shards(batch_sampler, expected) + + batch_sampler = BatchSampler(range(20), batch_size=3, drop_last=True) + expected = [ + [[0, 1, 2], [6, 7, 8], [12, 13, 14]], + [[3, 4, 5], [9, 10, 11], [15, 16, 17]], + ] + self.check_batch_sampler_shards(batch_sampler, expected) + + # Check the shards when the dataset is very small. + batch_sampler = BatchSampler(range(2), batch_size=3, drop_last=False) + expected = [[[0, 1, 0]], [[1, 0, 1]]] + self.check_batch_sampler_shards(batch_sampler, expected) + + batch_sampler = BatchSampler(range(2), batch_size=3, drop_last=True) + expected = [[], []] + self.check_batch_sampler_shards(batch_sampler, expected) + + def test_batch_sampler_shards_with_splits(self): + # Check the shards when the dataset is a round multiple of batch size. + batch_sampler = BatchSampler(range(24), batch_size=4, drop_last=False) + expected = [ + [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], + [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], + ] + self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True) + + batch_sampler = BatchSampler(range(24), batch_size=4, drop_last=True) + # Expected shouldn't change + self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True) + + # Check the shards when the dataset is not a round multiple of batch size. + batch_sampler = BatchSampler(range(22), batch_size=4, drop_last=False) + expected = [ + [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], + [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [0, 1]], + ] + self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True) + + batch_sampler = BatchSampler(range(22), batch_size=4, drop_last=True) + expected = [ + [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], + [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], + ] + self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True) + + # Check the shards when the dataset is not a round multiple of batch size or num_processes. + batch_sampler = BatchSampler(range(21), batch_size=4, drop_last=False) + expected = [ + [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 0]], + [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [1, 2]], + ] + self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True) + + batch_sampler = BatchSampler(range(21), batch_size=4, drop_last=True) + expected = [ + [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], + [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], + ] + self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True) + + # Check the shards when the dataset is very small. + batch_sampler = BatchSampler(range(2), batch_size=4, drop_last=False) + expected = [[[0, 1]], [[0, 1]]] + self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True) + + batch_sampler = BatchSampler(range(2), batch_size=4, drop_last=True) + expected = [[], []] + self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True) + + def test_batch_sampler_shards_with_no_splits_no_even(self): + # Check the shards when the dataset is a round multiple of total batch size. + batch_sampler = BatchSampler(range(24), batch_size=3, drop_last=False) + expected = [ + [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], + [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], + ] + self.check_batch_sampler_shards(batch_sampler, expected, even_batches=False) + + batch_sampler = BatchSampler(range(24), batch_size=3, drop_last=True) + # Expected shouldn't change + self.check_batch_sampler_shards(batch_sampler, expected, even_batches=False) + + # Check the shards when the dataset is a round multiple of batch size but not total batch size. + batch_sampler = BatchSampler(range(21), batch_size=3, drop_last=False) + expected = [ + [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], + [[3, 4, 5], [9, 10, 11], [15, 16, 17]], + ] + self.check_batch_sampler_shards(batch_sampler, expected, even_batches=False) + + batch_sampler = BatchSampler(range(21), batch_size=3, drop_last=True) + expected = [ + [[0, 1, 2], [6, 7, 8], [12, 13, 14]], + [[3, 4, 5], [9, 10, 11], [15, 16, 17]], + ] + self.check_batch_sampler_shards(batch_sampler, expected, even_batches=False) + + # Check the shards when the dataset is not a round multiple of batch size but has a multiple of + # num_processes batch. + batch_sampler = BatchSampler(range(22), batch_size=3, drop_last=False) + expected = [ + [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], + [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21]], + ] + self.check_batch_sampler_shards(batch_sampler, expected, even_batches=False) + + batch_sampler = BatchSampler(range(22), batch_size=3, drop_last=True) + expected = [ + [[0, 1, 2], [6, 7, 8], [12, 13, 14]], + [[3, 4, 5], [9, 10, 11], [15, 16, 17]], + ] + self.check_batch_sampler_shards(batch_sampler, expected, even_batches=False) + + # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of + # num_processes batch. + batch_sampler = BatchSampler(range(20), batch_size=3, drop_last=False) + expected = [ + [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19]], + [[3, 4, 5], [9, 10, 11], [15, 16, 17]], + ] + self.check_batch_sampler_shards(batch_sampler, expected, even_batches=False) + + batch_sampler = BatchSampler(range(20), batch_size=3, drop_last=True) + expected = [ + [[0, 1, 2], [6, 7, 8], [12, 13, 14]], + [[3, 4, 5], [9, 10, 11], [15, 16, 17]], + ] + self.check_batch_sampler_shards(batch_sampler, expected, even_batches=False) + + # Check the shards when the dataset is very small. + batch_sampler = BatchSampler(range(2), batch_size=3, drop_last=False) + expected = [[[0, 1]], []] + self.check_batch_sampler_shards(batch_sampler, expected, even_batches=False) + + batch_sampler = BatchSampler(range(2), batch_size=3, drop_last=True) + expected = [[], []] + self.check_batch_sampler_shards(batch_sampler, expected, even_batches=False) + + def test_batch_sampler_shards_with_splits_no_even(self): + # Check the shards when the dataset is a round multiple of batch size. + batch_sampler = BatchSampler(range(24), batch_size=4, drop_last=False) + expected = [ + [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], + [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], + ] + self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True, even_batches=False) + + batch_sampler = BatchSampler(range(24), batch_size=4, drop_last=True) + # Expected shouldn't change + self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True, even_batches=False) + + # Check the shards when the dataset is not a round multiple of batch size. + batch_sampler = BatchSampler(range(22), batch_size=4, drop_last=False) + expected = [ + [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], + [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], + ] + self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True, even_batches=False) + + batch_sampler = BatchSampler(range(22), batch_size=4, drop_last=True) + expected = [ + [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], + [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], + ] + self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True, even_batches=False) + + # Check the shards when the dataset is not a round multiple of batch size or num_processes. + batch_sampler = BatchSampler(range(21), batch_size=4, drop_last=False) + expected = [ + [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20]], + [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], + ] + self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True, even_batches=False) + + batch_sampler = BatchSampler(range(21), batch_size=4, drop_last=True) + expected = [ + [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], + [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], + ] + self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True, even_batches=False) + + # Check the shards when the dataset is very small. + batch_sampler = BatchSampler(range(2), batch_size=4, drop_last=False) + expected = [[[0, 1]], []] + self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True, even_batches=False) + + batch_sampler = BatchSampler(range(2), batch_size=4, drop_last=True) + expected = [[], []] + self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True, even_batches=False) + + def test_batch_sampler_with_varying_batch_size(self): + batch_sampler = [[0, 1, 2], [3, 4], [5, 6, 7, 8], [9, 10, 11], [12, 13]] + batch_sampler_shards = [BatchSamplerShard(batch_sampler, 2, i, even_batches=False) for i in range(2)] + + assert len(batch_sampler_shards[0]) == 3 + assert len(batch_sampler_shards[1]) == 2 + + assert list(batch_sampler_shards[0]) == [[0, 1, 2], [5, 6, 7, 8], [12, 13]] + assert list(batch_sampler_shards[1]) == [[3, 4], [9, 10, 11]] + + def check_iterable_dataset_shards( + self, dataset, seed, batch_size, drop_last=False, num_processes=2, split_batches=False + ): + random.seed(seed) + reference = list(dataset) + + iterable_dataset_shards = [ + IterableDatasetShard( + dataset, + batch_size=batch_size, + drop_last=drop_last, + num_processes=num_processes, + process_index=i, + split_batches=split_batches, + ) + for i in range(num_processes) + ] + iterable_dataset_lists = [] + for iterable_dataset_shard in iterable_dataset_shards: + # Since our random iterable dataset will be... random... we need to use a seed to get reproducible results. + random.seed(seed) + iterable_dataset_lists.append(list(iterable_dataset_shard)) + + shard_batch_size = batch_size // num_processes if split_batches else batch_size + # All iterable dataset shard should have the same length, a round multiple of shard_batch_size + first_list = iterable_dataset_lists[0] + for l in iterable_dataset_lists[1:]: + assert len(l) == len(first_list) + assert (len(l) % shard_batch_size) == 0 + + observed = [] + for idx in range(0, len(first_list), shard_batch_size): + for l in iterable_dataset_lists: + observed += l[idx : idx + shard_batch_size] + + if not drop_last: + while len(reference) < len(observed): + reference += reference + assert observed == reference[: len(observed)] + + def test_iterable_dataset_shard(self): + seed = 42 + dataset = RandomIterableDataset() + + self.check_iterable_dataset_shards(dataset, seed, batch_size=4, drop_last=False, split_batches=False) + self.check_iterable_dataset_shards(dataset, seed, batch_size=4, drop_last=True, split_batches=False) + self.check_iterable_dataset_shards(dataset, seed, batch_size=4, drop_last=False, split_batches=True) + self.check_iterable_dataset_shards(dataset, seed, batch_size=4, drop_last=True, split_batches=True) + + # Edge case with a very small dataset + dataset = RandomIterableDataset(max_length=2) + + self.check_iterable_dataset_shards(dataset, seed, batch_size=4, drop_last=False, split_batches=False) + self.check_iterable_dataset_shards(dataset, seed, batch_size=4, drop_last=True, split_batches=False) + self.check_iterable_dataset_shards(dataset, seed, batch_size=4, drop_last=False, split_batches=True) + self.check_iterable_dataset_shards(dataset, seed, batch_size=4, drop_last=True, split_batches=True) + + def test_iterable_dataset_using_none_batch_size(self): + dataset = SimpleIterableDataset(100) + dataloader = DataLoader(dataset, batch_size=None) + dataloader = prepare_data_loader(dataloader) + for d in dataloader: + assert isinstance(d, torch.Tensor) + + @parameterized.expand([1, 2], name_func=parameterized_custom_name_func) + def test_reproducibility(self, num_processes): + set_seed(21) + dataset = list(range(6)) + dataloader = DataLoader(dataset, batch_size=1, shuffle=True) + dataloader = prepare_data_loader(dataloader, num_processes=num_processes) + vals_1 = [] + for val in dataloader: + vals_1.append(val) + + # check same order for same seed + set_seed(21) + dataloader = DataLoader(dataset, batch_size=1, shuffle=True) + dataloader = prepare_data_loader(dataloader, num_processes=num_processes) + vals_2 = [] + for val in dataloader: + vals_2.append(val) + + assert vals_1 == vals_2 + + # check different order for different seed + set_seed(42) + dataloader = DataLoader(dataset, batch_size=1, shuffle=True) + dataloader = prepare_data_loader(dataloader, num_processes=num_processes) + vals_3 = [] + for val in dataloader: + vals_3.append(val) + + assert vals_1 != vals_3 + + def test_skip_batch_sampler(self): + batch_sampler = BatchSampler(range(16), batch_size=4, drop_last=False) + new_batch_sampler = SkipBatchSampler(batch_sampler, 2) + assert list(new_batch_sampler) == [[8, 9, 10, 11], [12, 13, 14, 15]] + + def test_dataloader_inheritance(self): + """ + `DataLoaderAdapter`'s parent classes are dynamically constructed, assert that subclasses of DataLoaderAdapter + are instances of DataLoader and DataLoaderStateMixin. + """ + skip_dl = SkipDataLoader(range(16), batch_size=4, skip_batches=2) + dl_shard = DataLoaderShard(range(16), batch_size=4) + dl_dispatcher = DataLoaderDispatcher(range(16), batch_size=4) + + # Test dataloaders are instances of instantiated classes + # These asserts look redundant, but it's worth checking since we are doing magic tricks such as dynamically overriding __class__ + assert isinstance(skip_dl, SkipDataLoader) + assert isinstance(dl_shard, DataLoaderShard) + assert isinstance(dl_dispatcher, DataLoaderDispatcher) + + # Test dataloaders are instances of base classes + assert isinstance(skip_dl, DataLoader) + assert isinstance(dl_shard, DataLoader) + assert isinstance(dl_dispatcher, DataLoader) + + assert isinstance(dl_shard, DataLoaderStateMixin) + assert isinstance(dl_dispatcher, DataLoaderStateMixin) + + assert isinstance(skip_dl.base_dataloader, DataLoader) + assert isinstance(dl_shard.base_dataloader, DataLoader) + assert isinstance(dl_dispatcher.base_dataloader, DataLoader) + + with pytest.raises(AttributeError): + _ = DataLoaderShard.base_dataloader + + def test_skip_data_loader(self): + dataloader = SkipDataLoader(list(range(16)), batch_size=4, skip_batches=2) + assert [t.tolist() for t in dataloader] == [[8, 9, 10, 11], [12, 13, 14, 15]] + + def test_skip_first_batches(self): + dataloader = DataLoader(list(range(16)), batch_size=4) + new_dataloader = skip_first_batches(dataloader, num_batches=2) + assert [t.tolist() for t in new_dataloader] == [[8, 9, 10, 11], [12, 13, 14, 15]] + + def test_end_of_dataloader(self): + dataloader = DataLoaderShard(list(range(16)), batch_size=4) + for idx, _ in enumerate(dataloader): + assert dataloader.end_of_dataloader == (idx == 3) + + # Test it also works on the second iteration + for idx, _ in enumerate(dataloader): + assert dataloader.end_of_dataloader == (idx == 3) + + def test_end_of_dataloader_dispatcher(self): + dataloader = DataLoaderDispatcher(range(16), batch_size=4) + for idx, _ in enumerate(dataloader): + assert dataloader.end_of_dataloader == (idx == 3) + + # Test it also works on the second iteration + for idx, _ in enumerate(dataloader): + assert dataloader.end_of_dataloader == (idx == 3) + + def test_set_epoch_in_batch_sampler(self): + # Ensure that set_epoch gets propagated to custom batch samplers that accept it + dataset = list(range(16)) + generator = torch.Generator() + batch_sampler = SimpleBatchSampler(dataset, batch_size=4, drop_last=False, generator=generator, seed=12) + dataloader = DataLoader(dataset, batch_sampler=batch_sampler) + + accelerator = Accelerator() + dataloader = accelerator.prepare_data_loader(dataloader) + + assert batch_sampler.epoch == 0 + dataloader.set_epoch(1) + assert batch_sampler.epoch == 1 + + def test_ensure_dataloader_gets_cleaned_up(self): + # Ensure that the dataloader gets cleaned up properly + class Dummy: + def __init__(self): + dataset = list(range(16)) + dataloader = DataLoader(dataset, batch_size=4) + + self.accelerator = Accelerator() + self.dataloader = self.accelerator.prepare_data_loader(dataloader) + + self.iter = iter(self.dataloader) + + def __call__(self, *args, **kwds): + return next(self.iter) + + instance = Dummy() + assert instance().tolist() == [0, 1, 2, 3] + + # Create weak references to the objects that *should* be cleaned up if the instance is deleted + accelerator_ref = weakref.ref(instance.accelerator) + dataloader_ref = weakref.ref(instance.dataloader) + gradient_state_ref = weakref.ref(instance.dataloader.gradient_state) + + del instance + + assert accelerator_ref() is None + assert dataloader_ref() is None + assert gradient_state_ref() is None + + +class StatefulDataLoaderTester(AccelerateTestCase): + @require_torchdata_stateful_dataloader + def test_skip_data_loader(self): + dataloader = SkipDataLoader(list(range(16)), batch_size=4, skip_batches=2, use_stateful_dataloader=True) + assert isinstance(dataloader, StatefulDataLoader) + assert [t.tolist() for t in dataloader] == [[8, 9, 10, 11], [12, 13, 14, 15]] + + @require_torchdata_stateful_dataloader + def test_end_of_dataloader(self): + dataloader = DataLoaderShard(list(range(16)), batch_size=4, use_stateful_dataloader=True) + assert dataloader.use_stateful_dataloader + assert isinstance(dataloader, StatefulDataLoader) + for idx, _ in enumerate(dataloader): + assert dataloader.end_of_dataloader == (idx == 3) + + # Test it also works on the second iteration + for idx, _ in enumerate(dataloader): + assert dataloader.end_of_dataloader == (idx == 3) + + @require_torchdata_stateful_dataloader + def test_end_of_dataloader_dispatcher(self): + dataloader = DataLoaderDispatcher(range(16), batch_size=4, use_stateful_dataloader=True) + assert isinstance(dataloader, StatefulDataLoader) + for idx, _ in enumerate(dataloader): + assert dataloader.end_of_dataloader == (idx == 3) + + # Test it also works on the second iteration + for idx, _ in enumerate(dataloader): + assert dataloader.end_of_dataloader == (idx == 3) + + @parameterized.expand([0, 2], name_func=parameterized_custom_name_func) + @require_torchdata_stateful_dataloader + def test_dataloader_state_dict(self, num_workers): + """ + Test that saving a stateful dataloader's state, then loading it back, gives the same results. + """ + dataset = list(range(16)) + dataloader = DataLoaderShard(dataset, batch_size=4, use_stateful_dataloader=True, num_workers=num_workers) + + assert dataloader.use_stateful_dataloader + assert isinstance(dataloader, StatefulDataLoader) + vals = [] + for idx, val in enumerate(dataloader): + vals.append(val) + if idx == 1: + sd = dataloader.state_dict() + assert len(vals) == 4 + + dataloader2 = DataLoaderShard(dataset, batch_size=4, use_stateful_dataloader=True, num_workers=num_workers) + dataloader2.load_state_dict(sd) + + data1 = vals[2:] + data2 = list(dataloader2) + assert len(data1) == len(data2) + for d1, d2 in zip(data1, data2): + assert torch.allclose(d1, d2) + + @parameterized.expand([0, 2], name_func=parameterized_custom_name_func) + @require_torchdata_stateful_dataloader + def test_dataloader_dispatcher_state_dict(self, num_workers): + """ + Test that saving a stateful dataloader's state, then loading it back, gives the same results. + """ + dataset = list(range(16)) + dataloader = DataLoaderDispatcher(dataset, batch_size=4, use_stateful_dataloader=True, num_workers=num_workers) + + assert dataloader.use_stateful_dataloader + assert isinstance(dataloader, StatefulDataLoader) + vals = [] + for idx, val in enumerate(dataloader): + vals.append(val) + if idx == 1: + sd = dataloader.state_dict() + assert len(vals) == 4 + dataloader2 = DataLoaderDispatcher( + dataset, batch_size=4, use_stateful_dataloader=True, num_workers=num_workers + ) + dataloader2.load_state_dict(sd) + + data1 = vals[2:] + data2 = list(dataloader2) + assert len(data1) == len(data2) + for d1, d2 in zip(data1, data2): + assert torch.allclose(d1, d2) + + @require_torchdata_stateful_dataloader + def test_dataloader_inheritance(self): + """ + `DataLoaderAdapter`'s parent classes are dynamically constructed, assert that if use_stateful_dataloader=True, + subclasses of DataLoaderAdapter are instances of StatefulDataLoader and DataLoaderStateMixin. + """ + skip_dl = SkipDataLoader(range(16), batch_size=4, skip_batches=2, use_stateful_dataloader=True) + dl_shard = DataLoaderShard(range(16), batch_size=4, use_stateful_dataloader=True) + dl_dispatcher = DataLoaderDispatcher(range(16), batch_size=4, use_stateful_dataloader=True) + + # Test dataloaders are instances of instantiated classes + # These asserts look redundant, but it's worth checking since we are doing magic tricks such as dynamically overriding __class__ + assert isinstance(skip_dl, SkipDataLoader) + assert isinstance(dl_shard, DataLoaderShard) + assert isinstance(dl_dispatcher, DataLoaderDispatcher) + + assert isinstance(skip_dl, StatefulDataLoader) + assert isinstance(dl_shard, StatefulDataLoader) + assert isinstance(dl_dispatcher, StatefulDataLoader) + + assert isinstance(dl_shard, DataLoaderStateMixin) + assert isinstance(dl_dispatcher, DataLoaderStateMixin) + + assert isinstance(skip_dl.base_dataloader, StatefulDataLoader) + assert isinstance(dl_shard.base_dataloader, StatefulDataLoader) + assert isinstance(dl_dispatcher.base_dataloader, StatefulDataLoader) + + @parameterized.expand([0, 2], name_func=parameterized_custom_name_func) + @require_torchdata_stateful_dataloader + def test_stateful_dataloader_adapter_equivalent_to_torchdata_stateful_dataloader(self, num_workers): + """ + Assert that `state_dict()` and `load_state_dict()` for derived subclasses of `DataLoaderAdapter` produce + the same behavior as `state_dict()` and `load_state_dict()` for `StatefulDataLoader`. + """ + dataset = list(range(64)) + + # Set the seed for reproducibility + def g(): + return torch.Generator().manual_seed(42) + + accelerator = Accelerator() + stateful_dl = StatefulDataLoader(dataset, batch_size=4, num_workers=num_workers, generator=g()) + skip_dl = SkipDataLoader( + dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True + ) + dl_shard = DataLoaderShard( + dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True + ) + dl_dispatcher = DataLoaderDispatcher( + dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True + ) + + dataloaders_under_test = [skip_dl, dl_shard, dl_dispatcher] + + num_batches_to_skip = 8 + + def get_first_n_batches(dl, n, device): + """ + Iterate over the first `n` batches of a dataloader then break, returning the batches in a list. + """ + batches = [] + for idx, batch in enumerate(dl): + if idx == n - 1: + if hasattr(dl, "end"): + dl.end() + break + batches.append(batch.to(device)) + return batches + + # Iterate over all of the dataloaders identically, expect the same values + expected_batches = get_first_n_batches(stateful_dl, num_batches_to_skip, accelerator.device) + batches_from_dataloaders = [ + get_first_n_batches(dl, num_batches_to_skip, accelerator.device) for dl in dataloaders_under_test + ] + + for dl_batches in batches_from_dataloaders: + for expected, actual in zip(expected_batches, dl_batches): + assert torch.allclose(expected, actual) + + # The adapters should all produce the same state_dict as the reference stateful dataloader + expected_state_dict = stateful_dl.state_dict() + skip_dl_state_dict = skip_dl.state_dict() + dl_shard_state_dict = dl_shard.state_dict() + dl_dispatcher_state_dict = dl_dispatcher.state_dict() + + assert expected_state_dict == skip_dl_state_dict + assert expected_state_dict == dl_shard_state_dict + assert expected_state_dict == dl_dispatcher_state_dict + + # Load the state dict into new dataloaders + manual_skip_dl = SkipDataLoader( + dataset, + batch_size=4, + num_workers=num_workers, + generator=g(), + skip_batches=num_batches_to_skip, + use_stateful_dataloader=True, + ) + loaded_stateful_dl = StatefulDataLoader(dataset, batch_size=4, num_workers=num_workers, generator=g()) + loaded_stateful_dl.load_state_dict(expected_state_dict) + loaded_skip_dl = SkipDataLoader( + dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True + ) + loaded_skip_dl.load_state_dict(expected_state_dict) + loaded_dl_shard = DataLoaderShard( + dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True + ) + loaded_dl_shard.load_state_dict(expected_state_dict) + loaded_dl_dispatcher = DataLoaderDispatcher( + dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True + ) + loaded_dl_dispatcher.load_state_dict(expected_state_dict) + + # Continue the iteration, expecting identical behavior across the board + def get_all_batches(dl, device): + """ + Iterate over all batches of a dataloader, returning (batches, num_batches_yielded) + """ + batches = [] + num_batches_yielded = 0 + for batch in dl: + batches.append(batch.to(device)) + num_batches_yielded += 1 + return (batches, num_batches_yielded) + + expected_batch_results = get_all_batches(loaded_stateful_dl, accelerator.device) + dataloader_batch_results = [ + get_all_batches(dl, accelerator.device) + for dl in [manual_skip_dl, loaded_skip_dl, loaded_dl_shard, loaded_dl_dispatcher] + ] + for dl_results in dataloader_batch_results: + for expected, actual in zip(expected_batches, dl_batches): + assert torch.allclose(expected[0], actual[0]) + assert expected_batch_results[1] == dl_results[1] + + assert accelerator.gradient_state.active_dataloader is None + + @parameterized.expand([0, 2], name_func=parameterized_custom_name_func) + @require_torchdata_stateful_dataloader + def test_decoupled_stateful_dataloader_adapter_equivalent_to_torchdata_stateful_dataloader(self, num_workers): + """ + Assert that `state_dict()` and `load_state_dict()` for derived subclasses of `DataLoaderAdapter` produce + the same behavior as `state_dict()` and `load_state_dict()` for `StatefulDataLoader` when *not* using + Accelerator (and instead using the decoupled `PartialState` workflow). + """ + dataset = list(range(64)) + + # Set the seed for reproducibility + def g(): + return torch.Generator().manual_seed(42) + + state = PartialState() + stateful_dl = StatefulDataLoader(dataset, batch_size=4, num_workers=num_workers, generator=g()) + skip_dl = SkipDataLoader( + dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True + ) + dl_shard = DataLoaderShard( + dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True + ) + dl_dispatcher = DataLoaderDispatcher( + dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True + ) + + dataloaders_under_test = [skip_dl, dl_shard, dl_dispatcher] + + num_batches_to_skip = 8 + + def get_first_n_batches(dl, n, device): + """ + Iterate over the first `n` batches of a dataloader then break, returning the batches in a list. + """ + batches = [] + for idx, batch in enumerate(dl): + if idx == n - 1: + if hasattr(dl, "end"): + dl.end() + break + batches.append(batch.to(device)) + return batches + + # Iterate over all of the dataloaders identically, expect the same values + expected_batches = get_first_n_batches(stateful_dl, num_batches_to_skip, state.device) + batches_from_dataloaders = [ + get_first_n_batches(dl, num_batches_to_skip, state.device) for dl in dataloaders_under_test + ] + + for dl_batches in batches_from_dataloaders: + for expected, actual in zip(expected_batches, dl_batches): + assert torch.allclose(expected, actual) + + # The adapters should all produce the same state_dict as the reference stateful dataloader + expected_state_dict = stateful_dl.state_dict() + skip_dl_state_dict = skip_dl.state_dict() + dl_shard_state_dict = dl_shard.state_dict() + dl_dispatcher_state_dict = dl_dispatcher.state_dict() + + assert expected_state_dict == skip_dl_state_dict + assert expected_state_dict == dl_shard_state_dict + assert expected_state_dict == dl_dispatcher_state_dict + + # Load the state dict into new dataloaders + manual_skip_dl = SkipDataLoader( + dataset, + batch_size=4, + num_workers=num_workers, + generator=g(), + skip_batches=num_batches_to_skip, + use_stateful_dataloader=True, + ) + loaded_stateful_dl = StatefulDataLoader(dataset, batch_size=4, num_workers=num_workers, generator=g()) + loaded_stateful_dl.load_state_dict(expected_state_dict) + loaded_skip_dl = SkipDataLoader( + dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True + ) + loaded_skip_dl.load_state_dict(expected_state_dict) + loaded_dl_shard = DataLoaderShard( + dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True + ) + loaded_dl_shard.load_state_dict(expected_state_dict) + loaded_dl_dispatcher = DataLoaderDispatcher( + dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True + ) + loaded_dl_dispatcher.load_state_dict(expected_state_dict) + + # Continue the iteration, expecting identical behavior across the board + def get_all_batches(dl, device): + """ + Iterate over all batches of a dataloader, returning (batches, num_batches_yielded) + """ + batches = [] + num_batches_yielded = 0 + for batch in dl: + batches.append(batch.to(device)) + num_batches_yielded += 1 + return (batches, num_batches_yielded) + + expected_batch_results = get_all_batches(loaded_stateful_dl, state.device) + dataloader_batch_results = [ + get_all_batches(dl, state.device) + for dl in [manual_skip_dl, loaded_skip_dl, loaded_dl_shard, loaded_dl_dispatcher] + ] + for dl_results in dataloader_batch_results: + for expected, actual in zip(expected_batches, dl_batches): + assert torch.allclose(expected[0], actual[0]) + assert expected_batch_results[1] == dl_results[1] + + # Using the decoupled (`PartialState`) workflow, GradientState should be automatically initialized (with + # default parameters) by `DataLoaderDispatcher` + assert GradientState._shared_state != {}, "GradientState should already be initialized!" + + gradient_state = GradientState() + assert gradient_state.active_dataloader is None diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_dataclasses.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_dataclasses.py new file mode 100644 index 0000000000000000000000000000000000000000..2dab51a6938da4da31c5b510e35b88402910880f --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_dataclasses.py @@ -0,0 +1,294 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest.mock import Mock, patch + +import pytest + +from accelerate.parallelism_config import ParallelismConfig +from accelerate.utils import patch_environment +from accelerate.utils.constants import ( + BETA_CP_AVAILABLE_PYTORCH_VERSION, + BETA_TP_AVAILABLE_PYTORCH_VERSION, + BETA_TP_AVAILABLE_TRANSFORMERS_VERSION, +) +from accelerate.utils.imports import is_transformers_available +from accelerate.utils.versions import compare_versions, is_torch_version + + +def _should_skip_cp_test(cp_size): + """Check if CP test should be skipped based on cp_size and torch version.""" + return cp_size > 1 and not is_torch_version(">=", BETA_CP_AVAILABLE_PYTORCH_VERSION) + + +def _should_skip_tp_test(tp_size): + """Check if TP test should be skipped based on tp_size, torch version, and transformers availability.""" + if tp_size <= 1: + return False + + if not is_torch_version(">=", BETA_TP_AVAILABLE_PYTORCH_VERSION): + return True + + if not is_transformers_available(): + return True + + if not compare_versions("transformers", ">=", BETA_TP_AVAILABLE_TRANSFORMERS_VERSION): + return True + + return False + + +class TestParallelismConfig: + @pytest.fixture(autouse=True) + def mock_init_device_mesh(self): + def mock_init_mesh(device_type, mesh_shape, mesh_dim_names): + mesh = Mock() + mesh.size.return_value = 1 + for dim in mesh_shape: + mesh.size.return_value *= dim + mesh.shape = mesh_shape + mesh.mesh_dim_names = mesh_dim_names + + # mock device_mesh._flatten + mesh.flattened_dims = [] + + def mock_getitem(key): + submesh = Mock() + + def mock_flatten(name): + mesh.flattened_dims.append((key, name)) + + submesh._flatten = Mock(side_effect=mock_flatten) + return submesh + + mesh.__getitem__ = Mock(side_effect=mock_getitem) + + return mesh + + with patch("accelerate.parallelism_config.init_device_mesh", side_effect=mock_init_mesh): + yield mock_init_mesh + + @pytest.mark.parametrize( + "dp_replicate_size, dp_shard_size, tp_size, cp_size, expected_shape, expected_dim_names", + [ + (8, 1, 1, 1, (8,), ("dp_replicate",)), # DDP + (1, 8, 1, 1, (8,), ("dp_shard",)), # FSDP + (2, 4, 1, 1, (2, 4), ("dp_replicate", "dp_shard")), # HSDP + (1, 4, 2, 1, (4, 2), ("dp_shard", "tp")), # FSDP + TP + (2, 2, 2, 1, (2, 2, 2), ("dp_replicate", "dp_shard", "tp")), # HSDP + TP + (1, 1, 8, 1, (8,), ("tp",)), # TP only + (1, 1, 1, 4, (4,), ("cp",)), # CP only + (1, 4, 1, 2, (4, 2), ("dp_shard", "cp")), # FSDP + CP + (1, 2, 2, 2, (2, 2, 2), ("dp_shard", "cp", "tp")), # FSDP + CP + TP + (2, 2, 2, 2, (2, 2, 2, 2), ("dp_replicate", "dp_shard", "cp", "tp")), # HSDP + CP + TP + ], + ) + def test_get_mesh( + self, + dp_replicate_size, + dp_shard_size, + tp_size, + cp_size, + expected_shape, + expected_dim_names, + ): + # Skip tests based on version requirements + if _should_skip_cp_test(cp_size): + pytest.skip(f"tests with `cp_size>1` require torch >= {BETA_CP_AVAILABLE_PYTORCH_VERSION}") + if _should_skip_tp_test(tp_size): + pytest.skip( + f"tests with `tp_size>1` require torch >= {BETA_TP_AVAILABLE_PYTORCH_VERSION}, transformers available and >= {BETA_TP_AVAILABLE_TRANSFORMERS_VERSION}" + ) + + config = ParallelismConfig( + dp_replicate_size=dp_replicate_size, dp_shard_size=dp_shard_size, tp_size=tp_size, cp_size=cp_size + ) + mesh_dim_names, mesh_shape = config._get_mesh() + assert mesh_shape == expected_shape + assert mesh_dim_names == expected_dim_names + + @pytest.mark.parametrize( + "dp_replicate_size, dp_shard_size, tp_size, cp_size, expected_shape, expected_dim_names", + [ + (8, 1, 1, 1, (8,), ("dp_replicate",)), + (1, 8, 1, 1, (8,), ("dp_shard",)), + (2, 4, 1, 1, (2, 4), ("dp_replicate", "dp_shard")), + (1, 4, 2, 1, (4, 2), ("dp_shard", "tp")), + (2, 2, 2, 1, (2, 2, 2), ("dp_replicate", "dp_shard", "tp")), + (1, 1, 8, 1, (8,), ("tp",)), + (1, 1, 1, 4, (4,), ("cp",)), + (1, 4, 1, 2, (4, 2), ("dp_shard", "cp")), + (1, 2, 2, 2, (2, 2, 2), ("dp_shard", "cp", "tp")), + (2, 2, 2, 2, (2, 2, 2, 2), ("dp_replicate", "dp_shard", "cp", "tp")), + ], + ) + def test_build_device_mesh( + self, + dp_replicate_size, + dp_shard_size, + tp_size, + cp_size, + expected_shape, + expected_dim_names, + ): + """Test build_device_mesh creates correct mesh and applies flattening.""" + # Skip tests based on version requirements + if _should_skip_cp_test(cp_size): + pytest.skip(f"tests with `cp_size>1` require torch >= {BETA_CP_AVAILABLE_PYTORCH_VERSION}") + if _should_skip_tp_test(tp_size): + pytest.skip( + f"tests with `tp_size>1` require torch >= {BETA_TP_AVAILABLE_PYTORCH_VERSION}, transformers available and >= {BETA_TP_AVAILABLE_TRANSFORMERS_VERSION}" + ) + + config = ParallelismConfig( + dp_replicate_size=dp_replicate_size, dp_shard_size=dp_shard_size, tp_size=tp_size, cp_size=cp_size + ) + device_mesh = config.build_device_mesh("cpu") + + # Check mesh shape and dimension names match expected + assert device_mesh.shape == expected_shape + assert device_mesh.mesh_dim_names == expected_dim_names + + # Literal expectations keyed by the independently parameterized names, + # not by properties on the submitted configuration implementation. + expected_flattened = { + ("dp_replicate",): [ + (["dp_replicate"], "dp"), + (["dp_replicate"], "dp_cp"), + ], + ("dp_shard",): [ + (["dp_shard"], "dp"), + (["dp_shard"], "dp_shard_cp"), + (["dp_shard"], "dp_cp"), + ], + ("dp_replicate", "dp_shard"): [ + (["dp_replicate", "dp_shard"], "dp"), + (["dp_shard"], "dp_shard_cp"), + (["dp_replicate", "dp_shard"], "dp_cp"), + ], + ("dp_shard", "tp"): [ + (["dp_shard"], "dp"), + (["dp_shard"], "dp_shard_cp"), + (["dp_shard"], "dp_cp"), + ], + ("dp_replicate", "dp_shard", "tp"): [ + (["dp_replicate", "dp_shard"], "dp"), + (["dp_shard"], "dp_shard_cp"), + (["dp_replicate", "dp_shard"], "dp_cp"), + ], + ("tp",): [], + ("cp",): [ + (["cp"], "dp_shard_cp"), + (["cp"], "dp_cp"), + ], + ("dp_shard", "cp"): [ + (["dp_shard"], "dp"), + (["dp_shard", "cp"], "dp_shard_cp"), + (["dp_shard", "cp"], "dp_cp"), + ], + ("dp_shard", "cp", "tp"): [ + (["dp_shard"], "dp"), + (["dp_shard", "cp"], "dp_shard_cp"), + (["dp_shard", "cp"], "dp_cp"), + ], + ("dp_replicate", "dp_shard", "cp", "tp"): [ + (["dp_replicate", "dp_shard"], "dp"), + (["dp_shard", "cp"], "dp_shard_cp"), + (["dp_replicate", "dp_shard", "cp"], "dp_cp"), + ], + }[expected_dim_names] + + # Alias creation order is internal; dimension order within each alias + # is meaningful. Compare lists rather than sets to retain duplicates. + actual_aliases = sorted((name, tuple(dims)) for dims, name in device_mesh.flattened_dims) + expected_aliases = sorted((name, tuple(dims)) for dims, name in expected_flattened) + assert actual_aliases == expected_aliases + + @pytest.mark.parametrize( + "dp_replicate_size, dp_shard_size, tp_size, cp_size", + [ + (8, 1, 1, 1), + (1, 8, 1, 1), + (2, 4, 1, 1), + (1, 4, 2, 1), + (2, 2, 2, 1), + (1, 1, 8, 1), + (1, 1, 1, 4), + (1, 4, 1, 2), + (1, 2, 2, 2), + (2, 2, 2, 2), + ], + ) + def test_from_env( + self, + dp_replicate_size, + dp_shard_size, + tp_size, + cp_size, + ): + if _should_skip_cp_test(cp_size): + pytest.skip(f"tests with `cp_size>1` require torch >= {BETA_CP_AVAILABLE_PYTORCH_VERSION}") + if _should_skip_tp_test(tp_size): + pytest.skip( + f"tests with `tp_size>1` require torch >= {BETA_TP_AVAILABLE_PYTORCH_VERSION}, transformers available and >= {BETA_TP_AVAILABLE_TRANSFORMERS_VERSION}" + ) + + new_env = { + "PARALLELISM_CONFIG_DP_REPLICATE_SIZE": dp_replicate_size, + "PARALLELISM_CONFIG_DP_SHARD_SIZE": dp_shard_size, + "PARALLELISM_CONFIG_TP_SIZE": tp_size, + "PARALLELISM_CONFIG_CP_SIZE": cp_size, + } + + with patch_environment(**new_env): + config = ParallelismConfig() + for key, value in new_env.items(): + assert getattr(config, key.split("PARALLELISM_CONFIG_")[-1].lower()) == value + + def test_cp_handler(self): + """Test CP handler with various configurations.""" + + # Any cp_size > 1 requires torch >= BETA_CP_AVAILABLE_PYTORCH_VERSION, we use placeholder for this check as this test doesn't depend on a specific size + if _should_skip_cp_test(2): + pytest.skip(f"tests with `cp_size>1` require torch >= {BETA_CP_AVAILABLE_PYTORCH_VERSION}") + + from accelerate.utils import TorchContextParallelConfig + + for setting in ("allgather", "alltoall"): + cp_handler = TorchContextParallelConfig(cp_comm_strategy=setting) + pc = ParallelismConfig(cp_size=2, cp_handler=cp_handler) + + assert pc.cp_handler is not None, "CP handler should be set" + assert pc.cp_handler.cp_comm_strategy == setting, ( + f"CP handler strategy should be {setting} but got {pc.cp_handler.cp_comm_strategy}" + ) + + for setting in ("allgather", "alltoall"): + with patch_environment(PARALLELISM_CONFIG_CP_COMM_STRATEGY=setting): + pc = ParallelismConfig(cp_size=2) + assert pc.cp_handler is not None, "CP handler should be set from environment" + assert pc.cp_handler.cp_comm_strategy == setting, ( + f"CP handler strategy should be {setting} but got {pc.cp_handler.cp_comm_strategy}" + ) + + for setting in ("invalid", "unsupported"): + with pytest.raises(ValueError, match=f"Invalid cp_comm_strategy: {setting}"): + TorchContextParallelConfig(cp_comm_strategy=setting) + + with patch_environment(PARALLELISM_CONFIG_CP_COMM_STRATEGY=setting): + with pytest.raises(ValueError, match=f"Invalid cp_comm_strategy: {setting}"): + pc = ParallelismConfig(cp_size=2) + + def test_tp_handler(self): + assert True, "Tensor parallelism handler doesn't hold any logic yet" diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_examples.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_examples.py new file mode 100644 index 0000000000000000000000000000000000000000..9e67794aa4edc793eb2fa78dde22b942ff05af56 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_examples.py @@ -0,0 +1,308 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import ast +import os +import re +import shutil +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +import torch + +from accelerate.test_utils.examples import compare_against_test +from accelerate.test_utils.testing import ( + TempDirTestCase, + get_launch_command, + is_hpu_available, + is_xpu_available, + require_fp16, + require_huggingface_suite, + require_multi_device, + require_pippy, + require_schedulefree, + require_trackers, + run_command, + run_first, + slow, +) +from accelerate.utils import write_basic_config + + +# DataLoaders built from `test_samples/MRPC` for quick testing +# Should mock `{script_name}.get_dataloaders` via: +# @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) + +EXCLUDE_EXAMPLES = [ + "cross_validation.py", + "checkpointing.py", + "gradient_accumulation.py", + "local_sgd.py", + "multi_process_metrics.py", + "memory.py", + "schedule_free.py", + "tracking.py", + "automatic_gradient_accumulation.py", + "gradient_accumulation_for_autoregressive_models.py", + "fsdp_with_peak_mem_tracking.py", + "deepspeed_with_config_support.py", + "megatron_lm_gpt_pretraining.py", + "early_stopping.py", + "ddp_comm_hook.py", + "profiler.py", +] + + +class ExampleDifferenceTests(unittest.TestCase): + """ + This TestCase checks that all of the `complete_*` scripts contain all of the + information found in the `by_feature` scripts, line for line. If one fails, + then a complete example does not contain all of the features in the features + scripts, and should be updated. + + Each example script should be a single test (such as `test_nlp_example`), + and should run `one_complete_example` twice: once with `parser_only=True`, + and the other with `parser_only=False`. This is so that when the test + failures are returned to the user, they understand if the discrepancy lies in + the `main` function, or the `training_loop` function. Otherwise it will be + unclear. + + Also, if there are any expected differences between the base script used and + `complete_nlp_example.py` (the canonical base script), these should be included in + `special_strings`. These would be differences in how something is logged, print statements, + etc (such as calls to `Accelerate.log()`) + """ + + by_feature_path = Path("examples", "by_feature").resolve() + examples_path = Path("examples").resolve() + + def one_complete_example( + self, complete_file_name: str, parser_only: bool, secondary_filename: str = None, special_strings: list = None + ): + """ + Tests a single `complete` example against all of the implemented `by_feature` scripts + + Args: + complete_file_name (`str`): + The filename of a complete example + parser_only (`bool`): + Whether to look at the main training function, or the argument parser + secondary_filename (`str`, *optional*): + A potential secondary base file to strip all script information not relevant for checking, + such as "cv_example.py" when testing "complete_cv_example.py" + special_strings (`list`, *optional*): + A list of strings to potentially remove before checking no differences are left. These should be + diffs that are file specific, such as different logging variations between files. + """ + self.maxDiff = None + for item in os.listdir(self.by_feature_path): + if item not in EXCLUDE_EXAMPLES: + item_path = self.by_feature_path / item + if item_path.is_file() and item_path.suffix == ".py": + with self.subTest( + tested_script=complete_file_name, + feature_script=item, + tested_section="main()" if parser_only else "training_function()", + ): + diff = compare_against_test( + self.examples_path / complete_file_name, item_path, parser_only, secondary_filename + ) + diff = "\n".join(diff) + if special_strings is not None: + for string in special_strings: + diff = diff.replace(string, "") + assert diff == "" + + def test_nlp_examples(self): + self.one_complete_example("complete_nlp_example.py", True) + self.one_complete_example("complete_nlp_example.py", False) + + def test_cv_examples(self): + cv_path = (self.examples_path / "cv_example.py").resolve() + special_strings = [ + " " * 16 + "{\n\n", + " " * 20 + '"accuracy": eval_metric["accuracy"],\n\n', + " " * 20 + '"f1": eval_metric["f1"],\n\n', + " " * 20 + '"train_loss": total_loss.item() / len(train_dataloader),\n\n', + " " * 20 + '"epoch": epoch,\n\n', + " " * 16 + "},\n\n", + " " * 16 + "step=epoch,\n", + " " * 12, + " " * 8 + "for step, batch in enumerate(active_dataloader):\n", + ] + self.one_complete_example("complete_cv_example.py", True, cv_path, special_strings) + self.one_complete_example("complete_cv_example.py", False, cv_path, special_strings) + + +@mock.patch.dict(os.environ, {"TESTING_MOCKED_DATALOADERS": "1"}) +@require_huggingface_suite +@run_first +class FeatureExamplesTests(TempDirTestCase): + clear_on_setup = False + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls._tmpdir = tempfile.mkdtemp() + cls.config_file = Path(cls._tmpdir) / "default_config.yml" + + write_basic_config(save_location=cls.config_file) + cls.launch_args = get_launch_command(config_file=cls.config_file) + + @classmethod + def tearDownClass(cls): + super().tearDownClass() + shutil.rmtree(cls._tmpdir) + + def test_checkpointing_by_epoch(self): + testargs = f""" + examples/by_feature/checkpointing.py + --checkpointing_steps epoch + --output_dir {self.tmpdir} + """.split() + run_command(self.launch_args + testargs) + assert (self.tmpdir / "epoch_0").exists() + + def test_checkpointing_by_steps(self): + testargs = f""" + examples/by_feature/checkpointing.py + --checkpointing_steps 1 + --output_dir {self.tmpdir} + """.split() + _ = run_command(self.launch_args + testargs) + assert (self.tmpdir / "step_2").exists() + + def test_load_states_by_epoch(self): + testargs = f""" + examples/by_feature/checkpointing.py + --resume_from_checkpoint {self.tmpdir / "epoch_0"} + """.split() + output = run_command(self.launch_args + testargs, return_stdout=True) + assert "epoch 0:" not in output + assert "epoch 1:" in output + + def test_load_states_by_steps(self): + testargs = f""" + examples/by_feature/checkpointing.py + --resume_from_checkpoint {self.tmpdir / "step_2"} + """.split() + output = run_command(self.launch_args + testargs, return_stdout=True) + if is_hpu_available(): + num_processes = torch.hpu.device_count() + elif torch.cuda.is_available(): + num_processes = torch.cuda.device_count() + elif is_xpu_available(): + num_processes = torch.xpu.device_count() + else: + num_processes = 1 + + if num_processes > 1: + assert "epoch 0:" not in output + assert "epoch 1:" in output + else: + assert "epoch 0:" in output + assert "epoch 1:" in output + + @slow + def test_cross_validation(self): + testargs = """ + examples/by_feature/cross_validation.py + --num_folds 2 + """.split() + with mock.patch.dict(os.environ, {"TESTING_MOCKED_DATALOADERS": "0"}): + output = run_command(self.launch_args + testargs, return_stdout=True) + results = re.findall("({.+})", output) + results = [r for r in results if "accuracy" in r][-1] + results = ast.literal_eval(results) + assert results["accuracy"] >= 0.75 + + def test_multi_process_metrics(self): + testargs = ["examples/by_feature/multi_process_metrics.py"] + run_command(self.launch_args + testargs) + + @require_schedulefree + def test_schedulefree(self): + testargs = ["examples/by_feature/schedule_free.py"] + run_command(self.launch_args + testargs) + + @require_trackers + @mock.patch.dict( + os.environ, + {"WANDB_MODE": "offline", "DVCLIVE_TEST": "true", "SWANLAB_MODE": "offline"}, + ) + def test_tracking(self): + with tempfile.TemporaryDirectory() as tmpdir: + testargs = f""" + examples/by_feature/tracking.py + --with_tracking + --project_dir {tmpdir} + """.split() + run_command(self.launch_args + testargs) + assert os.path.exists(os.path.join(tmpdir, "tracking")) + + def test_gradient_accumulation(self): + testargs = ["examples/by_feature/gradient_accumulation.py"] + run_command(self.launch_args + testargs) + + def test_gradient_accumulation_for_autoregressive_models(self): + testargs = [ + "examples/by_feature/gradient_accumulation_for_autoregressive_models.py", + "--gradient_accumulation_steps", + "2", + ] + run_command(self.launch_args + testargs) + + def test_local_sgd(self): + testargs = ["examples/by_feature/local_sgd.py"] + run_command(self.launch_args + testargs) + + def test_early_stopping(self): + testargs = ["examples/by_feature/early_stopping.py"] + run_command(self.launch_args + testargs) + + def test_profiler(self): + testargs = ["examples/by_feature/profiler.py"] + run_command(self.launch_args + testargs) + + @require_fp16 + @require_multi_device + def test_ddp_comm_hook(self): + testargs = ["examples/by_feature/ddp_comm_hook.py", "--ddp_comm_hook", "fp16"] + run_command(self.launch_args + testargs) + + @require_fp16 + @require_multi_device + def test_distributed_inference_examples_stable_diffusion(self): + testargs = ["examples/inference/distributed/stable_diffusion.py"] + run_command(self.launch_args + testargs) + + @require_fp16 + @require_multi_device + def test_distributed_inference_examples_phi2(self): + testargs = ["examples/inference/distributed/phi2.py"] + run_command(self.launch_args + testargs) + + @require_pippy + @require_multi_device + def test_pippy_examples_bert(self): + testargs = ["examples/inference/pippy/bert.py"] + run_command(self.launch_args + testargs) + + @require_pippy + @require_multi_device + def test_pippy_examples_gpt2(self): + testargs = ["examples/inference/pippy/gpt2.py"] + run_command(self.launch_args + testargs) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_fp8.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_fp8.py new file mode 100644 index 0000000000000000000000000000000000000000..53c463b92724d52ed438ffb14dce7d78f4590396 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_fp8.py @@ -0,0 +1,234 @@ +# Copyright 2025 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import json +import os +import tempfile +import textwrap +import unittest +from pathlib import Path + +import torch + +from accelerate import Accelerator +from accelerate.state import AcceleratorState +from accelerate.test_utils import ( + get_launch_command, + require_cuda_or_hpu, + require_huggingface_suite, + require_multi_device, + require_torchao, + require_transformer_engine, + run_first, +) +from accelerate.test_utils.testing import require_deepspeed, run_command +from accelerate.utils import ( + AORecipeKwargs, + TERecipeKwargs, + has_ao_layers, + has_transformer_engine_layers, +) + + +def can_convert_te_model(from_config=False): + if not from_config: + accelerator_kwargs = {"mixed_precision": "fp8", "kwargs_handlers": [TERecipeKwargs()]} + else: + accelerator_kwargs = {} + + accelerator = Accelerator(**accelerator_kwargs) + dataloader = torch.utils.data.DataLoader(torch.randn(10, 32), batch_size=2) + model = torch.nn.Sequential(torch.nn.Linear(32, 32), torch.nn.Linear(32, 16)) + optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) + scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.1) + + model, optimizer, dataloader, scheduler = accelerator.prepare(model, optimizer, dataloader, scheduler) + assert has_transformer_engine_layers(model) + + +def maintain_proper_deepspeed_config(expected_version): + assert AcceleratorState().deepspeed_plugin.zero_stage == expected_version, ( + f"Expected zero stage {expected_version} but got {AcceleratorState().deepspeed_plugin.zero_stage}" + ) + + +def can_convert_ao_model(from_config=False): + from transformers import AutoModelForSequenceClassification + + if not from_config: + accelerator_kwargs = {"mixed_precision": "fp8", "kwargs_handlers": [AORecipeKwargs()]} + else: + accelerator_kwargs = {} + + accelerator = Accelerator(**accelerator_kwargs) + dataloader = torch.utils.data.DataLoader(torch.randn(10, 32), batch_size=2) + model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased") + optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) + scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.1) + + model, optimizer, dataloader, scheduler = accelerator.prepare(model, optimizer, dataloader, scheduler) + assert has_ao_layers(model) + + +@run_first +@require_transformer_engine +@require_cuda_or_hpu +class TestTransformerEngine(unittest.TestCase): + def test_can_prepare_model_single_gpu(self): + command = get_launch_command(num_processes=1, monitor_interval=0.1) + command += ["-m", "tests.test_fp8", "--test_te"] + run_command(command) + + def test_can_prepare_model_single_gpu_from_config(self): + with tempfile.TemporaryDirectory() as dir_name: + config_file = Path(dir_name) / "config.yaml" + config_file.write_text( + textwrap.dedent( + """ + distributed_type: "NO" + num_processes: 1 + mixed_precision: fp8 + fp8_config: + backend: TE + """ + ) + ) + command = get_launch_command(config_file=str(config_file), monitor_interval=0.1) + command += ["-m", "tests.test_fp8", "--test_te", "--from_config"] + run_command(command) + + @require_multi_device + def test_can_prepare_model_multi_gpu(self): + command = get_launch_command(num_processes=2, monitor_interval=0.1) + command += ["-m", "tests.test_fp8", "--test_te"] + run_command(command) + + @require_deepspeed + @require_multi_device + def test_can_prepare_model_multigpu_deepspeed(self): + for zero_stage in [1, 2, 3]: + os.environ["ZERO_STAGE"] = str(zero_stage) + ds_config = { + "bf16": {"enabled": True}, + "zero_optimization": { + "stage": zero_stage, + "allgather_partitions": True, + "allgather_bucket_size": 2e8, + "overlap_comm": True, + "reduce_scatter": True, + "reduce_bucket_size": 2e8, + "contiguous_gradients": True, + }, + "gradient_accumulation_steps": 1, + "gradient_clipping": "auto", + "steps_per_print": 2000, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "wall_clock_breakdown": False, + } + + ds_config = json.dumps(ds_config) + + command = get_launch_command( + num_processes=2, monitor_interval=0.1, use_deepspeed=True, deepspeed_config_file=ds_config + ) + command += ["-m", "tests.test_fp8", "--test_te"] + run_command(command) + + +@require_torchao +@require_huggingface_suite +class TestTorchAO(unittest.TestCase): + def test_can_prepare_model_single_accelerator(self): + command = get_launch_command(num_processes=1, monitor_interval=0.1) + command += ["-m", "tests.test_fp8", "--test_ao"] + run_command(command) + + def test_can_prepare_model_single_gpu_from_config(self): + with tempfile.TemporaryDirectory() as dir_name: + config_file = Path(dir_name) / "config.yaml" + config_file.write_text( + textwrap.dedent( + """ + distributed_type: "NO" + num_processes: 1 + mixed_precision: fp8 + fp8_config: + backend: AO + """ + ) + ) + command = get_launch_command(config_file=str(config_file), monitor_interval=0.1) + command += ["-m", "tests.test_fp8", "--test_ao", "--from_config"] + run_command(command) + + @require_multi_device + def test_can_prepare_model_multi_accelerator(self): + command = get_launch_command(num_processes=2, monitor_interval=0.1) + command += ["-m", "tests.test_fp8", "--test_ao"] + run_command(command) + + @require_deepspeed + @require_multi_device + def test_can_prepare_model_multi_accelerator_deepspeed(self): + for zero_stage in [1, 2, 3]: + os.environ["ZERO_STAGE"] = str(zero_stage) + ds_config = { + "bf16": {"enabled": True}, + "zero_optimization": { + "stage": zero_stage, + "allgather_partitions": True, + "allgather_bucket_size": 2e8, + "overlap_comm": True, + "reduce_scatter": True, + "reduce_bucket_size": 2e8, + "contiguous_gradients": True, + }, + "gradient_accumulation_steps": 1, + "gradient_clipping": "auto", + "steps_per_print": 2000, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "wall_clock_breakdown": False, + } + + ds_config = json.dumps(ds_config) + + command = get_launch_command( + num_processes=2, monitor_interval=0.1, use_deepspeed=True, deepspeed_config_file=ds_config + ) + command += ["-m", "tests.test_fp8", "--test_ao"] + run_command(command) + + +if __name__ == "__main__": + # TE suite + parser = argparse.ArgumentParser() + parser.add_argument("--test_te", action="store_true", default=False) + parser.add_argument("--test_ao", action="store_true", default=False) + parser.add_argument("--from_config", action="store_true", default=False) + args = parser.parse_args() + + if not args.test_te and not args.test_ao: + raise ValueError("Must specify at least one of --test_te or --test_ao") + + if args.test_te: + can_convert_te_model(args.from_config) + if os.environ.get("ACCELERATE_USE_DEEPSPEED", "false") == "true": + maintain_proper_deepspeed_config(int(os.environ.get("ZERO_STAGE"))) + + # AO suite + if args.test_ao: + can_convert_ao_model(args.from_config) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_grad_sync.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_grad_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..c89f6e3a74d810dad964011f687eb93ae5f29707 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_grad_sync.py @@ -0,0 +1,52 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from accelerate import debug_launcher +from accelerate.test_utils import ( + DEFAULT_LAUNCH_COMMAND, + device_count, + execute_subprocess_async, + path_in_accelerate_package, + require_cpu, + require_multi_device, + require_non_cpu, + run_first, + test_sync, +) +from accelerate.test_utils.testing import AccelerateTestCase +from accelerate.utils import patch_environment + + +class SyncScheduler(AccelerateTestCase): + test_file_path = path_in_accelerate_package("test_utils", "scripts", "test_sync.py") + + @require_cpu + def test_gradient_sync_cpu_noop(self): + debug_launcher(test_sync.main, num_processes=1) + + @require_cpu + def test_gradient_sync_cpu_multi(self): + debug_launcher(test_sync.main) + + @require_non_cpu + def test_gradient_sync_gpu(self): + test_sync.main() + + @run_first + @require_multi_device + def test_gradient_sync_gpu_multi(self): + print(f"Found {device_count} devices.") + cmd = DEFAULT_LAUNCH_COMMAND + [self.test_file_path] + with patch_environment(omp_num_threads=1): + execute_subprocess_async(cmd) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_hooks.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..67a11b19d536d4e809b2965fd786d7dcaa8307aa --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_hooks.py @@ -0,0 +1,459 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import re +import unittest + +import torch +import torch.nn as nn +from parameterized import parameterized +from torch.fx import symbolic_trace + +from accelerate.big_modeling import attach_layerwise_casting_hooks +from accelerate.hooks import ( + AlignDevicesHook, + ModelHook, + SequentialHook, + add_hook_to_module, + attach_align_device_hook, + remove_hook_from_module, + remove_hook_from_submodules, +) +from accelerate.test_utils import require_multi_device, require_non_hpu, torch_device +from accelerate.utils.constants import SUPPORTED_PYTORCH_LAYERS_FOR_UPCASTING + + +torch_device = f"{torch_device}:0" if torch_device != "cpu" else "cpu" + + +class ModelForTest(nn.Module): + def __init__(self): + super().__init__() + self.linear1 = nn.Linear(3, 4) + self.batchnorm = nn.BatchNorm1d(4) + self.linear2 = nn.Linear(4, 5) + + def forward(self, x): + return self.linear2(self.batchnorm(self.linear1(x))) + + +class PreForwardHook(ModelHook): + def pre_forward(self, module, *args, **kwargs): + return (args[0] + 1,) + args[1:], kwargs + + +class PostForwardHook(ModelHook): + def post_forward(self, module, output): + return output + 1 + + +class HooksModelTester(unittest.TestCase): + def check_dtype_for_layerwise_upcasting( + self, + module, + storage_dtype, + loading_type, + patterns_to_check=None, + ): + for name, submodule in module.named_modules(): + attrs = [] + if getattr(submodule, "weight", None) is not None: + attrs.append(("weight", submodule.weight)) + if getattr(submodule, "bias", None) is not None: + attrs.append(("bias", submodule.bias)) + + if not isinstance(submodule, SUPPORTED_PYTORCH_LAYERS_FOR_UPCASTING): + if patterns_to_check is None: + for _, tensor in attrs: + self.assertEqual(tensor.dtype, loading_type) + continue + + if patterns_to_check and any(re.search(pat, name) for pat in patterns_to_check): + expected = loading_type + else: + expected = storage_dtype + + for _, tensor in attrs: + self.assertEqual(tensor.dtype, expected) + + def test_add_and_remove_hooks(self): + test_model = ModelForTest() + test_hook = ModelHook() + + add_hook_to_module(test_model, test_hook) + assert test_model._hf_hook == test_hook + assert hasattr(test_model, "_old_forward") + + # Check adding the hook did not change the name or the signature + assert test_model.forward.__name__ == "forward" + assert list(inspect.signature(test_model.forward).parameters) == ["x"] + + remove_hook_from_module(test_model) + assert not hasattr(test_model, "_hf_hook") + assert not hasattr(test_model, "_old_forward") + + def test_append_and_remove_hooks(self): + test_model = ModelForTest() + test_hook = ModelHook() + + add_hook_to_module(test_model, test_hook) + add_hook_to_module(test_model, test_hook, append=True) + + assert isinstance(test_model._hf_hook, SequentialHook) is True + assert len(test_model._hf_hook.hooks) == 2 + assert hasattr(test_model, "_old_forward") + + # Check adding the hook did not change the name or the signature + assert test_model.forward.__name__ == "forward" + assert list(inspect.signature(test_model.forward).parameters) == ["x"] + + remove_hook_from_module(test_model) + assert not hasattr(test_model, "_hf_hook") + assert not hasattr(test_model, "_old_forward") + + def test_pre_forward_hook_is_executed(self): + test_model = ModelForTest() + x = torch.randn(2, 3) + expected = test_model(x + 1) + expected2 = test_model(x + 2) + + test_hook = PreForwardHook() + add_hook_to_module(test_model, test_hook) + output1 = test_model(x) + assert torch.allclose(output1, expected, atol=1e-5) + + # Attaching a hook to a model when it already has one replaces, does not chain + test_hook = PreForwardHook() + add_hook_to_module(test_model, test_hook) + output1 = test_model(x) + assert torch.allclose(output1, expected, atol=1e-5) + + # You need to use the sequential hook to chain two or more hooks + test_hook = SequentialHook(PreForwardHook(), PreForwardHook()) + add_hook_to_module(test_model, test_hook) + + output2 = test_model(x) + assert torch.allclose(output2, expected2, atol=1e-5) + + def test_post_forward_hook_is_executed(self): + test_model = ModelForTest() + x = torch.randn(2, 3) + output = test_model(x) + + test_hook = PostForwardHook() + add_hook_to_module(test_model, test_hook) + output1 = test_model(x) + assert torch.allclose(output1, (output + 1), atol=1e-5) + + # Attaching a hook to a model when it already has one replaces, does not chain + test_hook = PostForwardHook() + add_hook_to_module(test_model, test_hook) + output1 = test_model(x) + assert torch.allclose(output1, (output + 1), atol=1e-5) + + # You need to use the sequential hook to chain two or more hooks + test_hook = SequentialHook(PostForwardHook(), PostForwardHook()) + add_hook_to_module(test_model, test_hook) + + output2 = test_model(x) + assert torch.allclose(output2, output + 2, atol=1e-5) + + def test_no_grad_in_hook(self): + test_model = ModelForTest() + x = torch.randn(2, 3) + output = test_model(x) + + test_hook = PostForwardHook() + add_hook_to_module(test_model, test_hook) + output1 = test_model(x) + assert torch.allclose(output1, (output + 1)) + assert output1.requires_grad + + test_hook.no_grad = True + output1 = test_model(x) + assert not output1.requires_grad + + @require_non_hpu # hpu does not support device indexing "hpu:1" + @require_multi_device + def test_align_devices_as_model_parallelism(self): + model = ModelForTest() + # Everything is on CPU + assert model.linear1.weight.device == torch.device("cpu") + assert model.batchnorm.weight.device == torch.device("cpu") + assert model.linear2.weight.device == torch.device("cpu") + + # This will move each submodule on different devices + add_hook_to_module(model.linear1, AlignDevicesHook(execution_device=0)) + add_hook_to_module(model.batchnorm, AlignDevicesHook(execution_device=0)) + add_hook_to_module(model.linear2, AlignDevicesHook(execution_device=1)) + + assert model.linear1.weight.device == torch.device(torch_device) + assert model.batchnorm.weight.device == torch.device(torch_device) + assert model.batchnorm.running_mean.device == torch.device(torch_device) + assert model.linear2.weight.device == torch.device(torch_device.replace(":0", ":1")) + + # We can still make a forward pass. The input does not need to be on any particular device + x = torch.randn(2, 3) + output = model(x) + assert output.device == torch.device(torch_device.replace(":0", ":1")) + + # We can add a general hook to put back output on same device as input. + add_hook_to_module(model, AlignDevicesHook(io_same_device=True)) + x = torch.randn(2, 3).to(torch_device) + output = model(x) + assert output.device == torch.device(torch_device) + + def test_align_devices_as_cpu_offload(self): + model = ModelForTest() + + # Everything is on CPU + assert model.linear1.weight.device == torch.device("cpu") + assert model.batchnorm.weight.device == torch.device("cpu") + assert model.linear2.weight.device == torch.device("cpu") + + # This will move each submodule on different devices + hook_kwargs = {"execution_device": torch_device, "offload": True} + + add_hook_to_module(model.linear1, AlignDevicesHook(**hook_kwargs)) + add_hook_to_module(model.batchnorm, AlignDevicesHook(**hook_kwargs)) + add_hook_to_module(model.linear2, AlignDevicesHook(**hook_kwargs)) + + # Parameters have been offloaded, so on the meta device + assert model.linear1.weight.device == torch.device("meta") + assert model.batchnorm.weight.device == torch.device("meta") + assert model.linear2.weight.device == torch.device("meta") + # Buffers are not included in the offload by default, so are on the execution device + device = torch.device(hook_kwargs["execution_device"]) + assert model.batchnorm.running_mean.device == device + + x = torch.randn(2, 3) + output = model(x) + assert output.device == device + + # Removing hooks loads back the weights in the model. + remove_hook_from_module(model.linear1) + remove_hook_from_module(model.batchnorm) + remove_hook_from_module(model.linear2) + assert model.linear1.weight.device == torch.device("cpu") + assert model.batchnorm.weight.device == torch.device("cpu") + assert model.linear2.weight.device == torch.device("cpu") + + # Now test with buffers included in the offload + hook_kwargs = { + "execution_device": torch_device, + "offload": True, + "offload_buffers": True, + } + + add_hook_to_module(model.linear1, AlignDevicesHook(**hook_kwargs)) + add_hook_to_module(model.batchnorm, AlignDevicesHook(**hook_kwargs)) + add_hook_to_module(model.linear2, AlignDevicesHook(**hook_kwargs)) + + # Parameters have been offloaded, so on the meta device, buffers included + assert model.linear1.weight.device == torch.device("meta") + assert model.batchnorm.weight.device == torch.device("meta") + assert model.linear2.weight.device == torch.device("meta") + assert model.batchnorm.running_mean.device == torch.device("meta") + + x = torch.randn(2, 3) + output = model(x) + assert output.device == device + + # Removing hooks loads back the weights in the model. + remove_hook_from_module(model.linear1) + remove_hook_from_module(model.batchnorm) + remove_hook_from_module(model.linear2) + assert model.linear1.weight.device == torch.device("cpu") + assert model.batchnorm.weight.device == torch.device("cpu") + assert model.linear2.weight.device == torch.device("cpu") + + def test_attach_align_device_hook_as_cpu_offload(self): + model = ModelForTest() + + # Everything is on CPU + assert model.linear1.weight.device == torch.device("cpu") + assert model.batchnorm.weight.device == torch.device("cpu") + assert model.linear2.weight.device == torch.device("cpu") + + # This will move each submodule on different devices + execution_device = torch_device + attach_align_device_hook(model, execution_device=execution_device, offload=True) + + # Parameters have been offloaded, so on the meta device + assert model.linear1.weight.device == torch.device("meta") + assert model.batchnorm.weight.device == torch.device("meta") + assert model.linear2.weight.device == torch.device("meta") + # Buffers are not included in the offload by default, so are on the execution device + device = torch.device(execution_device) + assert model.batchnorm.running_mean.device == device + + x = torch.randn(2, 3) + output = model(x) + assert output.device == device + + # Removing hooks loads back the weights in the model. + remove_hook_from_submodules(model) + assert model.linear1.weight.device == torch.device("cpu") + assert model.batchnorm.weight.device == torch.device("cpu") + assert model.linear2.weight.device == torch.device("cpu") + + # Now test with buffers included in the offload + attach_align_device_hook(model, execution_device=execution_device, offload=True, offload_buffers=True) + + # Parameters have been offloaded, so on the meta device, buffers included + assert model.linear1.weight.device == torch.device("meta") + assert model.batchnorm.weight.device == torch.device("meta") + assert model.linear2.weight.device == torch.device("meta") + assert model.batchnorm.running_mean.device == torch.device("meta") + + x = torch.randn(2, 3) + output = model(x) + assert output.device == device + + # Removing hooks loads back the weights in the model. + remove_hook_from_submodules(model) + assert model.linear1.weight.device == torch.device("cpu") + assert model.batchnorm.weight.device == torch.device("cpu") + assert model.linear2.weight.device == torch.device("cpu") + + def test_attach_align_device_hook_as_cpu_offload_with_weight_map(self): + model = ModelForTest() + + # Everything is on CPU + assert model.linear1.weight.device == torch.device("cpu") + assert model.batchnorm.weight.device == torch.device("cpu") + assert model.linear2.weight.device == torch.device("cpu") + + # This will move each submodule on different devices + execution_device = torch_device + attach_align_device_hook( + model, execution_device=execution_device, offload=True, weights_map=model.state_dict() + ) + + # Parameters have been offloaded, so on the meta device + assert model.linear1.weight.device == torch.device("meta") + assert model.batchnorm.weight.device == torch.device("meta") + assert model.linear2.weight.device == torch.device("meta") + # Buffers are not included in the offload by default, so are on the execution device + device = torch.device(execution_device) + assert model.batchnorm.running_mean.device == device + + x = torch.randn(2, 3) + output = model(x) + assert output.device == device + + # Removing hooks loads back the weights in the model. + remove_hook_from_submodules(model) + assert model.linear1.weight.device == torch.device("cpu") + assert model.batchnorm.weight.device == torch.device("cpu") + assert model.linear2.weight.device == torch.device("cpu") + + # Now test with buffers included in the offload + attach_align_device_hook( + model, + execution_device=execution_device, + offload=True, + weights_map=model.state_dict(), + offload_buffers=True, + ) + + # Parameters have been offloaded, so on the meta device, buffers included + assert model.linear1.weight.device == torch.device("meta") + assert model.batchnorm.weight.device == torch.device("meta") + assert model.linear2.weight.device == torch.device("meta") + assert model.batchnorm.running_mean.device == torch.device("meta") + + x = torch.randn(2, 3) + output = model(x) + assert output.device == device + + # Removing hooks loads back the weights in the model. + remove_hook_from_submodules(model) + assert model.linear1.weight.device == torch.device("cpu") + assert model.batchnorm.weight.device == torch.device("cpu") + assert model.linear2.weight.device == torch.device("cpu") + + def test_add_remove_hook_fx_graph_module(self): + with torch.no_grad(): + test_model = ModelForTest() + test_hook = ModelHook() + + x = torch.randn(2, 3) + output1 = test_model(x) + + graph_model = symbolic_trace(test_model) + + output2 = graph_model(x) + + assert torch.allclose(output1, output2) + + add_hook_to_module(graph_model, test_hook) + remove_hook_from_module(graph_model, recurse=True) + + # We want to make sure that `add_hook_to_module` and `remove_hook_from_module` yields back an fx.GraphModule + # that behaves correctly (for example that is not frozen, see https://github.com/huggingface/accelerate/pull/2369). + # For that, we add a sigmoid node to the FX graph and make sure that the new output (output3 below) is different than + # the original model's output. + linear2_node = None + for node in graph_model.graph.nodes: + if node.name == "linear2": + linear2_node = node + assert linear2_node is not None + + graph_model.graph.inserting_after(linear2_node) + new_node = graph_model.graph.create_node( + op="call_function", target=torch.sigmoid, args=(linear2_node,), name="relu" + ) + + output_node = None + for node in graph_model.graph.nodes: + if node.name == "output": + output_node = node + assert output_node is not None + + output_node.replace_input_with(linear2_node, new_node) + + graph_model.graph.lint() + graph_model.recompile() + + output3 = graph_model(x) + + # Now the output is expected to be different since we modified the graph. + assert not torch.allclose(output1, output3) + + @parameterized.expand( + [ + (torch.float16, torch.float32), + (torch.float8_e4m3fn, torch.float32), + (torch.float8_e4m3fn, torch.float32, ["batchnorm"]), + ] + ) + def test_layerwise_upcasting_inference(self, storage_dtype, compute_dtype, skip_modules_pattern=None): + test_model = ModelForTest() + loading_dtype = next(test_model.parameters()).data.dtype + inputs = torch.randn(2, 3) + inputs = inputs.to(compute_dtype) if inputs.dtype == torch.float32 else inputs + + attach_layerwise_casting_hooks( + test_model, + storage_dtype=storage_dtype, + compute_dtype=compute_dtype, + skip_modules_pattern=skip_modules_pattern, + ) + patterns_to_check = skip_modules_pattern if skip_modules_pattern else None + self.check_dtype_for_layerwise_upcasting(test_model, storage_dtype, loading_dtype, patterns_to_check) + + with torch.no_grad(): + _ = test_model(inputs) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_imports.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..57e49dcd9a275ff7130c62aba4191512d3ead67d --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_imports.py @@ -0,0 +1,100 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import subprocess +import sys + +from accelerate.test_utils import require_transformer_engine +from accelerate.test_utils.testing import TempDirTestCase, require_import_timer +from accelerate.utils import is_import_timer_available + + +if is_import_timer_available(): + from import_timer import calculate_total_time, read_import_profile + from import_timer.core import get_paths_above_threshold, sort_nodes_by_total_time + + +def convert_list_to_string(data): + end_result = "" + arrow_right = "->" + for path in data: + end_result += f"{arrow_right.join(path[0])} {path[1]:.3f}s\n" + return end_result + + +def run_import_time(command: str): + output = subprocess.run([sys.executable, "-X", "importtime", "-c", command], capture_output=True, text=True) + return output.stderr + + +@require_import_timer +class ImportSpeedTester(TempDirTestCase): + """ + Test suite which checks if imports have seen slowdowns + based on a particular baseline. + + If the error messages are not clear enough to get a + full view of what is slowing things down (or to + figure out how deep the initial depth should be), + please view the profile with the `tuna` framework: + `tuna import.log`. + """ + + clear_on_setup = False + + @classmethod + def setUpClass(cls): + super().setUpClass() + output = run_import_time("import torch") + data = read_import_profile(output) + total_time = calculate_total_time(data) + cls.pytorch_time = total_time + + def test_base_import(self): + output = run_import_time("import accelerate") + data = read_import_profile(output) + total_time = calculate_total_time(data) + pct_more = (total_time - self.pytorch_time) / self.pytorch_time * 100 + # Base import should never be more than 20% slower than raw torch import + err_msg = f"Base import is more than 20% slower than raw torch import ({pct_more:.2f}%), please check the attached `tuna` profile:\n" + sorted_data = sort_nodes_by_total_time(data) + paths_above_threshold = get_paths_above_threshold(sorted_data, 0.05, max_depth=7) + err_msg += f"\n{convert_list_to_string(paths_above_threshold)}" + self.assertLess(pct_more, 20, err_msg) + + def test_cli_import(self): + output = run_import_time("from accelerate.commands.launch import launch_command_parser") + data = read_import_profile(output) + total_time = calculate_total_time(data) + pct_more = (total_time - self.pytorch_time) / self.pytorch_time * 100 + # Base import should never be more than 20% slower than raw torch import + err_msg = f"Base import is more than 20% slower than raw torch import ({pct_more:.2f}%), please check the attached `tuna` profile:\n" + sorted_data = sort_nodes_by_total_time(data) + paths_above_threshold = get_paths_above_threshold(sorted_data, 0.05, max_depth=7) + err_msg += f"\n{convert_list_to_string(paths_above_threshold)}" + self.assertLess(pct_more, 20, err_msg) + + +@require_transformer_engine +class LazyImportTester(TempDirTestCase): + """ + Test suite which checks if specific packages are lazy-loaded. + + Eager-import will trigger circular import in some case, + e.g. in huggingface/accelerate#3056. + """ + + def test_te_import(self): + output = run_import_time("import accelerate, accelerate.utils.transformer_engine") + + self.assertFalse(" transformer_engine" in output, "`transformer_engine` should not be imported on import") diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_kwargs_handlers.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_kwargs_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..a6239af6df497df500df26af458673779ca746be --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_kwargs_handlers.py @@ -0,0 +1,206 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import os +from dataclasses import dataclass + +import torch + +from accelerate import Accelerator, DistributedDataParallelKwargs, GradScalerKwargs +from accelerate.state import AcceleratorState +from accelerate.test_utils import ( + DEFAULT_LAUNCH_COMMAND, + execute_subprocess_async, + path_in_accelerate_package, + require_fp16, + require_multi_device, + require_non_cpu, + run_first, +) +from accelerate.test_utils.testing import AccelerateTestCase, slow +from accelerate.utils import ( + AutocastKwargs, + KwargsHandler, + ProfileKwargs, + TorchDynamoPlugin, + clear_environment, +) +from accelerate.utils.dataclasses import DistributedType + + +@dataclass +class MockClass(KwargsHandler): + a: int = 0 + b: bool = False + c: float = 3.0 + + +class KwargsHandlerTester(AccelerateTestCase): + def test_kwargs_handler(self): + # If no defaults are changed, `to_kwargs` returns an empty dict. + assert MockClass().to_kwargs() == {} + assert MockClass(a=2).to_kwargs() == {"a": 2} + assert MockClass(a=2, b=True).to_kwargs() == {"a": 2, "b": True} + assert MockClass(a=2, c=2.25).to_kwargs() == {"a": 2, "c": 2.25} + + @require_fp16 + @require_non_cpu + def test_grad_scaler_kwargs(self): + # If no defaults are changed, `to_kwargs` returns an empty dict. + scaler_handler = GradScalerKwargs(init_scale=1024, growth_factor=2) + AcceleratorState._reset_state() + accelerator = Accelerator(mixed_precision="fp16", kwargs_handlers=[scaler_handler]) + assert accelerator.mixed_precision == "fp16" + scaler = accelerator.scaler + + # Check the kwargs have been applied + assert scaler._init_scale == 1024.0 + assert scaler._growth_factor == 2.0 + + # Check the other values are at the default + assert scaler._backoff_factor == 0.5 + assert scaler._growth_interval == 2000 + assert scaler._enabled is True + + @run_first + @require_multi_device + def test_ddp_kwargs(self): + cmd = DEFAULT_LAUNCH_COMMAND + [inspect.getfile(self.__class__)] + execute_subprocess_async(cmd) + + @require_fp16 + @require_non_cpu + def test_autocast_kwargs(self): + kwargs = AutocastKwargs(enabled=False) + AcceleratorState._reset_state() + accelerator = Accelerator(mixed_precision="fp16") + + a_float32 = torch.rand((8, 8), device=accelerator.device) + b_float32 = torch.rand((8, 8), device=accelerator.device) + c_float32 = torch.rand((8, 8), device=accelerator.device) + d_float32 = torch.rand((8, 8), device=accelerator.device) + + with accelerator.autocast(): + e_float16 = torch.mm(a_float32, b_float32) + assert e_float16.dtype == torch.float16 + + with accelerator.autocast(autocast_handler=kwargs): + # Convert e_float16 to float32 + f_float32 = torch.mm(c_float32, e_float16.float()) + assert f_float32.dtype == torch.float32 + + g_float16 = torch.mm(d_float32, f_float32) + # We should be back in fp16 + assert g_float16.dtype == torch.float16 + + @slow + def test_profile_kwargs(self): + # Arrange + schedule_options = [ + dict(wait=1, warmup=1, active=2, repeat=1), + dict(wait=2, warmup=2, active=2, repeat=2), + dict(wait=0, warmup=1, active=3, repeat=3, skip_first=1), + dict(wait=3, warmup=2, active=1, repeat=1, skip_first=2), + dict(wait=1, warmup=0, active=1, repeat=5), + ] + + total_steps = 100 + + for option in schedule_options: + count = 0 + table_outputs = [] + steps_per_cycle = option["wait"] + option["warmup"] + option["active"] + effective_steps = max(0, total_steps - option.get("skip_first", 0)) + cycles = effective_steps // steps_per_cycle + if option["repeat"] > 0: + expected_count = min(cycles, option["repeat"]) + else: + expected_count = cycles + + def on_trace_ready(prof): + nonlocal count + nonlocal table_outputs + + count += 1 + table_outputs.append(prof.key_averages().table(sort_by="cpu_time_total", row_limit=-1)) + + kwargs = ProfileKwargs(activities=["cpu"], on_trace_ready=on_trace_ready, schedule_option=option) + accelerator = Accelerator(kwargs_handlers=[kwargs]) + + # Act + with accelerator.profile() as prof: + for _ in range(total_steps): + prof.step() + torch.tensor([1, 2, 3, 4, 5], device=accelerator.device) + + # Assert + assert isinstance(prof, torch.profiler.profile) + assert count == expected_count, f"Option: {option}, Expected count: {expected_count}, but got {count}" + for output in table_outputs: + self.assertIn("CPU time total:", output) + + def test_torch_dynamo_plugin(self): + with clear_environment(): + prefix = "ACCELERATE_DYNAMO_" + # nvfuser's dynamo backend name is "nvprims_nvfuser" + # use "nvfuser" here to cause exception if this test causes os.environ changed permanently + os.environ[prefix + "BACKEND"] = "aot_ts_nvfuser" + os.environ[prefix + "MODE"] = "reduce-overhead" + + dynamo_plugin_kwargs = TorchDynamoPlugin().to_kwargs() + assert dynamo_plugin_kwargs == {"backend": "aot_ts_nvfuser", "mode": "reduce-overhead"} + assert os.environ.get(prefix + "BACKEND") != "aot_ts_nvfuser" + + @run_first + @require_multi_device + def test_ddp_comm_hook(self): + cmd = DEFAULT_LAUNCH_COMMAND + [path_in_accelerate_package("test_utils", "scripts", "test_ddp_comm_hook.py")] + execute_subprocess_async(cmd) + + +def main(): + ddp_scaler = DistributedDataParallelKwargs(bucket_cap_mb=15, find_unused_parameters=True) + accelerator = Accelerator(kwargs_handlers=[ddp_scaler]) + + # Skip this test due to TorchXLA not using torch.nn.parallel.DistributedDataParallel for model wrapping. + if accelerator.distributed_type == DistributedType.XLA: + return + + model = torch.nn.Linear(100, 200) + model = accelerator.prepare(model) + + # Check the values changed in kwargs + error_msg = "" + observed_bucket_cap_map = model.bucket_bytes_cap // (1024 * 1024) + if observed_bucket_cap_map != 15: + error_msg += f"Kwargs badly passed, should have `15` but found {observed_bucket_cap_map}.\n" + if model.find_unused_parameters is not True: + error_msg += f"Kwargs badly passed, should have `True` but found {model.find_unused_parameters}.\n" + + # Check the values of the defaults + if model.dim != 0: + error_msg += f"Default value not respected, should have `0` but found {model.dim}.\n" + if model.broadcast_buffers is not True: + error_msg += f"Default value not respected, should have `True` but found {model.broadcast_buffers}.\n" + if model.gradient_as_bucket_view is not False: + error_msg += f"Default value not respected, should have `False` but found {model.gradient_as_bucket_view}.\n" + + # Raise error at the end to make sure we don't stop at the first failure. + if len(error_msg) > 0: + raise ValueError(error_msg) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_launch.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_launch.py new file mode 100644 index 0000000000000000000000000000000000000000..99cc6af8a92bea7a88d5c836a2500600e495140f --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_launch.py @@ -0,0 +1,73 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import unittest + +from accelerate.utils.launch import prepare_multi_gpu_env + + +class TestPrepareMultiGpuEnv(unittest.TestCase): + def test_auto_port_selection(self): + args = argparse.Namespace( + num_processes=1, + num_machines=1, + main_process_ip="127.0.0.1", + main_process_port=0, + machine_rank=0, + module=False, + no_python=False, + debug=False, + gpu_ids="all", + mixed_precision="no", + dynamo_backend="NO", + dynamo_mode="default", + dynamo_use_fullgraph=False, + dynamo_use_dynamic=False, + dynamo_use_regional_compilation=False, + use_fsdp=False, + fsdp_cpu_ram_efficient_loading=False, + fsdp_sync_module_states=False, + fsdp_version=None, + fsdp_sharding_strategy=None, + fsdp_reshard_after_forward=False, + fsdp_offload_params=False, + fsdp_min_num_params=0, + fsdp_auto_wrap_policy=None, + fsdp_transformer_layer_cls_to_wrap=None, + fsdp_backward_prefetch=None, + fsdp_state_dict_type=None, + fsdp_forward_prefetch=False, + fsdp_use_orig_params=False, + fsdp_activation_checkpointing=False, + use_tp=False, + tp_size=1, + use_megatron_lm=False, + megatron_lm_tp_degree=1, + megatron_lm_pp_degree=1, + megatron_lm_gradient_clipping=1.0, + megatron_lm_num_micro_batches=None, + megatron_lm_sequence_parallelism=None, + megatron_lm_recompute_activations=None, + megatron_lm_use_distributed_optimizer=None, + num_cpu_threads_per_process=1, + enable_cpu_affinity=False, + same_network=False, + use_parallelism_config=False, + ) + + prepare_multi_gpu_env(args) + self.assertIn("master_port", args.__dict__) + self.assertNotEqual(args.master_port, "0") + self.assertTrue(args.master_port.isdigit()) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_load_checkpoint_and_dispatch_with_broadcast.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_load_checkpoint_and_dispatch_with_broadcast.py new file mode 100644 index 0000000000000000000000000000000000000000..694276a51da60d69352307dac42a580eb86c480d --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_load_checkpoint_and_dispatch_with_broadcast.py @@ -0,0 +1,260 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import functools +import itertools +import unittest +from typing import Any, Callable + +import torch +from huggingface_hub import hf_hub_download +from torch import distributed as dist +from torch import nn +from torch.distributed._composable.fsdp import fully_shard +from torch.distributed._tensor import DTensor +from torch.distributed.device_mesh import init_device_mesh +from torch.distributed.fsdp.wrap import _recursive_wrap, transformer_auto_wrap_policy +from torch.nn.parallel import DistributedDataParallel + +from accelerate import init_empty_weights, load_checkpoint_and_dispatch +from accelerate.test_utils import ( + execute_subprocess_async, + get_torch_dist_unique_port, + require_multi_device, + run_first, + torch_device, +) +from accelerate.test_utils.testing import require_torch_min_version, require_transformers +from accelerate.utils.imports import is_hpu_available, is_transformers_available, is_xccl_available + + +if is_transformers_available(): + from transformers import AutoConfig, AutoModel + from transformers.models.gpt2.modeling_gpt2 import GPT2Block + + +def manage_process_group(func: Callable[..., Any]) -> Callable[..., Any]: + """Manage the creation and destruction of the distributed process group for the wrapped function.""" + + def wrapped(*args: Any, **kwargs: Any) -> Any: + torch_accelerator_module = getattr(torch, torch_device, torch.cuda) + # FIXME currently, we still need specify "ccl" backend to use torch-ccl, + # pytorch built-in xccl will be available from PyTorch 2.9, will remove this after we have xccl + if torch_device == "xpu" and not is_xccl_available(): + dist.init_process_group(backend="ccl", world_size=torch_accelerator_module.device_count()) + elif torch_device == "hpu" and is_hpu_available(init_hccl=True): + dist.init_process_group(backend="hccl", world_size=torch_accelerator_module.device_count()) + else: + dist.init_process_group(world_size=torch_accelerator_module.device_count()) + try: + return func(*args, **kwargs) + finally: + dist.destroy_process_group() + + return wrapped + + +@manage_process_group +def load_checkpoint_and_dispatch_fsdp2(): + torch_accelerator_module = getattr(torch, torch_device, torch.cuda) + torch_accelerator_module.set_device(device := torch.device(dist.get_rank())) + + pretrained_model_name_or_path = "bigscience/bloom-560m" + model_path = hf_hub_download("bigscience/bloom-560m", "pytorch_model.bin") + + model = AutoModel.from_pretrained(pretrained_model_name_or_path, device_map=device) + assert isinstance(model, nn.Module) + + with init_empty_weights(): + config = AutoConfig.from_pretrained(pretrained_model_name_or_path) + fsdp2_model = AutoModel.from_config(config) + fsdp2_model.tie_weights() + assert isinstance(fsdp2_model, nn.Module) + + mesh = init_device_mesh(device.type, (dist.get_world_size(),)) + fsdp2_model, _ = _recursive_wrap( + fsdp2_model, + auto_wrap_policy=functools.partial( + transformer_auto_wrap_policy, + transformer_layer_cls={ + GPT2Block, + type(fsdp2_model), + }, + ), + wrapper_cls=functools.partial( + fully_shard, + mesh=mesh, + ), + ignored_modules=set(), + ignored_params=set(), + ) + + fsdp2_model._apply( + lambda t: torch.empty_like(t, device=device) if t.device == torch.device("meta") else t.to(device) + ) + + load_checkpoint_and_dispatch(fsdp2_model, model_path, strict=True, broadcast_from_rank0=True) + + for (name, tensor), (fsdp2_name, fsdp2_tensor) in zip( + itertools.chain(model.named_parameters(), model.named_buffers()), + itertools.chain(fsdp2_model.named_parameters(), fsdp2_model.named_buffers()), + ): + assert name == fsdp2_name + assert isinstance(fsdp2_tensor, DTensor), fsdp2_name + torch.testing.assert_close(tensor, fsdp2_tensor.full_tensor(), msg=fsdp2_name) + + +@manage_process_group +def load_checkpoint_and_dispatch_no_broadcast_from_rank0(): + torch_accelerator_module = getattr(torch, torch_device, torch.cuda) + torch_accelerator_module.set_device(device := torch.device(dist.get_rank())) + + pretrained_model_name_or_path = "bigscience/bloom-560m" + model_path = hf_hub_download("bigscience/bloom-560m", "pytorch_model.bin") + + with init_empty_weights(): + config = AutoConfig.from_pretrained(pretrained_model_name_or_path) + broadcasted_model = AutoModel.from_config(config) + broadcasted_model.tie_weights() + assert isinstance(broadcasted_model, nn.Module) + + broadcasted_model._apply( + lambda t: torch.empty_like(t, device=device) if t.device == torch.device("meta") else t.to(device) + ) + + load_checkpoint_and_dispatch(broadcasted_model, model_path, strict=True, broadcast_from_rank0=True) + + with init_empty_weights(): + config = AutoConfig.from_pretrained(pretrained_model_name_or_path) + non_broadcasted_model = AutoModel.from_config(config) + non_broadcasted_model.tie_weights() + assert isinstance(non_broadcasted_model, nn.Module) + + non_broadcasted_model._apply( + lambda t: torch.empty_like(t, device=device) if t.device == torch.device("meta") else t.to(device) + ) + + load_checkpoint_and_dispatch(non_broadcasted_model, model_path, strict=True, broadcast_from_rank0=False) + + for (broadcasted_name, broadcasted_tensor), (non_broadcasted_name, non_broadcasted_tensor) in zip( + itertools.chain(broadcasted_model.named_parameters(), broadcasted_model.named_buffers()), + itertools.chain(non_broadcasted_model.named_parameters(), non_broadcasted_model.named_buffers()), + ): + assert broadcasted_name == non_broadcasted_name + torch.testing.assert_close(broadcasted_tensor, non_broadcasted_tensor, msg=broadcasted_name) + + +@manage_process_group +def load_checkpoint_and_dispatch_ddp(): + torch_accelerator_module = getattr(torch, torch_device, torch.cuda) + torch_accelerator_module.set_device(device := torch.device(dist.get_rank())) + + pretrained_model_name_or_path = "bigscience/bloom-560m" + model_path = hf_hub_download("bigscience/bloom-560m", "pytorch_model.bin") + + model = AutoModel.from_pretrained(pretrained_model_name_or_path, device_map=device) + assert isinstance(model, nn.Module) + + with init_empty_weights(): + config = AutoConfig.from_pretrained(pretrained_model_name_or_path) + ddp_model = AutoModel.from_config(config) + ddp_model.tie_weights() + assert isinstance(ddp_model, nn.Module) + + ddp_model._apply( + lambda t: torch.empty_like(t, device=device) if t.device == torch.device("meta") else t.to(device) + ) + ddp_model = DistributedDataParallel(ddp_model) + + load_checkpoint_and_dispatch(ddp_model.module, model_path, strict=True, broadcast_from_rank0=True) + + for (name, tensor), (ddp_name, ddp_tensor) in zip( + itertools.chain(model.named_parameters(), model.named_buffers()), + itertools.chain(ddp_model.module.named_parameters(), ddp_model.module.named_buffers()), + ): + assert name == ddp_name + torch.testing.assert_close(tensor, ddp_tensor, msg=ddp_name) + + +@require_torch_min_version(version="2.4.0") +@require_transformers +@require_multi_device +@run_first +class TestLoadCheckpointAndDispatchWithBroadcast(unittest.TestCase): + def setUp(self): + self.torch_accelerator_module = getattr(torch, torch_device, torch.cuda) + + def test_load_checkpoint_and_dispatch_fsdp2(self): + execute_subprocess_async( + cmd=[ + "torchrun", + f"--nproc_per_node={self.torch_accelerator_module.device_count()}", + f"--master_port={get_torch_dist_unique_port()}", + __file__, + "--fsdp2", + ], + ) + # successful return here == success - any errors would have caused an error in the sub-call + + def test_load_checkpoint_and_dispatch_no_broadcast_from_rank0(self): + execute_subprocess_async( + cmd=[ + "torchrun", + f"--nproc_per_node={self.torch_accelerator_module.device_count()}", + f"--master_port={get_torch_dist_unique_port()}", + __file__, + "--no_broadcast_from_rank0", + ], + ) + # successful return here == success - any errors would have caused an error in the sub-call + + def test_load_checkpoint_and_dispatch_ddp(self): + execute_subprocess_async( + cmd=[ + "torchrun", + f"--nproc_per_node={self.torch_accelerator_module.device_count()}", + f"--master_port={get_torch_dist_unique_port()}", + __file__, + "--ddp", + ], + ) + # successful return here == success - any errors would have caused an error in the sub-call + + +if __name__ == "__main__": + # The script below is meant to be run under torch.distributed, on a machine with multiple GPUs: + # + # PYTHONPATH="src" python -m torch.distributed.run --nproc_per_node 2 --output_dir output_dir ./tests/test_fsdp2.py --fsdp2 + + class CLIArgs(argparse.Namespace): + fsdp2: bool + ddp: bool + no_broadcast_from_rank0: bool + + parser = argparse.ArgumentParser() + group = parser.add_mutually_exclusive_group() + group.add_argument("--fsdp2", action="store_true") + group.add_argument("--ddp", action="store_true") + group.add_argument("--no_broadcast_from_rank0", action="store_true") + args = parser.parse_args(namespace=CLIArgs()) + + if args.fsdp2: + load_checkpoint_and_dispatch_fsdp2() + elif args.ddp: + load_checkpoint_and_dispatch_ddp + elif args.no_broadcast_from_rank0: + load_checkpoint_and_dispatch_no_broadcast_from_rank0() + else: + raise ValueError("Missing test selection") diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_logging.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..f1f6948da98833a688ac12e47bcdf6e4e8ce6f1c --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_logging.py @@ -0,0 +1,94 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import inspect +import logging +import os + +import pytest + +from accelerate import Accelerator +from accelerate.logging import get_logger +from accelerate.state import AcceleratorState + + +def current_lineno() -> int: + # A simple helper that returns the lineno of its call-site. + caller_frame = inspect.currentframe().f_back + caller_info = inspect.getframeinfo(caller_frame) + return caller_info.lineno + + +class CustomLogger(logging.LoggerAdapter): + # Mocks a user-defined custom logger wrapper that sets `stacklevel=3`. + def log(self, level, msg, *args, **kwargs): + # E.g. the user wants to modify `stacklevel`, `accelerate.logging` + # should respect the user's `stacklevel`. For the specific value + # of `3`, calling `CustomLogger.log()`, etc., should log that callsite, + # rather than the callsite of the following `self.logger.log()`. + kwargs["stacklevel"] = 3 + self.logger.log(level, msg, *args, **kwargs) + + +@pytest.fixture(scope="module") +def accelerator(): + accelerator = Accelerator() + yield accelerator + AcceleratorState._reset_state(True) + + +@pytest.mark.usefixtures("accelerator") +def test_log_stack(caplog): + logger = get_logger(__name__) + logging.basicConfig( + format="%(filename)s:%(name)s:%(lineno)s:%(funcName)s - %(message)s", + datefmt="%m/%d %H:%M:%S", + ) + + message = "Test" + lineno = current_lineno() + 1 # the next line is the actual callsite + logger.warning(message) + + assert len(caplog.records) == 1 + rec = caplog.records[0] + assert rec.levelname == logging.getLevelName(logging.WARNING) + assert rec.filename == os.path.basename(__file__) + assert rec.name == __name__ + assert rec.lineno == lineno + assert rec.funcName == test_log_stack.__name__ + assert rec.message == message + + +@pytest.mark.usefixtures("accelerator") +def test_custom_stacklevel(caplog): + wrapped_logger = get_logger(__name__) + logging.basicConfig( + format="%(filename)s:%(name)s:%(lineno)s:%(funcName)s - %(message)s", + datefmt="%m/%d %H:%M:%S", + ) + logger = CustomLogger(wrapped_logger, {}) + + message = "Test" + lineno = current_lineno() + 1 # the next line is the actual callsite + logger.warning(message) + + # `CustomLogger.log` set custom `stacklevel=3`, so `logger.warning` should + # log its callsite (rather than those of the `warpped_logger`). + assert len(caplog.records) == 1 + rec = caplog.records[0] + assert rec.levelname == logging.getLevelName(logging.WARNING) + assert rec.filename == os.path.basename(__file__) + assert rec.name == __name__ + assert rec.lineno == lineno + assert rec.funcName == test_custom_stacklevel.__name__ + assert rec.message == message diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_memory_utils.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_memory_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d1802981cad1dfc97bd167366c37ce5ec1066c05 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_memory_utils.py @@ -0,0 +1,184 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +from torch import nn + +from accelerate.test_utils import ( + memory_allocated_func, + require_non_cpu, + require_non_torch_xla, + torch_device, +) +from accelerate.utils.memory import find_executable_batch_size, release_memory + + +def raise_fake_out_of_memory(): + raise RuntimeError("CUDA out of memory.") + + +class ModelForTest(nn.Module): + def __init__(self): + super().__init__() + self.linear1 = nn.Linear(3, 4) + self.batchnorm = nn.BatchNorm1d(4) + self.linear2 = nn.Linear(4, 5) + + def forward(self, x): + return self.linear2(self.batchnorm(self.linear1(x))) + + +class BigModelForTest(ModelForTest): + def __init__(self): + super().__init__() + self.linear3 = nn.Linear(5, 1000) + + def forward(self, x): + return self.linear3(super().forward(x)) + + +class MemoryTest(unittest.TestCase): + def test_memory_implicit(self): + batch_sizes = [] + + @find_executable_batch_size(starting_batch_size=128) + def mock_training_loop_function(batch_size): + nonlocal batch_sizes + batch_sizes.append(batch_size) + if batch_size != 8: + raise_fake_out_of_memory() + + mock_training_loop_function() + assert batch_sizes == [ + 128, + 115, + 103, + 92, + 82, + 73, + 65, + 58, + 52, + 46, + 41, + 36, + 32, + 28, + 25, + 22, + 19, + 17, + 15, + 13, + 11, + 9, + 8, + ] + + def test_memory_explicit(self): + batch_sizes = [] + + @find_executable_batch_size(starting_batch_size=128) + def mock_training_loop_function(batch_size, arg1): + nonlocal batch_sizes + batch_sizes.append(batch_size) + if batch_size != 8: + raise_fake_out_of_memory() + return batch_size, arg1 + + bs, arg1 = mock_training_loop_function("hello") + assert batch_sizes == [ + 128, + 115, + 103, + 92, + 82, + 73, + 65, + 58, + 52, + 46, + 41, + 36, + 32, + 28, + 25, + 22, + 19, + 17, + 15, + 13, + 11, + 9, + 8, + ] + assert [bs, arg1] == [8, "hello"] + + def test_start_zero(self): + @find_executable_batch_size(starting_batch_size=0) + def mock_training_loop_function(batch_size): + pass + + with self.assertRaises(RuntimeError) as cm: + mock_training_loop_function() + assert "No executable batch size found, reached zero." in cm.exception.args[0] + + def test_approach_zero(self): + @find_executable_batch_size(starting_batch_size=16) + def mock_training_loop_function(batch_size): + if batch_size > 0: + raise_fake_out_of_memory() + pass + + with self.assertRaises(RuntimeError) as cm: + mock_training_loop_function() + assert "No executable batch size found, reached zero." in cm.exception.args[0] + + def test_verbose_guard(self): + @find_executable_batch_size(starting_batch_size=128) + def mock_training_loop_function(batch_size, arg1, arg2): + if batch_size != 8: + raise raise_fake_out_of_memory() + + with self.assertRaises(TypeError) as cm: + mock_training_loop_function(128, "hello", "world") + assert "Batch size was passed into `f`" in cm.exception.args[0] + assert "`f(arg1='hello', arg2='world')" in cm.exception.args[0] + + def test_any_other_error(self): + @find_executable_batch_size(starting_batch_size=16) + def mock_training_loop_function(batch_size): + raise ValueError("Oops, we had an error!") + + with self.assertRaises(ValueError) as cm: + mock_training_loop_function() + assert "Oops, we had an error!" in cm.exception.args[0] + + @require_non_cpu + @require_non_torch_xla + def test_release_memory(self): + starting_memory = memory_allocated_func() + + if torch_device.startswith("hpu"): + # hpu has a minimum memory allocation that cannot be released, + # we need to surpass it by using a bigger model (>5767296 bytes) + model = BigModelForTest() + else: + model = ModelForTest() + + model.to(torch_device) + assert memory_allocated_func() > starting_memory + model = release_memory(model) + assert memory_allocated_func() == starting_memory diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_metrics.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..c42acdb52ae6fe9697efe523100e91569ca6771e --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_metrics.py @@ -0,0 +1,63 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import numpy as np +from packaging import version + +from accelerate import debug_launcher +from accelerate.test_utils import ( + DEFAULT_LAUNCH_COMMAND, + device_count, + execute_subprocess_async, + path_in_accelerate_package, + require_cpu, + require_huggingface_suite, + require_multi_device, + require_single_device, + run_first, +) +from accelerate.utils import patch_environment + + +@require_huggingface_suite +@unittest.skipIf(version.parse(np.__version__) >= version.parse("2.0"), "Test requires numpy version < 2.0") +class MetricTester(unittest.TestCase): + def setUp(self): + self.test_file_path = path_in_accelerate_package("test_utils", "scripts", "external_deps", "test_metrics.py") + + from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 + + self.test_metrics = test_metrics + + @require_cpu + def test_metric_cpu_noop(self): + debug_launcher(self.test_metrics.main, num_processes=1) + + @require_cpu + def test_metric_cpu_multi(self): + debug_launcher(self.test_metrics.main) + + @require_single_device + def test_metric_accelerator(self): + self.test_metrics.main() + + @run_first + @require_multi_device + def test_metric_accelerator_multi(self): + print(f"Found {device_count} devices.") + cmd = DEFAULT_LAUNCH_COMMAND + [self.test_file_path] + with patch_environment(omp_num_threads=1, ACCELERATE_LOG_LEVEL="INFO"): + execute_subprocess_async(cmd) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_modeling_utils.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_modeling_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4857b3b5df22a3762280340a8b1902b249cd0c1c --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_modeling_utils.py @@ -0,0 +1,1067 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import os +import tempfile +import unittest +import warnings +from collections import OrderedDict +from typing import Optional + +import torch +import torch.nn as nn +from parameterized import parameterized +from safetensors.torch import save_file + +from accelerate import init_empty_weights +from accelerate.big_modeling import cpu_offload +from accelerate.test_utils import ( + require_huggingface_suite, + require_multi_device, + require_non_cpu, + require_non_hpu, + torch_device, +) +from accelerate.utils.modeling import ( + align_module_device, + check_device_map, + clean_device_map, + compute_module_sizes, + compute_module_total_buffer_size, + convert_file_size_to_int, + find_tied_parameters, + get_balanced_memory, + get_module_size_with_ties, + get_state_dict_offloaded_model, + infer_auto_device_map, + load_checkpoint_in_model, + load_state_dict, + named_module_tensors, + retie_parameters, + set_module_tensor_to_device, +) + + +torch_device = f"{torch_device}:0" if torch_device != "cpu" else "cpu" + + +class ModelForTest(nn.Module): + def __init__(self): + super().__init__() + self.linear1 = nn.Linear(3, 4) + self.batchnorm = nn.BatchNorm1d(4) + self.linear2 = nn.Linear(4, 5) + + def forward(self, x): + return self.linear2(self.batchnorm(self.linear1(x))) + + +class NestedModelForTest(nn.Module): + def __init__(self): + super().__init__() + self.model = ModelForTest() + + def forward(self, x): + return self.model(x) + + +class LinearWithNonPersistentBuffers(nn.Module): + def __init__(self, in_features: int, out_features: int, bias: bool = True, device=None, dtype=None) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.in_features = in_features + self.out_features = out_features + self.register_buffer("weight", torch.empty((out_features, in_features), **factory_kwargs)) + if bias: + self.register_buffer("bias", torch.empty(out_features, **factory_kwargs), persistent=False) + else: + self.register_buffer("bias", None) + + def forward(self, input: torch.Tensor) -> torch.Tensor: + return torch.nn.functional.linear(input, self.weight, self.bias) + + +class ModelSeveralDtypes(nn.Module): + def __init__(self): + super().__init__() + self.register_buffer("int_param", torch.randint(high=10, size=(15, 30))) + self.register_parameter("float_param", torch.nn.Parameter(torch.rand(10, 5))) + + def forward(self, x): + return x + 2 + + +def sequential_model(num_layers): + layers = OrderedDict([(f"linear{i}", nn.Linear(1000, 1000)) for i in range(1, num_layers + 1)]) + return nn.Sequential(layers) + + +class ModelingUtilsTester(unittest.TestCase): + def check_set_module_tensor_for_device(self, model, device1, device2): + assert model.linear1.weight.device == torch.device(device1) + + with self.subTest("Access by submodule and direct name for a parameter"): + set_module_tensor_to_device(model.linear1, "weight", device2) + assert model.linear1.weight.device == torch.device(device2) + + if torch.device(device2) == torch.device("meta"): + with self.assertRaises(ValueError): + # We need a `value` to set the weight back on device1 + set_module_tensor_to_device(model.linear1, "weight", device1) + + set_module_tensor_to_device(model.linear1, "weight", device1, value=torch.randn(4, 3)) + else: + set_module_tensor_to_device(model.linear1, "weight", device1) + assert model.linear1.weight.device == torch.device(device1) + + with self.subTest("Access by module and full name for a parameter"): + set_module_tensor_to_device(model, "linear1.weight", device2) + assert model.linear1.weight.device == torch.device(device2) + + if torch.device(device2) == torch.device("meta"): + with self.assertRaises(ValueError): + # We need a `value` to set the weight back on device1 + set_module_tensor_to_device(model, "linear1.weight", device1) + set_module_tensor_to_device(model, "linear1.weight", device1, value=torch.randn(4, 3)) + else: + set_module_tensor_to_device(model, "linear1.weight", device1) + assert model.linear1.weight.device == torch.device(device1) + + assert model.batchnorm.running_mean.device == torch.device(device1) + + with self.subTest("Access by submodule and direct name for a buffer"): + set_module_tensor_to_device(model.batchnorm, "running_mean", device2) + assert model.batchnorm.running_mean.device == torch.device(device2) + + if torch.device(device2) == torch.device("meta"): + with self.assertRaises(ValueError): + # We need a `value` to set the weight back on device1 + set_module_tensor_to_device(model.batchnorm, "running_mean", device1) + set_module_tensor_to_device(model.batchnorm, "running_mean", device1, value=torch.randn(4)) + else: + set_module_tensor_to_device(model.batchnorm, "running_mean", device1) + assert model.batchnorm.running_mean.device == torch.device(device1) + + with self.subTest("Access by module and full name for a parameter"): + set_module_tensor_to_device(model, "batchnorm.running_mean", device2) + assert model.batchnorm.running_mean.device == torch.device(device2) + + if torch.device(device2) == torch.device("meta"): + with self.assertRaises(ValueError): + # We need a `value` to set the weight back on CPU + set_module_tensor_to_device(model, "batchnorm.running_mean", device1) + + set_module_tensor_to_device(model, "batchnorm.running_mean", device1, value=torch.randn(4)) + else: + set_module_tensor_to_device(model, "batchnorm.running_mean", device1) + assert model.batchnorm.running_mean.device == torch.device(device1) + + def test_set_module_tensor_to_meta_and_cpu(self): + model = ModelForTest() + self.check_set_module_tensor_for_device(model, "cpu", "meta") + + @require_non_cpu + def test_set_module_tensor_to_cpu_and_gpu(self): + model = ModelForTest() + self.check_set_module_tensor_for_device(model, "cpu", torch_device) + + @require_non_cpu + def test_set_module_tensor_to_meta_and_gpu(self): + model = ModelForTest().to(torch_device) + self.check_set_module_tensor_for_device(model, torch_device, "meta") + + @require_non_hpu # hpu does not support device indexing "hpu:1" + @require_multi_device + def test_set_module_tensor_between_gpus(self): + model = ModelForTest().to(torch_device) + self.check_set_module_tensor_for_device(model, torch_device, torch_device.replace("0", "1")) + + def test_set_module_tensor_sets_dtype(self): + model = ModelForTest() + set_module_tensor_to_device(model, "linear1.weight", "cpu", value=model.linear1.weight, dtype=torch.float16) + assert model.linear1.weight.dtype == torch.float16 + + def test_set_module_tensor_checks_shape(self): + model = ModelForTest() + tensor = torch.zeros((2, 2)) + with self.assertRaises(ValueError) as cm: + set_module_tensor_to_device(model, "linear1.weight", "cpu", value=tensor) + assert ( + str(cm.exception) + == 'Trying to set a tensor of shape torch.Size([2, 2]) in "weight" (which has shape torch.Size([4, 3])), this looks incorrect.' + ) + + def test_named_tensors(self): + model = nn.BatchNorm1d(4) + named_tensors = named_module_tensors(model) + assert [name for name, _ in named_tensors] == [ + "weight", + "bias", + "running_mean", + "running_var", + "num_batches_tracked", + ] + + named_tensors = named_module_tensors(model, include_buffers=False) + assert [name for name, _ in named_tensors] == ["weight", "bias"] + + model = ModelForTest() + named_tensors = named_module_tensors(model) + assert [name for name, _ in named_tensors] == [] + + named_tensors = named_module_tensors(model, recurse=True) + assert [name for name, _ in named_tensors] == [ + "linear1.weight", + "linear1.bias", + "batchnorm.weight", + "batchnorm.bias", + "linear2.weight", + "linear2.bias", + "batchnorm.running_mean", + "batchnorm.running_var", + "batchnorm.num_batches_tracked", + ] + + named_tensors = named_module_tensors(model, include_buffers=False, recurse=True) + assert [name for name, _ in named_tensors] == [ + "linear1.weight", + "linear1.bias", + "batchnorm.weight", + "batchnorm.bias", + "linear2.weight", + "linear2.bias", + ] + + model = LinearWithNonPersistentBuffers(10, 10) + + named_tensors = named_module_tensors(model, include_buffers=True, remove_non_persistent=False) + assert [name for name, _ in named_tensors] == ["weight", "bias"] + + named_tensors = named_module_tensors(model, include_buffers=True, remove_non_persistent=True) + assert [name for name, _ in named_tensors] == ["weight"] + + def test_find_tied_parameters(self): + model = sequential_model(4) + assert find_tied_parameters(model) == [] + + model.linear2.weight = model.linear1.weight + assert find_tied_parameters(model) == [["linear1.weight", "linear2.weight"]] + + model.linear4.weight = model.linear1.weight + assert find_tied_parameters(model) == [["linear1.weight", "linear2.weight", "linear4.weight"]] + + model = sequential_model(5) + model.linear1.weight = model.linear4.weight + model.linear2.weight = model.linear3.weight + model.linear5.weight = model.linear2.weight + tied_params = sorted(find_tied_parameters(model), key=lambda x: len(x)) + assert tied_params == [ + ["linear1.weight", "linear4.weight"], + ["linear2.weight", "linear3.weight", "linear5.weight"], + ] + + model = nn.Sequential(OrderedDict([("block1", sequential_model(4)), ("block2", sequential_model(4))])) + model.block1.linear1.weight = model.block2.linear1.weight + assert find_tied_parameters(model) == [["block1.linear1.weight", "block2.linear1.weight"]] + + layer = nn.Linear(10, 10) + model = nn.Sequential(layer, layer) + tied_params = find_tied_parameters(model) + assert sorted(tied_params) == [["0.bias", "1.bias"], ["0.weight", "1.weight"]] + + def test_retie_parameters(self): + model = sequential_model(2) + retie_parameters(model, [["linear1.weight", "linear2.weight"]]) + assert model.linear1.weight is model.linear2.weight + + model = sequential_model(3) + retie_parameters(model, [["linear1.weight", "linear2.weight", "linear3.weight"]]) + + assert model.linear1.weight is model.linear2.weight + assert model.linear1.weight is model.linear3.weight + + model = sequential_model(5) + retie_parameters( + model, [["linear1.weight", "linear4.weight"], ["linear2.weight", "linear3.weight", "linear5.weight"]] + ) + + assert model.linear1.weight is model.linear4.weight + assert model.linear2.weight is model.linear3.weight + assert model.linear2.weight is model.linear5.weight + + model = nn.Sequential(OrderedDict([("block1", sequential_model(4)), ("block2", sequential_model(4))])) + retie_parameters(model, [["block1.linear1.weight", "block2.linear1.weight"]]) + + assert model.block1.linear1.weight is model.block2.linear1.weight + + def test_compute_module_sizes(self): + model = ModelForTest() + expected_sizes = {"": 236, "linear1": 64, "linear1.weight": 48, "linear1.bias": 16} + expected_sizes.update({"linear2": 100, "linear2.weight": 80, "linear2.bias": 20}) + expected_sizes.update({"batchnorm": 72, "batchnorm.weight": 16, "batchnorm.bias": 16}) + expected_sizes.update( + {"batchnorm.running_mean": 16, "batchnorm.running_var": 16, "batchnorm.num_batches_tracked": 8} + ) + + module_sizes = compute_module_sizes(model) + assert module_sizes == expected_sizes + + model.half() + expected_sizes = {k: s // 2 for k, s in expected_sizes.items()} + # This one is not converted to half. + expected_sizes["batchnorm.num_batches_tracked"] = 8 + # This impacts batchnorm and total + expected_sizes["batchnorm"] += 4 + expected_sizes[""] += 4 + + module_sizes = compute_module_sizes(model) + assert module_sizes == expected_sizes + + def test_compute_module_total_buffer_size(self): + model = ModelForTest() + model.linear1.register_buffer("test_buffer", torch.zeros(10, 10)) + model.register_buffer("test_buffer2", torch.zeros(20, 10)) + + buffer_size = compute_module_total_buffer_size(model) + assert buffer_size == 1240 + + model.half() + buffer_size = compute_module_total_buffer_size(model) + assert buffer_size == 624 + + def test_check_device_map(self): + model = ModelForTest() + check_device_map(model, {"": 0}) + with self.assertRaises(ValueError): + check_device_map(model, {"linear1": 0, "linear2": 1}) + + check_device_map(model, {"linear1": 0, "linear2": 1, "batchnorm": 1}) + + def test_check_device_map_invalid_keys(self): + model = ModelForTest() + + device_map = { + "linear1": "cpu", # Valid module + "batchnorm": "cpu", # Valid module + "linear2": "cpu", # Valid module + "invalid_module": 0, # Invalid - should trigger warning + "another_invalid": 1, # Invalid - should trigger warning + } + + # Test for the warning about invalid keys + with self.assertWarns(UserWarning) as cm: + check_device_map(model, device_map) + + warning_msg = str(cm.warning) + self.assertIn("device_map keys do not match any submodules", warning_msg) + self.assertIn("invalid_module", warning_msg) + self.assertIn("another_invalid", warning_msg) + + def shard_test_model(self, model, tmp_dir): + module_index = { + "linear1": "checkpoint_part1.bin", + "batchnorm": "checkpoint_part2.bin", + "linear2": "checkpoint_part3.bin", + } + index = {} + for name, _ in model.state_dict().items(): + module = name.split(".")[0] + index[name] = module_index[module] + + with open(os.path.join(tmp_dir, "weight_map.index.json"), "w") as f: + json.dump(index, f) + + for module, fname in module_index.items(): + state_dict = {k: v for k, v in model.state_dict().items() if k.startswith(module)} + full_fname = os.path.join(tmp_dir, fname) + torch.save(state_dict, full_fname) + + def test_load_checkpoint_in_model(self): + # Check with whole checkpoint + model = ModelForTest() + with tempfile.TemporaryDirectory() as tmp_dir: + fname = os.path.join(tmp_dir, "pt_model.bin") + torch.save(model.state_dict(), fname) + load_checkpoint_in_model(model, fname) + + # Check with sharded index + model = ModelForTest() + with tempfile.TemporaryDirectory() as tmp_dir: + self.shard_test_model(model, tmp_dir) + index_file = os.path.join(tmp_dir, "weight_map.index.json") + load_checkpoint_in_model(model, index_file) + + # Check with sharded checkpoint + model = ModelForTest() + with tempfile.TemporaryDirectory() as tmp_dir: + self.shard_test_model(model, tmp_dir) + load_checkpoint_in_model(model, tmp_dir) + + @require_non_cpu + def test_load_checkpoint_in_model_one_gpu(self): + device_map = {"linear1": 0, "batchnorm": "cpu", "linear2": "cpu"} + + # Check with whole checkpoint + model = ModelForTest() + with tempfile.TemporaryDirectory() as tmp_dir: + fname = os.path.join(tmp_dir, "pt_model.bin") + torch.save(model.state_dict(), fname) + load_checkpoint_in_model(model, fname, device_map=device_map) + assert model.linear1.weight.device == torch.device(torch_device) + assert model.batchnorm.weight.device == torch.device("cpu") + assert model.linear2.weight.device == torch.device("cpu") + + # Check with sharded index + model = ModelForTest() + with tempfile.TemporaryDirectory() as tmp_dir: + self.shard_test_model(model, tmp_dir) + index_file = os.path.join(tmp_dir, "weight_map.index.json") + load_checkpoint_in_model(model, index_file, device_map=device_map) + + assert model.linear1.weight.device == torch.device(torch_device) + assert model.batchnorm.weight.device == torch.device("cpu") + assert model.linear2.weight.device == torch.device("cpu") + + # Check with sharded checkpoint folder + model = ModelForTest() + with tempfile.TemporaryDirectory() as tmp_dir: + self.shard_test_model(model, tmp_dir) + load_checkpoint_in_model(model, tmp_dir, device_map=device_map) + + assert model.linear1.weight.device == torch.device(torch_device) + assert model.batchnorm.weight.device == torch.device("cpu") + assert model.linear2.weight.device == torch.device("cpu") + + @require_non_cpu + def test_load_checkpoint_in_model_disk_offload(self): + device_map = {"linear1": "cpu", "batchnorm": "disk", "linear2": "cpu"} + + model = ModelForTest() + with tempfile.TemporaryDirectory() as tmp_dir: + fname = os.path.join(tmp_dir, "pt_model.bin") + torch.save(model.state_dict(), fname) + load_checkpoint_in_model(model, fname, device_map=device_map, offload_folder=tmp_dir) + assert model.linear1.weight.device == torch.device("cpu") + assert model.batchnorm.weight.device == torch.device("meta") + # Buffers are not offloaded by default + assert model.batchnorm.running_mean.device == torch.device("cpu") + assert model.linear2.weight.device == torch.device("cpu") + + model = ModelForTest() + with tempfile.TemporaryDirectory() as tmp_dir: + fname = os.path.join(tmp_dir, "pt_model.bin") + torch.save(model.state_dict(), fname) + load_checkpoint_in_model(model, fname, device_map=device_map, offload_folder=tmp_dir, offload_buffers=True) + assert model.linear1.weight.device == torch.device("cpu") + assert model.batchnorm.weight.device == torch.device("meta") + assert model.batchnorm.running_mean.device == torch.device("meta") + assert model.linear2.weight.device == torch.device("cpu") + + @require_non_hpu # hpu does not support device indexing "hpu:1" + @require_multi_device + def test_load_checkpoint_in_model_two_gpu(self): + device_map = {"linear1": 0, "batchnorm": "cpu", "linear2": 1} + + # Check with whole checkpoint + model = ModelForTest() + with tempfile.TemporaryDirectory() as tmp_dir: + fname = os.path.join(tmp_dir, "pt_model.bin") + torch.save(model.state_dict(), fname) + load_checkpoint_in_model(model, fname, device_map=device_map) + assert model.linear1.weight.device == torch.device(torch_device) + assert model.batchnorm.weight.device == torch.device("cpu") + assert model.linear2.weight.device == torch.device(torch_device.replace("0", "1")) + + # Check with sharded index + model = ModelForTest() + with tempfile.TemporaryDirectory() as tmp_dir: + self.shard_test_model(model, tmp_dir) + index_file = os.path.join(tmp_dir, "weight_map.index.json") + load_checkpoint_in_model(model, index_file, device_map=device_map) + + assert model.linear1.weight.device == torch.device(torch_device) + assert model.batchnorm.weight.device == torch.device("cpu") + assert model.linear2.weight.device == torch.device(torch_device.replace("0", "1")) + + # Check with sharded checkpoint + model = ModelForTest() + with tempfile.TemporaryDirectory() as tmp_dir: + self.shard_test_model(model, tmp_dir) + load_checkpoint_in_model(model, tmp_dir, device_map=device_map) + + assert model.linear1.weight.device == torch.device(torch_device) + assert model.batchnorm.weight.device == torch.device("cpu") + assert model.linear2.weight.device == torch.device(torch_device.replace("0", "1")) + + def test_load_checkpoint_in_model_dtype(self): + with tempfile.NamedTemporaryFile(suffix=".pt") as tmpfile: + model = ModelSeveralDtypes() + torch.save(model.state_dict(), tmpfile.name) + + new_model = ModelSeveralDtypes() + load_checkpoint_in_model( + new_model, tmpfile.name, offload_state_dict=True, dtype=torch.float16, device_map={"": "cpu"} + ) + + assert new_model.int_param.dtype == torch.int64 + assert new_model.float_param.dtype == torch.float16 + + @parameterized.expand([(None,), ({"": "cpu"},)]) + def test_load_checkpoint_in_model_unexpected_keys(self, device_map: Optional[dict]): + model = ModelForTest() + + state_dict = model.state_dict() + state_dict["foo"] = torch.rand(4, 5) + with tempfile.NamedTemporaryFile(suffix=".pt") as tmpfile: + torch.save(state_dict, tmpfile) + + model = ModelForTest() + + with self.assertLogs() as cm: + load_checkpoint_in_model(model, tmpfile.name, device_map=device_map) + + self.assertTrue(any("were not used when" in out for out in cm.output)) + + with self.assertRaises((ValueError, RuntimeError)): + load_checkpoint_in_model(model, tmpfile.name, device_map=device_map, strict=True) + + def test_clean_device_map(self): + # Regroup everything if all is on the same device + assert clean_device_map({"a": 0, "b": 0, "c": 0}) == {"": 0} + # Regroups children of level 1 on the same device + assert clean_device_map({"a.x": 0, "a.y": 0, "b.x": 1, "b.y": 1, "c": 1}) == {"a": 0, "b": 1, "c": 1} + # Regroups children of level 2 on the same device + assert clean_device_map({"a.x": 0, "a.y": 0, "b.x.0": 1, "b.x.1": 1, "b.y.0": 2, "b.y.1": 2, "c": 2}) == { + "a": 0, + "b.x": 1, + "b.y": 2, + "c": 2, + } + + def test_infer_auto_device_map(self): + model = ModelForTest() + # model has size 236: linear1 64, batchnorm 72, linear2 100 + try: + with self.assertLogs() as cm: + device_map = infer_auto_device_map(model, max_memory={0: 200, 1: 200}) + self.assertFalse(any("insufficient memory" in out for out in cm.output)) + except AssertionError: + # No logs exist; test passes implicitly + pass + + # only linear1 fits on device 0 as we keep memory available for the maximum layer in case of offload + assert device_map == {"linear1": 0, "batchnorm": 1, "linear2": 1} + + device_map = infer_auto_device_map(model, max_memory={0: 200, 1: 172, 2: 200}) + # On device 1, we don't care about keeping size available for the max layer, so even if there is just the + # size available for batchnorm + linear2, they fit here. + assert device_map == {"linear1": 0, "batchnorm": 1, "linear2": 1} + + model.linear1.weight = model.linear2.weight + device_map = infer_auto_device_map(model, max_memory={0: 200, 1: 200}) + # By tying weights, the whole model fits on device 0 + assert device_map == {"": 0} + + # When splitting a bigger model, the split is done at the layer level + model = nn.Sequential(ModelForTest(), ModelForTest(), ModelForTest()) + device_map = infer_auto_device_map(model, max_memory={0: 500, 1: 500}) + assert device_map == {"0": 0, "1.linear1": 0, "1.batchnorm": 0, "1.linear2": 1, "2": 1} + + # With no_split_module_classes, it's done at that module level + model = nn.Sequential(ModelForTest(), ModelForTest(), ModelForTest()) + device_map = infer_auto_device_map( + model, max_memory={0: 500, 1: 500}, no_split_module_classes=["ModelForTest"] + ) + assert device_map == {"0": 0, "1": 1, "2": 1} + + def test_infer_auto_device_map_with_tied_weights(self): + model = nn.Sequential( + OrderedDict([("layer1", ModelForTest()), ("layer2", ModelForTest()), ("layer3", ModelForTest())]) + ) + model.layer3.linear2.weight = model.layer1.linear2.weight + device_map = infer_auto_device_map(model, max_memory={0: 400, 1: 500}) + expected = {"layer1": 0, "layer3.linear2": 0, "layer2": 1, "layer3.linear1": 1, "layer3.batchnorm": 1} + assert device_map == expected + + # With three weights tied together + model.layer2.linear2.weight = model.layer1.linear2.weight + device_map = infer_auto_device_map(model, max_memory={0: 400, 1: 500}) + expected = { + "layer1": 0, + "layer2.linear2": 0, + "layer3.linear2": 0, + "layer2.linear1": 1, + "layer2.batchnorm": 1, + "layer3.linear1": 1, + "layer3.batchnorm": 1, + } + assert device_map == expected + + # With two groups of weights tied together + model.layer2.linear1.weight = model.layer1.linear1.weight + device_map = infer_auto_device_map(model, max_memory={0: 400, 1: 500}) + expected = { + "layer1": 0, + "layer2.linear1": 0, + "layer2.linear2": 0, + "layer3.linear2": 0, + "layer2.batchnorm": 1, + "layer3.linear1": 1, + "layer3.batchnorm": 1, + } + assert device_map == expected + + # With weights ties in the same module + model = nn.Sequential( + OrderedDict( + [ + ("linear1", nn.Linear(4, 4)), + ("linear2", nn.Linear(6, 6)), + ("linear3", nn.Linear(4, 4)), + ("linear4", nn.Linear(6, 6)), + ] + ) + ) + model.linear3.weight = model.linear1.weight + model.linear3.bias = model.linear1.bias + device_map = infer_auto_device_map(model, max_memory={0: 250, 1: 400}) + expected = {"linear1": 0, "linear2": 1, "linear3": 0, "linear4": 1} + assert device_map == expected + + # With tied weights sharing a same prefix name (`compute.weight` vs `compute.weight_submodule.parameter`) + class SubModule(torch.nn.Module): + def __init__(self, ref_to_parameter): + super().__init__() + self.parameter = ref_to_parameter + + def forward(self, x): + return self.x + torch.max(self.parameter) + + class LinearModuleAndSubModule(torch.nn.Linear): + def __init__(self, in_features, out_features): + super().__init__(in_features, out_features) + self.weight_submodule = SubModule(self.weight) + + def forward(self, x): + return torch.nn.functional.linear(self.weight_submodule(x), self.weight) + + class Model(torch.nn.Module): + def __init__(self): + super().__init__() + self.compute = LinearModuleAndSubModule(3, 8) + + def forward(self, x): + return self.compute(x) + + model = Model() + + device_memory = {0: 4, "cpu": 96000} # Low memory device, just to force splitting and trigger the error + infer_auto_device_map(model, device_memory) + + @require_huggingface_suite + def test_infer_auto_device_map_on_t0pp(self): + from transformers import AutoConfig, AutoModelForSeq2SeqLM + + config = AutoConfig.from_pretrained("bigscience/T0pp") + with init_empty_weights(): + model = AutoModelForSeq2SeqLM.from_config(config) + model.tie_weights() + + special_dtypes = {n: torch.float32 for n, _ in model.named_parameters() if "wo" in n} + max_memory = {0: 10**10, 1: 10**10, "cpu": 10**10} + device_map = infer_auto_device_map( + model, + no_split_module_classes=["T5Block"], + dtype=torch.float16, + max_memory=max_memory, + special_dtypes=special_dtypes, + ) + + # The 3 tied weights should all be on device 0 + assert device_map["shared"] == 0 + assert device_map["encoder.embed_tokens"] == 0 + assert device_map["decoder.embed_tokens"] == 0 + + def test_infer_auto_device_map_with_buffer_check(self): + model = ModelForTest() + model.linear1.register_buffer("test_buffer1", torch.zeros(10, 2)) + model.batchnorm.register_buffer("test_buffer2", torch.zeros(10, 3)) + model.linear2.register_buffer("test_buffer3", torch.zeros(10, 3)) + # model has size 236(parameters) + 360(buffers): linear1 64 + 80, batchnorm 72 + 160, linear2 100 + 120 + + # Only linear1 (144) fits on device 0, and remaining buffers (batchnorm's 160 + linear2's 120 = 280) won't fit + # device 0, because they will also be loaded to device 0 all at once when inferencing without offload_buffers + # Should print a warning as intended in such case + with self.assertWarns(Warning): + device_map = infer_auto_device_map(model, max_memory={0: 400, "cpu": "1GB"}) + assert device_map == {"linear1": 0, "batchnorm": "cpu", "linear2": "cpu"} + + # Only linear1 (144) fits on device 0, and remaining buffers (batchnorm's 160 + linear2's 120 = 280) won't fit + # device 0, but with offload_buffers they won't be loaded to device 0 all at once, so it's ok now + # Should NOT print a warning in such case + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + device_map = infer_auto_device_map(model, max_memory={0: 400, "cpu": "1GB"}, offload_buffers=True) + assert len(w) == 0 + assert device_map == {"linear1": 0, "batchnorm": "cpu", "linear2": "cpu"} + + def test_infer_auto_device_map_with_buffer_check_and_multi_devices(self): + model = ModelForTest() + model.linear1.register_buffer("test_buffer1", torch.zeros(10, 2)) + model.batchnorm.register_buffer("test_buffer2", torch.zeros(10, 3)) + model.linear2.register_buffer("test_buffer3", torch.zeros(10, 3)) + model.linear3 = nn.Linear(4, 5) + model.linear3.register_buffer("test_buffer4", torch.zeros(10, 2)) + # model has size 336(parameters) + 440(buffers): linear1 64 + 80, batchnorm 72 + 160, linear2 100 + 120, + # linear3 100 + 80 + + # Now we have two devices, linear1 will fit on device 0, batchnorm will fit on device 1, and the second device + # can hold all remaining buffers + # Should NOT print a warning in such case + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + device_map = infer_auto_device_map(model, max_memory={0: 400, 1: 400, "cpu": "1GB"}) + assert len(w) == 0 + assert device_map == {"linear1": 0, "batchnorm": 1, "linear2": "cpu", "linear3": "cpu"} + + # Now we have two devices, but neither the first nor the second device can hold all remaining buffers + # Should print a warning as intended in such case + with self.assertWarns(Warning): + device_map = infer_auto_device_map(model, max_memory={0: 400, 1: 200, "cpu": "1GB"}) + assert device_map == {"linear1": 0, "batchnorm": 1, "linear2": "cpu", "linear3": "cpu"} + + # Now we have two devices, neither can hold all the buffers, but we are using the offload_buffers=True + # Should NOT print a warning in such case + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + device_map = infer_auto_device_map(model, max_memory={0: 400, 1: 200, "cpu": "1GB"}, offload_buffers=True) + assert len(w) == 0 + assert device_map == {"linear1": 0, "batchnorm": 1, "linear2": "cpu", "linear3": "cpu"} + + def test_infer_auto_device_map_with_fallback_allocation(self): + # Create a model where modules cannot be allocated without fallback_allocation + # Define the inner module with its layers + inner_module = nn.Sequential( + OrderedDict([("linear1", nn.Linear(10, 4)), ("linear2", nn.Linear(4, 4)), ("linear3", nn.Linear(4, 8))]) + ) + + # Wrap the inner module in another module + model = nn.Sequential(OrderedDict([("module", inner_module)])) + + max_memory = {0: 256} + + # Without fallback_allocation + with self.assertLogs() as cm: + device_map = infer_auto_device_map(model, max_memory=max_memory, fallback_allocation=False) + # No module should be assigned to device 0 + assert all(device != 0 for device in device_map.values()) + # Check for warning about insufficient memory + self.assertTrue(any("insufficient memory" in out for out in cm.output)) + + # With fallback_allocation + try: + with self.assertLogs() as cm: + device_map = infer_auto_device_map(model, max_memory=max_memory, fallback_allocation=True) + self.assertFalse(any("insufficient memory" in out for out in cm.output)) + except AssertionError: + # No logs exist; test passes implicitly + pass + # At least one submodule should be assigned to device 0 + assert any(device == 0 for device in device_map.values()) + + expected_device_map = {"module.linear1": "disk", "module.linear2": 0, "module.linear3": "disk"} + assert device_map == expected_device_map + + def test_infer_auto_device_map_with_fallback_allocation_no_fit(self): + # Create a model where even the smallest submodules cannot fit + inner_module = nn.Sequential( + OrderedDict( + [("linear1", nn.Linear(10, 10)), ("linear2", nn.Linear(10, 10)), ("linear3", nn.Linear(10, 10))] + ) + ) + + # Wrap the inner module in another module + model = nn.Sequential(OrderedDict([("module", inner_module)])) + + max_memory = {0: 30} + + # With fallback_allocation + try: + with self.assertLogs() as cm: + device_map = infer_auto_device_map(model, max_memory=max_memory, fallback_allocation=True) + # No module should be assigned to device 0 + assert all(device != 0 for device in device_map.values()) + # Check for warning about insufficient memory + self.assertTrue(any("insufficient memory" in out for out in cm.output)) + except AssertionError: + # No logs exist; test passes implicitly + pass + + def test_infer_auto_device_map_with_fallback_allocation_partial_fit(self): + # Create a model with deeper hierarchy + class CustomModule(nn.Module): + def __init__(self): + super().__init__() + self.submodule1 = nn.Linear(20, 20) + self.submodule2 = nn.Linear(20, 20) + + model = nn.Sequential( + OrderedDict([("module1", CustomModule()), ("module2", CustomModule()), ("module3", CustomModule())]) + ) + + max_memory = {0: 5000} + + # With fallback_allocation + device_map = infer_auto_device_map(model, max_memory=max_memory, fallback_allocation=True) + # Check that at least some parameters are assigned to device 0 + assigned_to_device_0 = [name for name, device in device_map.items() if device == 0] + assert len(assigned_to_device_0) > 0 + + def test_infer_auto_device_map_with_fallback_allocation_tied_weights(self): + # Create a model with tied weights + class TiedWeightsModel(nn.Module): + def __init__(self): + super().__init__() + self.linear1 = nn.Linear(10, 10) + self.linear2 = nn.Linear(10, 10) + self.linear2.weight = self.linear1.weight + + model = TiedWeightsModel() + + max_memory = {0: 600} + + # With fallback_allocation + device_map = infer_auto_device_map(model, max_memory=max_memory, fallback_allocation=True) + # Check that tied modules are assigned correctly + expected_device_map = {"": 0} + assert device_map == expected_device_map + + def test_infer_auto_device_map_with_fallback_allocation_and_buffers(self): + # Create a model with buffers + model = nn.Sequential( + OrderedDict( + [("linear1", nn.Linear(10, 10)), ("batchnorm", nn.BatchNorm1d(10)), ("linear2", nn.Linear(10, 10))] + ) + ) + model.linear1.register_buffer("buffer1", torch.zeros(5)) + model.batchnorm.register_buffer("buffer2", torch.zeros(5)) + model.linear2.register_buffer("buffer3", torch.zeros(5)) + + max_memory = {0: 678} + + # With fallback_allocation and offload_buffers=False + with self.assertWarns(Warning) as cm: + device_map = infer_auto_device_map( + model, max_memory=max_memory, fallback_allocation=True, offload_buffers=False + ) + + # Check that the warning contains the expected message + warning_message = str(cm.warning) + assert "offload_buffers" in warning_message or "Current model requires" in warning_message + + # Verify that the entire model is assigned to device 0 + expected_device_map = {"batchnorm": 0, "linear1": "disk", "linear2": "disk"} + assert device_map == expected_device_map + + @require_non_cpu + def test_get_balanced_memory(self): + model = ModelForTest() + # model has size 236: linear1 64, batchnorm 72, linear2 100 + max_memory = get_balanced_memory(model, max_memory={0: 200, 1: 200}) + assert {0: 200, 1: 200} == max_memory + + # We should be able to set models on a non-contiguous sub-set of + max_memory = get_balanced_memory(model, max_memory={0: 200, 2: 200}) + assert {0: 200, 2: 200} == max_memory + + max_memory = get_balanced_memory(model, max_memory={0: 300, 1: 300}) + assert {0: 215, 1: 300} == max_memory + + # Last device always get max memory to give more buffer and avoid accidental CPU offload + max_memory = get_balanced_memory(model, max_memory={0: 300, 1: 500}) + assert {0: 215, 1: 500} == max_memory + + # Last device always get max memory to give more buffer, even if CPU is provided + max_memory = get_balanced_memory(model, max_memory={0: 300, "cpu": 1000}) + assert {0: 300, "cpu": 1000} == max_memory + + # If we set a device to 0, it's not counted. + max_memory = get_balanced_memory(model, max_memory={0: 0, 1: 300, 2: 300}) + assert {0: 0, 1: 215, 2: 300} == max_memory + + # If we set a device to 0, it's not counted. + max_memory = get_balanced_memory(model, max_memory={0: 0, "cpu": 100}) + assert {0: 0, "cpu": 100} == max_memory + + # Tests that get_module_size_with_ties returns the correct tied modules in + # models with tied parameters whose parent modules share the same name prefix + # See issue #3308: https://github.com/huggingface/accelerate/issues/3308 + def test_get_module_size_with_ties(self): + # Create a model with a ModuleList containing more than 10 elements + # so the names of some layers share the same prefix, e.g. "1" and "10" + num_layers = 15 + model = nn.ModuleList([nn.Linear(10, 10) for _ in range(num_layers)]) + # Tie .weight for all the layers + for i in range(1, num_layers): + model[i].weight = model[i - 1].weight + # Each tied parameter group is sorted in alphabetical ordering, + # mimicking the output of find_tied_parameters + tied_parameters = [sorted([f"{i}.weight" for i in range(num_layers)])] + # Compute module sizes + weight_size, bias_size = ( + model[0].weight.element_size() * model[0].weight.numel(), + model[0].bias.element_size() * model[0].bias.numel(), + ) + module_sizes = dict( + **{"": num_layers * (weight_size + bias_size)}, + **{f"{i}": (weight_size + bias_size) for i in range(num_layers)}, + **{f"{i}.weight": weight_size for i in range(num_layers)}, + **{f"{i}.bias": bias_size for i in range(num_layers)}, + ) + # Simulate the input for get_module_size_with_ties when invoked from infer_auto_device_map + # when the first module in model is being processed + modules_to_treat = list(model.named_children())[1:] + tied_params = tied_parameters[0][1:] + module_size = weight_size + bias_size + + module_size_with_ties, tied_module_names, tied_modules = get_module_size_with_ties( + tied_params, module_size, module_sizes, modules_to_treat + ) + # The expected lists are ordered using as key the module names, to follow + # the same order as the tied_parameters returned by find_tied_parameters + expected_tied_module_names, expected_tied_modules = map( + list, zip(*sorted(modules_to_treat, key=lambda x: x[0])) + ) + + assert module_size_with_ties == module_size + (num_layers - 1) * bias_size + assert tied_module_names == expected_tied_module_names + assert tied_modules == expected_tied_modules + + @require_non_cpu + def test_load_state_dict(self): + state_dict = {k: torch.randn(4, 5) for k in ["a", "b", "c"]} + device_maps = [{"a": "cpu", "b": 0, "c": "disk"}, {"a": 0, "b": 0, "c": "disk"}, {"a": 0, "b": 0, "c": 0}] + + for device_map in device_maps: + with tempfile.TemporaryDirectory() as tmp_dir: + checkpoint_file = os.path.join(tmp_dir, "model.safetensors") + save_file(state_dict, checkpoint_file, metadata={"format": "pt"}) + + loaded_state_dict = load_state_dict(checkpoint_file, device_map=device_map) + + for param, device in device_map.items(): + device = device if device != "disk" else "cpu" + assert loaded_state_dict[param].device == torch.device(device) + + def test_convert_file_size(self): + result = convert_file_size_to_int("0MB") + assert result == 0 + + result = convert_file_size_to_int("100MB") + assert result == (100 * (10**6)) + + result = convert_file_size_to_int("2GiB") + assert result == (2 * (2**30)) + + result = convert_file_size_to_int("512KiB") + assert result == (512 * (2**10)) + + result = convert_file_size_to_int("1.5GB") + assert result == (1.5 * (10**9)) + + result = convert_file_size_to_int("100KB") + assert result == (100 * (10**3)) + + result = convert_file_size_to_int(500) + assert result == 500 + + with self.assertRaises(ValueError): + convert_file_size_to_int("5MBB") + + with self.assertRaises(ValueError): + convert_file_size_to_int("5k0MB") + + with self.assertRaises(ValueError): + convert_file_size_to_int("-1GB") + + def test_get_state_dict_offloaded_model(self): + for model_cls in (ModelForTest, NestedModelForTest): + model = model_cls() + execution_device = torch.device(torch_device) + original_state_dict = model.state_dict() + + cpu_offload(model, execution_device=execution_device) + state_dict = get_state_dict_offloaded_model(model) + + assert original_state_dict.keys() == state_dict.keys() + for key in original_state_dict: + assert torch.equal(original_state_dict[key], state_dict[key]) + + def test_align_module_device_simple(self): + model = ModelForTest() + execution_device = torch.device(torch_device) + model_device = torch.device("cpu") + + # test default execution device + with align_module_device(model.batchnorm): + assert model.linear1.weight.device == model_device + assert model.batchnorm.weight.device == model_device + assert model.linear2.weight.device == model_device + assert model.linear1.weight.device == model_device + assert model.batchnorm.weight.device == model_device + assert model.linear2.weight.device == model_device + + # test with explicit execution device + with align_module_device(model.batchnorm, execution_device=execution_device): + assert model.linear1.weight.device == model_device + assert model.batchnorm.weight.device == execution_device + assert model.linear2.weight.device == model_device + assert model.linear1.weight.device == model_device + assert model.batchnorm.weight.device == model_device + assert model.linear2.weight.device == model_device + + def test_align_module_device_offloaded(self): + model = ModelForTest() + execution_device = torch.device(torch_device) + offload_device = torch.device("meta") + cpu_offload(model, execution_device=execution_device) + + # test default execution device + with align_module_device(model.batchnorm): + assert model.linear1.weight.device == offload_device + assert model.batchnorm.weight.device == execution_device + assert model.linear2.weight.device == offload_device + assert model.linear1.weight.device == offload_device + assert model.batchnorm.weight.device == offload_device + assert model.linear2.weight.device == offload_device + + # test with explicit execution device + with align_module_device(model.batchnorm, execution_device="cpu"): + assert model.linear1.weight.device == offload_device + assert model.batchnorm.weight.device == torch.device("cpu") + assert model.linear2.weight.device == offload_device + assert model.linear1.weight.device == offload_device + assert model.batchnorm.weight.device == offload_device + assert model.linear2.weight.device == offload_device + + def test_align_module_device_offloaded_nested(self): + model = NestedModelForTest() + execution_device = torch.device(torch_device) + align_device = torch.device("cpu") + cpu_offload(model, execution_device=execution_device) + for module in model.modules(): + with align_module_device(module, align_device): + for param in model.parameters(recurse=False): + assert param.device == align_device diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_multigpu.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_multigpu.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f588be533a44e00064392e1ea6bc03398ef615 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_multigpu.py @@ -0,0 +1,172 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import unittest + +import torch + +from accelerate import Accelerator +from accelerate.big_modeling import dispatch_model +from accelerate.test_utils import ( + DEFAULT_LAUNCH_COMMAND, + assert_exception, + device_count, + execute_subprocess_async, + get_launch_command, + path_in_accelerate_package, + require_huggingface_suite, + require_multi_device, + require_non_torch_xla, + require_pippy, + require_torchvision, + run_first, + torch_device, +) +from accelerate.utils import is_hpu_available, patch_environment + + +class MultiDeviceTester(unittest.TestCase): + test_file_path = path_in_accelerate_package("test_utils", "scripts", "test_script.py") + data_loop_file_path = path_in_accelerate_package("test_utils", "scripts", "test_distributed_data_loop.py") + operation_file_path = path_in_accelerate_package("test_utils", "scripts", "test_ops.py") + pippy_file_path = path_in_accelerate_package("test_utils", "scripts", "external_deps", "test_pippy.py") + merge_weights_file_path = path_in_accelerate_package("test_utils", "scripts", "test_merge_weights.py") + + @run_first + @require_multi_device + def test_multi_device(self): + print(f"Found {device_count} {torch_device} devices.") + cmd = DEFAULT_LAUNCH_COMMAND + [self.test_file_path] + with patch_environment(omp_num_threads=1): + execute_subprocess_async(cmd) + + @run_first + @require_multi_device + def test_multi_device_ops(self): + print(f"Found {device_count} {torch_device} devices.") + cmd = DEFAULT_LAUNCH_COMMAND + [self.operation_file_path] + with patch_environment(omp_num_threads=1): + execute_subprocess_async(cmd) + + @run_first + @require_multi_device + def test_pad_across_processes(self): + print(f"Found {device_count} {torch_device} devices.") + cmd = DEFAULT_LAUNCH_COMMAND + [inspect.getfile(self.__class__)] + with patch_environment(omp_num_threads=1): + execute_subprocess_async(cmd) + + @run_first + @require_multi_device + def test_multi_device_merge_fsdp_weights(self): + print(f"Found {device_count} {torch_device} devices.") + cmd = DEFAULT_LAUNCH_COMMAND + [self.merge_weights_file_path] + + env_kwargs = dict(omp_num_threads=1) + with patch_environment(**env_kwargs): + execute_subprocess_async(cmd) + + @run_first + @require_non_torch_xla + @require_multi_device + def test_distributed_data_loop(self): + """ + This TestCase checks the behaviour that occurs during distributed training or evaluation, + when the batch size does not evenly divide the dataset size. + """ + print(f"Found {device_count} devices, using 2 devices only") + cmd = get_launch_command(num_processes=2) + [self.data_loop_file_path] + + env_kwargs = dict(omp_num_threads=1) + if torch_device == "xpu": + env_kwargs.update(ze_affinity_mask="0,1") + elif torch_device == "npu": + env_kwargs.update(ascend_rt_visible_devices="0,1") + elif torch_device == "mlu": + env_kwargs.update(mlu_visible_devices="0,1") + elif torch_device == "sdaa": + env_kwargs.update(sdaa_visible_devices="0,1") + else: + env_kwargs.update(cuda_visible_devices="0,1") + + with patch_environment(**env_kwargs): + execute_subprocess_async(cmd) + + @run_first + @require_pippy + @require_torchvision + @require_multi_device + @require_huggingface_suite + def test_pippy(self): + """ + Checks the integration with the pippy framework + """ + print(f"Found {device_count} {torch_device} devices") + cmd = get_launch_command(multi_gpu=True, num_processes=device_count) + [self.pippy_file_path] + with patch_environment(omp_num_threads=1): + execute_subprocess_async(cmd) + + +if __name__ == "__main__": + accelerator = Accelerator() + shape = (accelerator.state.process_index + 2, 10) + tensor = torch.randint(0, 10, shape).to(accelerator.device) + + error_msg = "" + + tensor1 = accelerator.pad_across_processes(tensor) + if tensor1.shape[0] != accelerator.state.num_processes + 1: + error_msg += f"Found shape {tensor1.shape} but should have {accelerator.state.num_processes + 1} at dim 0." + index = accelerator.state.process_index + 2 + if not torch.equal(tensor1[:index], tensor): + error_msg += "Tensors have different values." + if not torch.all(tensor1[index:] == 0): + error_msg += "Padding was not done with the right value (0)." + + tensor2 = accelerator.pad_across_processes(tensor.clone(), pad_first=True) + if tensor2.shape[0] != accelerator.state.num_processes + 1: + error_msg += f"Found shape {tensor2.shape} but should have {accelerator.state.num_processes + 1} at dim 0." + index = accelerator.state.num_processes - accelerator.state.process_index - 1 + if not torch.equal(tensor2[index:], tensor): + error_msg += "Tensors have different values." + if not torch.all(tensor2[:index] == 0): + error_msg += "Padding was not done with the right value (0)." + + # Raise error at the end to make sure we don't stop at the first failure. + if len(error_msg) > 0: + raise ValueError(error_msg) + + # Check device_map + accelerator.print("Test `device_map` cannot be prepared.") + + class ModelForTest(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear1 = torch.nn.Linear(3, 4) + self.batchnorm = torch.nn.BatchNorm1d(4) + self.linear2 = torch.nn.Linear(4, 5) + + def forward(self, x): + return self.linear2(self.batchnorm(self.linear1(x))) + + if is_hpu_available(): + device_map = {"linear1": 0, "batchnorm": "cpu", "linear2": 0} + else: + device_map = {"linear1": 0, "batchnorm": "cpu", "linear2": 1} + + model = ModelForTest() + dispatch_model(model, device_map=device_map) + with assert_exception(ValueError, "You can't train a model that has been loaded with"): + model = accelerator.prepare_model(model) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_offload.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_offload.py new file mode 100644 index 0000000000000000000000000000000000000000..95566a4bcbfe5340e558b0717d6acbe2f2145c77 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_offload.py @@ -0,0 +1,114 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import unittest +from tempfile import TemporaryDirectory + +import torch +import torch.nn as nn + +from accelerate.utils import ( + OffloadedWeightsLoader, + extract_submodules_state_dict, + load_offloaded_weight, + offload_state_dict, + offload_weight, +) + + +class ModelForTest(nn.Module): + def __init__(self): + super().__init__() + self.linear1 = nn.Linear(3, 4) + self.batchnorm = nn.BatchNorm1d(4) + self.linear2 = nn.Linear(4, 5) + + def forward(self, x): + return self.linear2(self.batchnorm(self.linear1(x))) + + +class OffloadTester(unittest.TestCase): + def test_offload_state_dict(self): + model = ModelForTest() + with TemporaryDirectory() as tmp_dir: + offload_state_dict(tmp_dir, model.state_dict()) + index_file = os.path.join(tmp_dir, "index.json") + assert os.path.isfile(index_file) + # TODO: add tests on what is inside the index + + for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: + weight_file = os.path.join(tmp_dir, f"{key}.dat") + assert os.path.isfile(weight_file) + # TODO: add tests on the fact weights are properly loaded + + def test_offload_weight(self): + dtypes = [torch.float16, torch.float32, torch.bfloat16] + + for dtype in dtypes: + weight = torch.randn(2, 3, dtype=dtype) + with TemporaryDirectory() as tmp_dir: + index = offload_weight(weight, "weight", tmp_dir, {}) + weight_file = os.path.join(tmp_dir, "weight.dat") + assert os.path.isfile(weight_file) + assert index == {"weight": {"shape": [2, 3], "dtype": str(dtype).split(".")[1]}} + + new_weight = load_offloaded_weight(weight_file, index["weight"]) + assert torch.equal(weight, new_weight) + + def test_offload_weights_loader(self): + model = ModelForTest() + state_dict = model.state_dict() + cpu_part = {k: v for k, v in state_dict.items() if "linear2" not in k} + disk_part = {k: v for k, v in state_dict.items() if "linear2" in k} + + with TemporaryDirectory() as tmp_dir: + offload_state_dict(tmp_dir, disk_part) + weight_map = OffloadedWeightsLoader(state_dict=cpu_part, save_folder=tmp_dir) + + # Every key is there with the right value + assert sorted(weight_map) == sorted(state_dict.keys()) + for key, param in state_dict.items(): + assert torch.allclose(param, weight_map[key]) + + cpu_part = {k: v for k, v in state_dict.items() if "weight" in k} + disk_part = {k: v for k, v in state_dict.items() if "weight" not in k} + + with TemporaryDirectory() as tmp_dir: + offload_state_dict(tmp_dir, disk_part) + weight_map = OffloadedWeightsLoader(state_dict=cpu_part, save_folder=tmp_dir) + + # Every key is there with the right value + assert sorted(weight_map) == sorted(state_dict.keys()) + for key, param in state_dict.items(): + assert torch.allclose(param, weight_map[key]) + + with TemporaryDirectory() as tmp_dir: + offload_state_dict(tmp_dir, state_dict) + # Duplicates are removed + weight_map = OffloadedWeightsLoader(state_dict=cpu_part, save_folder=tmp_dir) + + # Every key is there with the right value + assert sorted(weight_map) == sorted(state_dict.keys()) + for key, param in state_dict.items(): + assert torch.allclose(param, weight_map[key]) + + def test_extract_submodules_state_dict(self): + state_dict = {"a.1": 0, "a.10": 1, "a.2": 2} + extracted = extract_submodules_state_dict(state_dict, ["a.1", "a.2"]) + assert extracted == {"a.1": 0, "a.2": 2} + + state_dict = {"a.1.a": 0, "a.10.a": 1, "a.2.a": 2} + extracted = extract_submodules_state_dict(state_dict, ["a.1", "a.2"]) + assert extracted == {"a.1.a": 0, "a.2.a": 2} diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_optimizer.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..8bb324f0ec5b73bbef66a4742a44b1c60ec13615 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_optimizer.py @@ -0,0 +1,82 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pickle + +import torch + +from accelerate import Accelerator +from accelerate.test_utils import require_cpu, require_fp16, require_non_cpu +from accelerate.test_utils.testing import AccelerateTestCase + + +@require_cpu +class CPUOptimizerTester(AccelerateTestCase): + def test_accelerated_optimizer_pickling(self): + model = torch.nn.Linear(10, 10) + optimizer = torch.optim.SGD(model.parameters(), 0.1) + accelerator = Accelerator() + optimizer = accelerator.prepare(optimizer) + try: + pickle.loads(pickle.dumps(optimizer)) + except Exception as e: + self.fail(f"Accelerated optimizer pickling failed with {e}") + + +@require_fp16 +@require_non_cpu +class OptimizerTester(AccelerateTestCase): + def test_accelerated_optimizer_step_was_skipped(self): + model = torch.nn.Linear(5, 5) + optimizer = torch.optim.SGD(model.parameters(), 0.1) + accelerator = Accelerator(mixed_precision="fp16") + model, optimizer = accelerator.prepare(model, optimizer) + + loss = model(torch.randn(2, 5, device=accelerator.device)).sum() + accelerator.backward(loss) + for p in model.parameters(): + # Fake the gradients, as if there's no overflow + p.grad.fill_(0.01) + + optimizer.step() + assert optimizer.step_was_skipped is False + + loss = model(torch.randn(2, 5, device=accelerator.device)).sum() + accelerator.backward(loss) + for p in model.parameters(): + p.grad.fill_(0.01) + # Manually set the gradients to be NaN, as if there's an overflow + p.grad[0] = torch.tensor(float("nan")) + + optimizer.step() + assert optimizer.step_was_skipped is True + + loss = model(torch.randn(2, 5, device=accelerator.device)).sum() + accelerator.backward(loss) + for p in model.parameters(): + p.grad.fill_(0.01) + # Manually set the gradients to be NaN, as if there's an overflow + p.grad[0] = torch.tensor(float("nan")) + + optimizer.step() + assert optimizer.step_was_skipped is True + + loss = model(torch.randn(2, 5, device=accelerator.device)).sum() + accelerator.backward(loss) + for p in model.parameters(): + # Fake the gradients, as if there's no overflow + p.grad.fill_(0.01) + + optimizer.step() + assert optimizer.step_was_skipped is False diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_quantization.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_quantization.py new file mode 100644 index 0000000000000000000000000000000000000000..072473a952a8747c7d325008ba65179ad80659c7 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_quantization.py @@ -0,0 +1,962 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import tempfile +import unittest + +import torch +import torch.nn as nn + +from accelerate import Accelerator, init_empty_weights +from accelerate.test_utils import ( + require_bnb, + require_cuda_or_xpu, + require_huggingface_suite, + require_multi_device, + require_non_torch_xla, + slow, +) +from accelerate.test_utils.testing import AccelerateTestCase +from accelerate.utils.bnb import load_and_quantize_model +from accelerate.utils.dataclasses import BnbQuantizationConfig +from accelerate.utils.memory import clear_device_cache + + +class BitsAndBytesConfigIntegration(unittest.TestCase): + def test_BnbQuantizationConfig(self): + with self.assertRaises(ValueError): + BnbQuantizationConfig(load_in_8bit=True, load_in_4bit=True) + + +@require_non_torch_xla +@slow +@require_cuda_or_xpu +@require_bnb +@require_huggingface_suite +class MixedInt8EmptyModelTest(AccelerateTestCase): + # We keep the constants inside the init function and model loading inside setUp function + + # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) + # Therefore here we use only bloom-1b3 to test our module + model_name = "marcsun13/bloom-1b7_with_lm_head" + + # Constant values + # This was obtained on a Quadro RTX 8000 so the number might slightly change + EXPECTED_RELATIVE_DIFFERENCE = 1.540025 + + input_text = "Hello my name is" + EXPECTED_OUTPUT = "Hello my name is John.\nI am a friend of the family.\n" + MAX_NEW_TOKENS = 10 + + def setUp(self): + """ + Setup quantized model from empty model + """ + from huggingface_hub import hf_hub_download + from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer + + # Models and tokenizer + self.model_fp16 = AutoModelForCausalLM.from_pretrained( + self.model_name, torch_dtype=torch.float16, device_map="auto" + ) + + # create model on meta device + with init_empty_weights(): + self.model_8bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name)) + self.model_8bit.tie_weights() + + self.weights_location = hf_hub_download(self.model_name, "pytorch_model.bin") + self.bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True) + + self.model_8bit = load_and_quantize_model( + self.model_8bit, + self.bnb_quantization_config, + weights_location=self.weights_location, + device_map={"": 0}, + no_split_module_classes=["BloomBlock"], + ) + + self.tokenizer = AutoTokenizer.from_pretrained("bigscience/bloom-1b7") + self.accelerate = Accelerator() + + def tearDown(self): + r""" + TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + del self.model_fp16 + del self.model_8bit + + clear_device_cache(garbage_collection=True) + + def test_memory_footprint(self): + r""" + A simple test to check if the model conversion has been done correctly by checking on the + memory footprint of the converted model and the class type of the linear layers of the converted models + """ + from bitsandbytes.nn import Int8Params + + mem_fp16 = self.model_fp16.get_memory_footprint() + mem_8bit = self.model_8bit.get_memory_footprint() + + assert round((mem_fp16 / mem_8bit) - self.EXPECTED_RELATIVE_DIFFERENCE, 7) >= 0 + assert self.model_8bit.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Int8Params + + def test_linear_are_8bit(self): + r""" + A simple test to check if the model conversion has been done correctly by checking on the + memory footprint of the converted model and the class type of the linear layers of the converted models + """ + + self.model_fp16.get_memory_footprint() + self.model_8bit.get_memory_footprint() + + for name, module in self.model_8bit.named_modules(): + if isinstance(module, torch.nn.Linear): + modules_not_converted = ( + self.bnb_quantization_config.keep_in_fp32_modules + self.bnb_quantization_config.skip_modules + ) + if name not in modules_not_converted: + assert module.weight.dtype == torch.int8 + + def test_llm_skip(self): + r""" + A simple test to check if `llm_int8_skip_modules` works as expected + """ + import bitsandbytes as bnb + from transformers import AutoConfig, AutoModelForCausalLM + + bnb_quantization_config = BnbQuantizationConfig( + load_in_8bit=True, skip_modules=["lm_head", "transformer.word_embeddings"] + ) + + with init_empty_weights(): + model = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name)) + + model.tie_weights() + model = load_and_quantize_model( + model, + bnb_quantization_config, + weights_location=self.weights_location, + device_map="auto", + no_split_module_classes=["BloomBlock"], + ) + + assert model.transformer.h[1].mlp.dense_4h_to_h.weight.dtype == torch.int8 + assert isinstance(model.transformer.h[1].mlp.dense_4h_to_h, bnb.nn.Linear8bitLt) + assert isinstance(model.lm_head, nn.Linear) + assert model.lm_head.weight.dtype != torch.int8 + + def check_inference_correctness(self, model): + r""" + Test the generation quality of the quantized model and see that we are matching the expected output. + Given that we are operating on small numbers + the testing model is relatively small, we might not get + the same output across GPUs. So we'll generate few tokens (5-10) and check their output. + """ + # Check that inference pass works on the model + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + # Check the exactness of the results + output_parallel = model.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10) + + # Get the generation + output_text = self.tokenizer.decode(output_parallel[0], skip_special_tokens=True) + assert output_text == self.EXPECTED_OUTPUT + + def test_generate_quality(self): + self.check_inference_correctness(self.model_8bit) + + def test_fp32_8bit_conversion(self): + r""" + Test whether it is possible to mix both `8bit` and `fp32` weights when using `keep_in_fp32_modules` correctly. + """ + from transformers import AutoConfig, AutoModelForCausalLM + + bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True, keep_in_fp32_modules=["lm_head"]) + + with init_empty_weights(): + model = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name)) + + model.tie_weights() + model = load_and_quantize_model( + model, + bnb_quantization_config, + weights_location=self.weights_location, + device_map="auto", + no_split_module_classes=["BloomBlock"], + ) + assert model.lm_head.weight.dtype == torch.float32 + + @require_multi_device + def test_cpu_gpu_loading_custom_device_map(self): + from bitsandbytes.nn import Int8Params + from transformers import AutoConfig, AutoModelForCausalLM + + r""" + A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map`. + """ + device_map = { + "transformer.word_embeddings": "cpu", + "transformer.word_embeddings_layernorm": 0, + "lm_head": "cpu", + "transformer.h.0": "cpu", + "transformer.h.1": "cpu", + "transformer.h.2": "cpu", + "transformer.h.3": 0, + "transformer.h.4": 0, + "transformer.h.5": 0, + "transformer.h.6": 0, + "transformer.h.7": 0, + "transformer.h.8": 0, + "transformer.h.9": 1, + "transformer.h.10": 0, + "transformer.h.11": 1, + "transformer.h.12": 0, + "transformer.h.13": 0, + "transformer.h.14": 1, + "transformer.h.15": 0, + "transformer.h.16": 0, + "transformer.h.17": 1, + "transformer.h.18": 1, + "transformer.h.19": 0, + "transformer.h.20": 1, + "transformer.h.21": 1, + "transformer.h.22": 0, + "transformer.h.23": 0, + "transformer.ln_f": 1, + } + bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True) + + with init_empty_weights(): + model_8bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name)) + + model_8bit.tie_weights() + model_8bit = load_and_quantize_model( + model_8bit, + bnb_quantization_config, + weights_location=self.weights_location, + device_map=device_map, + no_split_module_classes=["BloomBlock"], + ) + assert model_8bit.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Int8Params + assert model_8bit.transformer.h[1].mlp.dense_4h_to_h.weight.__class__ == Int8Params + self.check_inference_correctness(model_8bit) + + @require_multi_device + def test_cpu_gpu_loading_custom_device_map_offload_state_dict(self): + from bitsandbytes.nn import Int8Params + from transformers import AutoConfig, AutoModelForCausalLM + + r""" + A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map` and offload_state_dict=True. + """ + device_map = { + "transformer.word_embeddings": "cpu", + "transformer.word_embeddings_layernorm": 0, + "lm_head": "cpu", + "transformer.h.0": "cpu", + "transformer.h.1": "cpu", + "transformer.h.2": "cpu", + "transformer.h.3": 0, + "transformer.h.4": 0, + "transformer.h.5": 0, + "transformer.h.6": 0, + "transformer.h.7": 0, + "transformer.h.8": 0, + "transformer.h.9": 1, + "transformer.h.10": 0, + "transformer.h.11": 1, + "transformer.h.12": 0, + "transformer.h.13": 0, + "transformer.h.14": 1, + "transformer.h.15": 0, + "transformer.h.16": 0, + "transformer.h.17": 1, + "transformer.h.18": 1, + "transformer.h.19": 0, + "transformer.h.20": 1, + "transformer.h.21": 1, + "transformer.h.22": 0, + "transformer.h.23": 0, + "transformer.ln_f": 1, + } + + bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True) + + with init_empty_weights(): + model_8bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name)) + + model_8bit.tie_weights() + model_8bit = load_and_quantize_model( + model_8bit, + bnb_quantization_config, + weights_location=self.weights_location, + device_map=device_map, + no_split_module_classes=["BloomBlock"], + offload_state_dict=True, + ) + assert model_8bit.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Int8Params + assert model_8bit.transformer.h[1].mlp.dense_4h_to_h.weight.__class__ == Int8Params + self.check_inference_correctness(model_8bit) + + @require_multi_device + def test_cpu_gpu_disk_loading_custom_device_map_kwargs(self): + from bitsandbytes.nn import Int8Params + from transformers import AutoConfig, AutoModelForCausalLM + + r""" + A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map`. + This time we also add `disk` on the device_map - using the kwargs directly instead of the quantization config + """ + device_map = { + "transformer.word_embeddings": "cpu", + "transformer.word_embeddings_layernorm": 0, + "lm_head": "cpu", + "transformer.h.0": "cpu", + "transformer.h.1": "cpu", + "transformer.h.2": "cpu", + "transformer.h.3": "disk", + "transformer.h.4": "disk", + "transformer.h.5": "disk", + "transformer.h.6": 0, + "transformer.h.7": 0, + "transformer.h.8": 0, + "transformer.h.9": 1, + "transformer.h.10": 0, + "transformer.h.11": 1, + "transformer.h.12": 0, + "transformer.h.13": 0, + "transformer.h.14": 1, + "transformer.h.15": 0, + "transformer.h.16": 0, + "transformer.h.17": 1, + "transformer.h.18": 1, + "transformer.h.19": 0, + "transformer.h.20": 1, + "transformer.h.21": 1, + "transformer.h.22": 0, + "transformer.h.23": 0, + "transformer.ln_f": 1, + } + bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True) + + with init_empty_weights(): + model_8bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name)) + model_8bit.tie_weights() + + with tempfile.TemporaryDirectory() as tmpdirname: + model_8bit = load_and_quantize_model( + model_8bit, + bnb_quantization_config, + weights_location=self.weights_location, + device_map=device_map, + no_split_module_classes=["BloomBlock"], + offload_folder=tmpdirname, + offload_state_dict=True, + ) + assert model_8bit.transformer.h[4].mlp.dense_4h_to_h.weight.__class__ == Int8Params + assert model_8bit.transformer.h[5].mlp.dense_4h_to_h.weight.__class__ == Int8Params + self.check_inference_correctness(model_8bit) + + def test_int8_serialization(self): + r""" + Test whether it is possible to serialize a model in 8-bit. + """ + from bitsandbytes.nn import Int8Params + from transformers import AutoConfig, AutoModelForCausalLM + + with tempfile.TemporaryDirectory() as tmpdirname: + # saving state dict for now but will save config and other in the future + self.accelerate.save_model(self.model_8bit, tmpdirname) + + with init_empty_weights(): + # let's suppose that we can get the right config + model_8bit_from_saved = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name)) + model_8bit_from_saved.tie_weights() + + bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True) + + model_8bit_from_saved = load_and_quantize_model( + model_8bit_from_saved, + bnb_quantization_config, + weights_location=tmpdirname, + device_map="auto", + no_split_module_classes=["BloomBlock"], + ) + + assert model_8bit_from_saved.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Int8Params + assert hasattr(model_8bit_from_saved.transformer.h[0].mlp.dense_4h_to_h.weight, "SCB") + assert hasattr(model_8bit_from_saved.transformer.h[0].mlp.dense_4h_to_h.weight, "CB") + + self.check_inference_correctness(model_8bit_from_saved) + + @require_multi_device + def test_int8_serialization_offload(self): + r""" + Test whether it is possible to serialize a model in 8-bit and offload weights to cpu/disk + """ + from bitsandbytes.nn import Int8Params + from transformers import AutoConfig, AutoModelForCausalLM + + with tempfile.TemporaryDirectory() as tmpdirname: + # saving state dict for now but will save config and other in the future + self.accelerate.save_model(self.model_8bit, tmpdirname) + + with init_empty_weights(): + # let's suppose that we can get the right config + model_8bit_from_saved = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name)) + model_8bit_from_saved.tie_weights() + bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True) + device_map = { + "transformer.word_embeddings": "cpu", + "transformer.word_embeddings_layernorm": 0, + "lm_head": "cpu", + "transformer.h.0": "cpu", + "transformer.h.1": "cpu", + "transformer.h.2": "cpu", + "transformer.h.3": "disk", + "transformer.h.4": "disk", + "transformer.h.5": "disk", + "transformer.h.6": 0, + "transformer.h.7": 0, + "transformer.h.8": 0, + "transformer.h.9": 1, + "transformer.h.10": 0, + "transformer.h.11": 1, + "transformer.h.12": 0, + "transformer.h.13": 0, + "transformer.h.14": 1, + "transformer.h.15": 0, + "transformer.h.16": 0, + "transformer.h.17": 1, + "transformer.h.18": 1, + "transformer.h.19": 0, + "transformer.h.20": 1, + "transformer.h.21": 1, + "transformer.h.22": 0, + "transformer.h.23": 0, + "transformer.ln_f": 1, + } + model_8bit_from_saved = load_and_quantize_model( + model_8bit_from_saved, + bnb_quantization_config, + weights_location=tmpdirname, + device_map=device_map, + no_split_module_classes=["BloomBlock"], + offload_folder=tmpdirname + "/tmp", + offload_state_dict=True, + ) + + assert model_8bit_from_saved.transformer.h[4].mlp.dense_4h_to_h.weight.__class__ == Int8Params + assert model_8bit_from_saved.transformer.h[5].mlp.dense_4h_to_h.weight.__class__ == Int8Params + self.check_inference_correctness(model_8bit_from_saved) + + def test_int8_serialization_shard(self): + r""" + Test whether it is possible to serialize a model in 8-bit. + """ + from bitsandbytes.nn import Int8Params + from transformers import AutoConfig, AutoModelForCausalLM + + with tempfile.TemporaryDirectory() as tmpdirname: + # saving state dict for now but will save config and other in the future + self.accelerate.save_model(self.model_8bit, tmpdirname, max_shard_size="1GB") + + with init_empty_weights(): + # let's suppose that we can get the right config + model_8bit_from_saved = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name)) + + model_8bit_from_saved.tie_weights() + + bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True) + + model_8bit_from_saved = load_and_quantize_model( + model_8bit_from_saved, + bnb_quantization_config, + weights_location=tmpdirname, + device_map="auto", + no_split_module_classes=["BloomBlock"], + ) + + assert model_8bit_from_saved.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Int8Params + assert hasattr(model_8bit_from_saved.transformer.h[0].mlp.dense_4h_to_h.weight, "SCB") + assert hasattr(model_8bit_from_saved.transformer.h[0].mlp.dense_4h_to_h.weight, "CB") + + self.check_inference_correctness(model_8bit_from_saved) + + +@require_non_torch_xla +@slow +@require_cuda_or_xpu +@require_bnb +@require_huggingface_suite +class MixedInt8LoaddedModelTest(unittest.TestCase): + # We keep the constants inside the init function and model loading inside setUp function + + # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) + # Therefore here we use only bloom-1b3 to test our module + model_name = "marcsun13/bloom-1b7_with_lm_head" + + # Constant values + # This was obtained on a Quadro RTX 8000 so the number might slightly change + EXPECTED_RELATIVE_DIFFERENCE = 1.540025 + + input_text = "Hello my name is" + EXPECTED_OUTPUT = "Hello my name is John.\nI am a friend of the family.\n" + MAX_NEW_TOKENS = 10 + + def setUp(self): + """ + Setup quantized model from loaded model + """ + from transformers import AutoModelForCausalLM, AutoTokenizer + + # Models and tokenizer + self.model_fp16 = AutoModelForCausalLM.from_pretrained( + self.model_name, torch_dtype=torch.float16, device_map="auto" + ) + + self.bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True) + + self.model_8bit = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype=torch.float16) + self.model_8bit = load_and_quantize_model(self.model_8bit, self.bnb_quantization_config) + + self.tokenizer = AutoTokenizer.from_pretrained("bigscience/bloom-1b7") + + def tearDown(self): + r""" + TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + del self.model_fp16 + del self.model_8bit + + clear_device_cache(garbage_collection=True) + + def test_memory_footprint(self): + r""" + A simple test to check if the model conversion has been done correctly by checking on the + memory footprint of the converted model and the class type of the linear layers of the converted models + """ + from bitsandbytes.nn import Int8Params + + mem_fp16 = self.model_fp16.get_memory_footprint() + mem_8bit = self.model_8bit.get_memory_footprint() + + assert round((mem_fp16 / mem_8bit) - self.EXPECTED_RELATIVE_DIFFERENCE, 7) >= 0 + assert self.model_8bit.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Int8Params + + def test_linear_are_8bit(self): + r""" + A simple test to check if the model conversion has been done correctly by checking on the + memory footprint of the converted model and the class type of the linear layers of the converted models + """ + + self.model_fp16.get_memory_footprint() + self.model_8bit.get_memory_footprint() + + for name, module in self.model_8bit.named_modules(): + if isinstance(module, torch.nn.Linear): + modules_not_converted = ( + self.bnb_quantization_config.keep_in_fp32_modules + self.bnb_quantization_config.skip_modules + ) + if name not in modules_not_converted: + assert module.weight.dtype == torch.int8 + + def test_generate_quality(self): + r""" + Test the generation quality of the quantized model and see that we are matching the expected output. + Given that we are operating on small numbers + the testing model is relatively small, we might not get + the same output across GPUs. So we'll generate few tokens (5-10) and check their output. + """ + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + output_sequences = self.model_8bit.generate( + input_ids=encoded_input["input_ids"].to(self.model_8bit.device), max_new_tokens=10 + ) + + assert self.tokenizer.decode(output_sequences[0], skip_special_tokens=True) == self.EXPECTED_OUTPUT + + def test_fp32_8bit_conversion(self): + r""" + Test whether it is possible to mix both `8bit` and `fp32` weights when using `keep_in_fp32_modules` correctly. + """ + from transformers import AutoModelForCausalLM + + bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True, keep_in_fp32_modules=["lm_head"]) + + model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype=torch.float16) + model = load_and_quantize_model(model, bnb_quantization_config) + assert model.lm_head.weight.dtype == torch.float32 + + +@require_non_torch_xla +@slow +@require_cuda_or_xpu +@require_bnb +@require_huggingface_suite +class Bnb4BitEmptyModelTest(unittest.TestCase): + # We keep the constants inside the init function and model loading inside setUp function + + # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) + # Therefore here we use only bloom-1b3 to test our module + model_name = "marcsun13/bloom-1b7_with_lm_head" + + # Constant values + # This was obtained on a RTX Titan so the number might slightly change + EXPECTED_RELATIVE_DIFFERENCE = 2.109659552692574 + + input_text = "Hello my name is" + EXPECTED_OUTPUTS = set() + EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer. I") + EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of your father.\n") + MAX_NEW_TOKENS = 10 + + def setUp(self): + from huggingface_hub import hf_hub_download + from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer + + super().setUp() + + # Models and tokenizer + self.model_fp16 = AutoModelForCausalLM.from_pretrained( + self.model_name, torch_dtype=torch.float16, device_map="auto" + ) + + # create model on meta device + with init_empty_weights(): + self.model_4bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name)) + + self.model_4bit.tie_weights() + self.weights_location = hf_hub_download(self.model_name, "pytorch_model.bin") + self.bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True) + + self.model_4bit = load_and_quantize_model( + self.model_4bit, + self.bnb_quantization_config, + weights_location=self.weights_location, + device_map={"": 0}, + no_split_module_classes=["BloomBlock"], + ) + + self.tokenizer = AutoTokenizer.from_pretrained("bigscience/bloom-1b7") + + def tearDown(self): + """ + TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + super().tearDown() + del self.model_fp16 + del self.model_4bit + + clear_device_cache(garbage_collection=True) + + def test_memory_footprint(self): + r""" + A simple test to check if the model conversion has been done correctly by checking on the + memory footprint of the converted model and the class type of the linear layers of the converted models + """ + from bitsandbytes.nn import Params4bit + + mem_fp16 = self.model_fp16.get_memory_footprint() + mem_4bit = self.model_4bit.get_memory_footprint() + + assert round((mem_fp16 / mem_4bit) - self.EXPECTED_RELATIVE_DIFFERENCE, 7) >= 0 + assert self.model_4bit.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Params4bit + + def check_inference_correctness(self, model): + r""" + Test the generation quality of the quantized model and see that we are matching the expected output. + Given that we are operating on small numbers + the testing model is relatively small, we might not get + the same output across GPUs. So we'll generate few tokens (5-10) and check their output. + """ + # Check that inference pass works on the model + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + # Check the exactness of the results + output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10) + + assert self.tokenizer.decode(output_sequences[0], skip_special_tokens=True) in self.EXPECTED_OUTPUTS + + def test_generate_quality(self): + self.check_inference_correctness(self.model_4bit) + + def test_linear_are_4bit(self): + r""" + A simple test to check if the model conversion has been done correctly by checking on the + memory footprint of the converted model and the class type of the linear layers of the converted models + """ + + self.model_fp16.get_memory_footprint() + self.model_4bit.get_memory_footprint() + + for name, module in self.model_4bit.named_modules(): + if isinstance(module, torch.nn.Linear): + if ( + name + not in self.bnb_quantization_config.keep_in_fp32_modules + + self.bnb_quantization_config.skip_modules + ): + # 4-bit parameters are packed in uint8 variables + assert module.weight.dtype == torch.uint8 + + def test_fp32_4bit_conversion(self): + r""" + Test whether it is possible to mix both `4bit` and `fp32` weights when using `keep_in_fp32_modules` correctly. + """ + from transformers import AutoConfig, AutoModelForCausalLM + + bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True, keep_in_fp32_modules=["lm_head"]) + + with init_empty_weights(): + model = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name)) + + model.tie_weights() + model = load_and_quantize_model( + model, + bnb_quantization_config, + weights_location=self.weights_location, + device_map="auto", + no_split_module_classes=["BloomBlock"], + ) + assert model.lm_head.weight.dtype == torch.float32 + + @require_multi_device + def test_cpu_gpu_loading_random_device_map(self): + from transformers import AutoConfig, AutoModelForCausalLM + + r""" + A test to check is dispatching a model on cpu & gpu works correctly using a random `device_map`. + """ + device_map = { + "transformer.word_embeddings": "cpu", + "transformer.word_embeddings_layernorm": 0, + "lm_head": "cpu", + "transformer.h.0": 0, + "transformer.h.1": 0, + "transformer.h.2": 0, + "transformer.h.3": 0, + "transformer.h.4": 0, + "transformer.h.5": 0, + "transformer.h.6": 0, + "transformer.h.7": 0, + "transformer.h.8": 0, + "transformer.h.9": 1, + "transformer.h.10": 0, + "transformer.h.11": 1, + "transformer.h.12": 0, + "transformer.h.13": 0, + "transformer.h.14": 1, + "transformer.h.15": 0, + "transformer.h.16": 0, + "transformer.h.17": 1, + "transformer.h.18": 1, + "transformer.h.19": 0, + "transformer.h.20": 1, + "transformer.h.21": 1, + "transformer.h.22": 0, + "transformer.h.23": 0, + "transformer.ln_f": 1, + } + + bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True) + + with init_empty_weights(): + model_4bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name)) + + model_4bit.tie_weights() + model_4bit = load_and_quantize_model( + model_4bit, + bnb_quantization_config, + weights_location=self.weights_location, + device_map=device_map, + no_split_module_classes=["BloomBlock"], + ) + self.check_inference_correctness(model_4bit) + + @require_multi_device + def test_cpu_gpu_loading_custom_device_map(self): + from transformers import AutoConfig, AutoModelForCausalLM + + r""" + A test to check is dispatching a model on cpu & gpu works correctly using a random `device_map`. + """ + device_map = { + "transformer.word_embeddings": "cpu", + "transformer.word_embeddings_layernorm": "cpu", + "lm_head": "cpu", + "transformer.h": 0, + "transformer.ln_f": 1, + } + + bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True) + + with init_empty_weights(): + model_4bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name)) + + model_4bit.tie_weights() + model_4bit = load_and_quantize_model( + model_4bit, + bnb_quantization_config, + weights_location=self.weights_location, + device_map=device_map, + no_split_module_classes=["BloomBlock"], + ) + self.check_inference_correctness(model_4bit) + + @require_multi_device + def test_cpu_gpu_disk_loading_custom_device_map_kwargs(self): + from transformers import AutoConfig, AutoModelForCausalLM + + r""" + A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map`. + This time we also add `disk` on the device_map - using the kwargs directly instead of the quantization config + """ + device_map = { + "transformer.word_embeddings": 0, + "transformer.word_embeddings_layernorm": "disk", + "lm_head": 0, + "transformer.h": 1, + "transformer.ln_f": "cpu", + } + bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True) + + with init_empty_weights(): + model_4bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name)) + + model_4bit.tie_weights() + with tempfile.TemporaryDirectory() as tmpdirname: + model_4bit = load_and_quantize_model( + model_4bit, + bnb_quantization_config, + weights_location=self.weights_location, + device_map=device_map, + no_split_module_classes=["BloomBlock"], + offload_folder=tmpdirname, + offload_state_dict=True, + ) + self.check_inference_correctness(model_4bit) + + +@require_non_torch_xla +@slow +@require_cuda_or_xpu +@require_bnb +@require_huggingface_suite +class Bnb4BitTestLoadedModel(unittest.TestCase): + # We keep the constants inside the init function and model loading inside setUp function + + # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) + # Therefore here we use only bloom-1b3 to test our module + model_name = "marcsun13/bloom-1b7_with_lm_head" + + # Constant values + # This was obtained on a RTX Titan so the number might slightly change + EXPECTED_RELATIVE_DIFFERENCE = 2.109659552692574 + + input_text = "Hello my name is" + EXPECTED_OUTPUTS = set() + EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer. I") + EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of your father.\n") + MAX_NEW_TOKENS = 10 + + def setUp(self): + """ + Setup quantized model from loaded model + """ + from transformers import AutoModelForCausalLM, AutoTokenizer + + super().setUp() + + # Models and tokenizer + self.model_fp16 = AutoModelForCausalLM.from_pretrained( + self.model_name, torch_dtype=torch.float16, device_map="auto" + ) + + self.bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True) + + self.model_4bit = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype=torch.float16) + self.model_4bit = load_and_quantize_model(self.model_4bit, self.bnb_quantization_config) + + self.tokenizer = AutoTokenizer.from_pretrained("bigscience/bloom-1b7") + + def tearDown(self): + """ + TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + super().tearDown() + del self.model_fp16 + del self.model_4bit + + clear_device_cache(garbage_collection=True) + + def test_memory_footprint(self): + r""" + A simple test to check if the model conversion has been done correctly by checking on the + memory footprint of the converted model and the class type of the linear layers of the converted models + """ + from bitsandbytes.nn import Params4bit + + mem_fp16 = self.model_fp16.get_memory_footprint() + mem_4bit = self.model_4bit.get_memory_footprint() + + assert round((mem_fp16 / mem_4bit) - self.EXPECTED_RELATIVE_DIFFERENCE, 7) >= 0 + assert self.model_4bit.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Params4bit + + def test_linear_are_4bit(self): + r""" + A simple test to check if the model conversion has been done correctly by checking on the + memory footprint of the converted model and the class type of the linear layers of the converted models + """ + + self.model_fp16.get_memory_footprint() + self.model_4bit.get_memory_footprint() + + for name, module in self.model_4bit.named_modules(): + if isinstance(module, torch.nn.Linear): + if ( + name + not in self.bnb_quantization_config.keep_in_fp32_modules + + self.bnb_quantization_config.skip_modules + ): + # 4-bit parameters are packed in uint8 variables + assert module.weight.dtype == torch.uint8 + + def test_generate_quality(self): + r""" + Test the generation quality of the quantized model and see that we are matching the expected output. + Given that we are operating on small numbers + the testing model is relatively small, we might not get + the same output across GPUs. So we'll generate few tokens (5-10) and check their output. + """ + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + output_sequences = self.model_4bit.generate( + input_ids=encoded_input["input_ids"].to(self.model_4bit.device), max_new_tokens=10 + ) + + assert self.tokenizer.decode(output_sequences[0], skip_special_tokens=True) in self.EXPECTED_OUTPUTS + + def test_fp32_4bit_conversion(self): + r""" + Test whether it is possible to mix both `4bit` and `fp32` weights when using `keep_in_fp32_modules` correctly. + """ + from transformers import AutoModelForCausalLM + + bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True, keep_in_fp32_modules=["lm_head"]) + + model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype=torch.float16) + model = load_and_quantize_model(model, bnb_quantization_config) + assert model.lm_head.weight.dtype == torch.float32 diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_sagemaker.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_sagemaker.py new file mode 100644 index 0000000000000000000000000000000000000000..5166c0237eef6ad924fd401ca4974dafac224cfe --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_sagemaker.py @@ -0,0 +1,76 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import unittest +from dataclasses import dataclass + +import pytest + +from accelerate.commands.config.config_args import SageMakerConfig +from accelerate.utils import ComputeEnvironment +from accelerate.utils.launch import _convert_nargs_to_dict + + +@dataclass +class MockLaunchConfig(SageMakerConfig): + compute_environment = ComputeEnvironment.AMAZON_SAGEMAKER + fp16 = True + ec2_instance_type = "ml.p3.2xlarge" + iam_role_name = "accelerate_sagemaker_execution_role" + profile = "hf-sm" + region = "us-east-1" + num_machines = 1 + base_job_name = "accelerate-sagemaker-1" + pytorch_version = "1.6" + transformers_version = "4.4" + training_script = "train.py" + success_training_script_args = [ + "--model_name_or_path", + "bert", + "--do_train", + "False", + "--epochs", + "3", + "--learning_rate", + "5e-5", + "--max_steps", + "50.5", + ] + fail_training_script_args = [ + "--model_name_or_path", + "bert", + "--do_train", + "--do_test", + "False", + "--do_predict", + "--epochs", + "3", + "--learning_rate", + "5e-5", + "--max_steps", + "50.5", + ] + + +class SageMakerLaunch(unittest.TestCase): + def test_args_convert(self): + # If no defaults are changed, `to_kwargs` returns an empty dict. + converted_args = _convert_nargs_to_dict(MockLaunchConfig.success_training_script_args) + assert isinstance(converted_args["model_name_or_path"], str) + assert isinstance(converted_args["do_train"], bool) + assert isinstance(converted_args["epochs"], int) + assert isinstance(converted_args["learning_rate"], float) + assert isinstance(converted_args["max_steps"], float) + + with pytest.raises(ValueError): + _convert_nargs_to_dict(MockLaunchConfig.fail_training_script_args) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_samples/MRPC/dev.csv b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_samples/MRPC/dev.csv new file mode 100644 index 0000000000000000000000000000000000000000..96beccda96d7e164e4484e037a52fb338cc22180 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_samples/MRPC/dev.csv @@ -0,0 +1,7 @@ +label,sentence1,sentence2 +equivalent,He said the foodservice pie business doesn 't fit the company 's long-term growth strategy .,""" The foodservice pie business does not fit our long-term growth strategy ." +not_equivalent,Magnarelli said Racicot hated the Iraqi regime and looked forward to using his long years of training in the war .,"His wife said he was "" 100 percent behind George Bush "" and looked forward to using his years of training in the war ." +not_equivalent,"The dollar was at 116.92 yen against the yen , flat on the session , and at 1.2891 against the Swiss franc , also flat .","The dollar was at 116.78 yen JPY = , virtually flat on the session , and at 1.2871 against the Swiss franc CHF = , down 0.1 percent ." +equivalent,The AFL-CIO is waiting until October to decide if it will endorse a candidate .,The AFL-CIO announced Wednesday that it will decide in October whether to endorse a candidate before the primaries . +not_equivalent,No dates have been set for the civil or the criminal trial .,"No dates have been set for the criminal or civil cases , but Shanley has pleaded not guilty ." +equivalent,Wal-Mart said it would check all of its million-plus domestic workers to ensure they were legally employed .,It has also said it would review all of its domestic employees more than 1 million to ensure they have legal status . diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_samples/MRPC/train.csv b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_samples/MRPC/train.csv new file mode 100644 index 0000000000000000000000000000000000000000..96beccda96d7e164e4484e037a52fb338cc22180 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_samples/MRPC/train.csv @@ -0,0 +1,7 @@ +label,sentence1,sentence2 +equivalent,He said the foodservice pie business doesn 't fit the company 's long-term growth strategy .,""" The foodservice pie business does not fit our long-term growth strategy ." +not_equivalent,Magnarelli said Racicot hated the Iraqi regime and looked forward to using his long years of training in the war .,"His wife said he was "" 100 percent behind George Bush "" and looked forward to using his years of training in the war ." +not_equivalent,"The dollar was at 116.92 yen against the yen , flat on the session , and at 1.2891 against the Swiss franc , also flat .","The dollar was at 116.78 yen JPY = , virtually flat on the session , and at 1.2871 against the Swiss franc CHF = , down 0.1 percent ." +equivalent,The AFL-CIO is waiting until October to decide if it will endorse a candidate .,The AFL-CIO announced Wednesday that it will decide in October whether to endorse a candidate before the primaries . +not_equivalent,No dates have been set for the civil or the criminal trial .,"No dates have been set for the criminal or civil cases , but Shanley has pleaded not guilty ." +equivalent,Wal-Mart said it would check all of its million-plus domestic workers to ensure they were legally employed .,It has also said it would review all of its domestic employees more than 1 million to ensure they have legal status . diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_samples/test_command_file.sh b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_samples/test_command_file.sh new file mode 100644 index 0000000000000000000000000000000000000000..592a7d5324e281f0bfc5490e4ae303cae1fe7df1 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_samples/test_command_file.sh @@ -0,0 +1,2 @@ +echo "hello world" +echo "this is a second command" \ No newline at end of file diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_scheduler.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..e55c6561540f180a50caf7e3acb120e6ac9fdb20 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_scheduler.py @@ -0,0 +1,142 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest +from functools import partial + +import torch + +from accelerate import Accelerator, debug_launcher +from accelerate.state import AcceleratorState, GradientState +from accelerate.test_utils import require_cpu, require_huggingface_suite +from accelerate.utils import GradientAccumulationPlugin + + +def one_cycle_test(num_processes=2, step_scheduler_with_optimizer=True, split_batches=False): + accelerator = Accelerator(step_scheduler_with_optimizer=step_scheduler_with_optimizer, split_batches=split_batches) + model = torch.nn.Linear(2, 4) + optimizer = torch.optim.AdamW(model.parameters(), lr=1.0) + scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=0.01, steps_per_epoch=2, epochs=1) + model, optimizer, scheduler = accelerator.prepare(model, optimizer, scheduler) + + # Optimizer has stepped + scheduler.step() + if step_scheduler_with_optimizer or (num_processes == 1): + assert scheduler.scheduler.last_epoch == num_processes, ( + f"Last Epoch ({scheduler.scheduler.last_epoch}) != Num Processes ({num_processes})" + ) + else: + assert scheduler.scheduler.last_epoch != num_processes, ( + f"Last Epoch ({scheduler.scheduler.last_epoch}) == Num Processes ({num_processes})" + ) + + +def lambda_test(num_processes=2, step_scheduler_with_optimizer=True, split_batches=False): + accelerator = Accelerator(step_scheduler_with_optimizer=step_scheduler_with_optimizer, split_batches=split_batches) + model = torch.nn.Linear(2, 4) + optimizer = torch.optim.AdamW(model.parameters(), lr=1.0) + scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda n: 1 - n / 10) + model, optimizer, scheduler = accelerator.prepare(model, optimizer, scheduler) + + # Optimizer has stepped + optimizer._is_overflow = False + scheduler.step() + expected_lr = 1 - (num_processes if (step_scheduler_with_optimizer and not split_batches) else 1) / 10 + assert scheduler.get_last_lr()[0] == expected_lr, ( + f"Wrong lr found at first step, expected {expected_lr}, got {scheduler.get_last_lr()[0]}" + ) + + # Optimizer has not stepped + optimizer._is_overflow = True + scheduler.step() + if not step_scheduler_with_optimizer: + expected_lr = 1 - 2 / 10 + assert scheduler.get_last_lr()[0] == expected_lr, ( + f"Wrong lr found at second step, expected {expected_lr}, got {scheduler.get_last_lr()[0]}" + ) + + +def accumulation_test(num_processes: int = 2): + """ + With this test, an observed batch size of 64 should result in negligible + differences in the scheduler after going through the correct number of steps. + + Uses single, two, and four steps to test. + """ + from transformers import get_linear_schedule_with_warmup + + steps = [1, 2, 4] + for num_steps in steps: + plugin = GradientAccumulationPlugin(num_steps=num_steps, adjust_scheduler=num_steps > 1) + accelerator = Accelerator(gradient_accumulation_plugin=plugin) + model = torch.nn.Linear(2, 4) + optimizer = torch.optim.AdamW(model.parameters(), lr=10.0) + scheduler = get_linear_schedule_with_warmup(optimizer=optimizer, num_warmup_steps=0, num_training_steps=20) + + model, optimizer, scheduler = accelerator.prepare(model, optimizer, scheduler) + + for i in range(10 * num_steps): + with accelerator.accumulate(model): + optimizer.step() + scheduler.step() + + if i == (10 * num_steps - 2): + assert scheduler.get_last_lr()[0] != 0, ( + f"Wrong lr found at second-to-last step, expected non-zero, got {scheduler.get_last_lr()[0]}. num_steps: {num_steps}" + ) + assert scheduler.get_last_lr()[0] == 0, ( + f"Wrong lr found at last step, expected 0, got {scheduler.get_last_lr()[0]}" + ) + GradientState._reset_state() + + +@require_cpu +class SchedulerTester(unittest.TestCase): + def test_lambda_scheduler_steps_with_optimizer_single_process(self): + debug_launcher(partial(lambda_test, num_processes=1), num_processes=1) + debug_launcher(partial(lambda_test, num_processes=1, split_batches=True), num_processes=1) + + def test_one_cycle_scheduler_steps_with_optimizer_single_process(self): + debug_launcher(partial(one_cycle_test, num_processes=1), num_processes=1) + debug_launcher(partial(one_cycle_test, num_processes=1, split_batches=True), num_processes=1) + + def test_lambda_scheduler_not_step_with_optimizer_single_process(self): + debug_launcher(partial(lambda_test, num_processes=1, step_scheduler_with_optimizer=False), num_processes=1) + + def test_one_cycle_scheduler_not_step_with_optimizer_single_process(self): + debug_launcher(partial(one_cycle_test, num_processes=1, step_scheduler_with_optimizer=False), num_processes=1) + + def test_lambda_scheduler_steps_with_optimizer_multiprocess(self): + AcceleratorState._reset_state(True) + debug_launcher(lambda_test) + debug_launcher(partial(lambda_test, num_processes=1, split_batches=True), num_processes=1) + + def test_one_cycle_scheduler_steps_with_optimizer_multiprocess(self): + AcceleratorState._reset_state(True) + debug_launcher(one_cycle_test) + debug_launcher(partial(one_cycle_test, num_processes=1, split_batches=True), num_processes=1) + + def test_lambda_scheduler_not_step_with_optimizer_multiprocess(self): + AcceleratorState._reset_state(True) + debug_launcher(partial(lambda_test, step_scheduler_with_optimizer=False)) + + def test_one_cycle_scheduler_not_step_with_optimizer_multiprocess(self): + AcceleratorState._reset_state(True) + debug_launcher(partial(one_cycle_test, step_scheduler_with_optimizer=False)) + + @require_huggingface_suite + def test_accumulation(self): + AcceleratorState._reset_state(True) + debug_launcher(partial(accumulation_test, num_processes=1)) + debug_launcher(accumulation_test) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_state_checkpointing.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_state_checkpointing.py new file mode 100644 index 0000000000000000000000000000000000000000..bb24c672b8c077f3509e0cf3d6b42003e7ce5234 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_state_checkpointing.py @@ -0,0 +1,444 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import logging +import os +import random +import shutil +import tempfile +import uuid +from contextlib import contextmanager + +import pytest +import torch +from parameterized import parameterized_class +from torch import nn +from torch.utils.data import DataLoader, TensorDataset + +from accelerate import Accelerator +from accelerate.test_utils import ( + DEFAULT_LAUNCH_COMMAND, + execute_subprocess_async, + require_non_cpu, + require_non_torch_xla, + run_first, +) +from accelerate.test_utils.testing import AccelerateTestCase +from accelerate.utils import DistributedType, ProjectConfiguration, patch_environment, set_seed + + +logger = logging.getLogger(__name__) + + +def dummy_dataloaders(a=2, b=3, batch_size=16, n_train_batches: int = 10, n_valid_batches: int = 2): + "Generates a tuple of dummy DataLoaders to test with" + + def get_dataset(n_batches): + x = torch.randn(batch_size * n_batches, 1) + return TensorDataset(x, a * x + b + 0.1 * torch.randn(batch_size * n_batches, 1)) + + train_dataset = get_dataset(n_train_batches) + valid_dataset = get_dataset(n_valid_batches) + train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size, num_workers=4) + valid_dataloader = DataLoader(valid_dataset, shuffle=False, batch_size=batch_size, num_workers=4) + return (train_dataloader, valid_dataloader) + + +def train(num_epochs, model, dataloader, optimizer, accelerator, scheduler=None): + "Trains for `num_epochs`" + rands = [] + for epoch in range(num_epochs): + # Train quickly + model.train() + for batch in dataloader: + x, y = batch + outputs = model(x) + loss = torch.nn.functional.mse_loss(outputs, y) + accelerator.backward(loss) + optimizer.step() + optimizer.zero_grad() + rands.append(random.random()) # Introduce some randomness + if scheduler is not None: + scheduler.step() + return rands + + +class DummyModel(nn.Module): + "Simple model to do y=mx+b" + + def __init__(self): + super().__init__() + self.a = nn.Parameter(torch.randn(1)) + self.b = nn.Parameter(torch.randn(1)) + + def forward(self, x): + return x * self.a + self.b + + +def parameterized_custom_name_func(func, param_num, param): + # customize the test name generator function as we want both params to appear in the sub-test + # name, as by default it shows only the first param + param_based_name = "use_safetensors" if param["use_safetensors"] is True else "use_pytorch" + return f"{func.__name__}_{param_based_name}" + + +@parameterized_class(("use_safetensors",), [[True], [False]], class_name_func=parameterized_custom_name_func) +class CheckpointTest(AccelerateTestCase): + def check_adam_state(self, state1, state2, distributed_type): + # For DistributedType.XLA, the `accelerator.save_state` function calls `xm._maybe_convert_to_cpu` before saving. + # As a result, all tuple values are converted to lists. Therefore, we need to convert them back here. + # Remove this code once Torch XLA fixes this issue. + if distributed_type == DistributedType.XLA: + state1["param_groups"][0]["betas"] = tuple(state1["param_groups"][0]["betas"]) + state2["param_groups"][0]["betas"] = tuple(state2["param_groups"][0]["betas"]) + assert state1 == state2 + + def test_with_save_limit(self): + with tempfile.TemporaryDirectory() as tmpdir: + set_seed(42) + model = DummyModel() + optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3) + train_dataloader, valid_dataloader = dummy_dataloaders() + project_config = ProjectConfiguration(total_limit=1, project_dir=tmpdir, automatic_checkpoint_naming=True) + # Train baseline + accelerator = Accelerator(project_config=project_config) + model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare( + model, optimizer, train_dataloader, valid_dataloader + ) + # Save initial + accelerator.save_state(safe_serialization=self.use_safetensors) + + # Save second state + accelerator.save_state(safe_serialization=self.use_safetensors) + assert len(os.listdir(accelerator.project_dir)) == 1 + + def test_can_resume_training_with_folder(self): + with tempfile.TemporaryDirectory() as tmpdir: + set_seed(42) + model = DummyModel() + optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3) + train_dataloader, valid_dataloader = dummy_dataloaders() + # Train baseline + accelerator = Accelerator() + model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare( + model, optimizer, train_dataloader, valid_dataloader + ) + # Save initial + initial = os.path.join(tmpdir, "initial") + accelerator.save_state(initial, safe_serialization=self.use_safetensors) + (a, b) = model.a.item(), model.b.item() + opt_state = optimizer.state_dict() + ground_truth_rands = train(3, model, train_dataloader, optimizer, accelerator) + (a1, b1) = model.a.item(), model.b.item() + opt_state1 = optimizer.state_dict() + + # Train partially + set_seed(42) + model = DummyModel() + optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3) + train_dataloader, valid_dataloader = dummy_dataloaders() + accelerator = Accelerator() + model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare( + model, optimizer, train_dataloader, valid_dataloader + ) + accelerator.load_state(initial) + (a2, b2) = model.a.item(), model.b.item() + opt_state2 = optimizer.state_dict() + self.assertEqual(a, a2) + self.assertEqual(b, b2) + assert a == a2 + assert b == b2 + self.check_adam_state(opt_state, opt_state2, accelerator.distributed_type) + + test_rands = train(2, model, train_dataloader, optimizer, accelerator) + # Save everything + checkpoint = os.path.join(tmpdir, "checkpoint") + accelerator.save_state(checkpoint, safe_serialization=self.use_safetensors) + + # Load everything back in and make sure all states work + accelerator.load_state(checkpoint) + test_rands += train(1, model, train_dataloader, optimizer, accelerator) + (a3, b3) = model.a.item(), model.b.item() + opt_state3 = optimizer.state_dict() + assert a1 == a3 + assert b1 == b3 + self.check_adam_state(opt_state1, opt_state3, accelerator.distributed_type) + assert ground_truth_rands == test_rands + + def test_can_resume_training(self): + with tempfile.TemporaryDirectory() as tmpdir: + set_seed(42) + model = DummyModel() + optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3) + train_dataloader, valid_dataloader = dummy_dataloaders() + project_config = ProjectConfiguration(automatic_checkpoint_naming=True) + + # Train baseline + accelerator = Accelerator(project_dir=tmpdir, project_config=project_config) + model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare( + model, optimizer, train_dataloader, valid_dataloader + ) + # Save initial + accelerator.save_state(safe_serialization=self.use_safetensors) + (a, b) = model.a.item(), model.b.item() + opt_state = optimizer.state_dict() + ground_truth_rands = train(3, model, train_dataloader, optimizer, accelerator) + (a1, b1) = model.a.item(), model.b.item() + opt_state1 = optimizer.state_dict() + + # Train partially + set_seed(42) + model = DummyModel() + optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3) + train_dataloader, valid_dataloader = dummy_dataloaders() + project_config = ProjectConfiguration(iteration=1, automatic_checkpoint_naming=True) + accelerator = Accelerator(project_dir=tmpdir, project_config=project_config) + model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare( + model, optimizer, train_dataloader, valid_dataloader + ) + accelerator.load_state(os.path.join(tmpdir, "checkpoints", "checkpoint_0")) + (a2, b2) = model.a.item(), model.b.item() + opt_state2 = optimizer.state_dict() + assert a == a2 + assert b == b2 + self.check_adam_state(opt_state, opt_state2, accelerator.distributed_type) + + test_rands = train(2, model, train_dataloader, optimizer, accelerator) + # Save everything + accelerator.save_state(safe_serialization=self.use_safetensors) + + # Load everything back in and make sure all states work + accelerator.load_state(os.path.join(tmpdir, "checkpoints", "checkpoint_1")) + test_rands += train(1, model, train_dataloader, optimizer, accelerator) + (a3, b3) = model.a.item(), model.b.item() + opt_state3 = optimizer.state_dict() + assert a1 == a3 + assert b1 == b3 + self.check_adam_state(opt_state1, opt_state3, accelerator.distributed_type) + assert ground_truth_rands == test_rands + + def test_can_resume_training_checkpoints_relative_path(self): + # See #1983 + # This test is like test_can_resume_training but uses a relative path for the checkpoint and automatically + # infers the checkpoint path when loading. + @contextmanager + def temporary_relative_directory(): + # This is equivalent to tempfile.TemporaryDirectory() except that it returns a relative path + rand_dir = f"test_path_{uuid.uuid4()}" + os.mkdir(rand_dir) + try: + yield rand_dir + finally: + shutil.rmtree(rand_dir) + + with temporary_relative_directory() as tmpdir: + set_seed(42) + model = DummyModel() + optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3) + train_dataloader, valid_dataloader = dummy_dataloaders() + project_config = ProjectConfiguration(automatic_checkpoint_naming=True) + + # Train baseline + accelerator = Accelerator(project_dir=tmpdir, project_config=project_config) + model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare( + model, optimizer, train_dataloader, valid_dataloader + ) + # Save initial + accelerator.save_state(safe_serialization=self.use_safetensors) + (a, b) = model.a.item(), model.b.item() + opt_state = optimizer.state_dict() + ground_truth_rands = train(3, model, train_dataloader, optimizer, accelerator) + (a1, b1) = model.a.item(), model.b.item() + opt_state1 = optimizer.state_dict() + + # Train partially + set_seed(42) + model = DummyModel() + optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3) + train_dataloader, valid_dataloader = dummy_dataloaders() + project_config = ProjectConfiguration(iteration=1, automatic_checkpoint_naming=True) + accelerator = Accelerator(project_dir=tmpdir, project_config=project_config) + model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare( + model, optimizer, train_dataloader, valid_dataloader + ) + accelerator.load_state() # <= infer the directory automatically + (a2, b2) = model.a.item(), model.b.item() + opt_state2 = optimizer.state_dict() + assert a == a2 + assert b == b2 + self.check_adam_state(opt_state, opt_state2, accelerator.distributed_type) + assert opt_state == opt_state2 + + test_rands = train(2, model, train_dataloader, optimizer, accelerator) + # Save everything + accelerator.save_state(safe_serialization=self.use_safetensors) + + # Load everything back in and make sure all states work + accelerator.load_state(os.path.join(tmpdir, "checkpoints", "checkpoint_1")) + test_rands += train(1, model, train_dataloader, optimizer, accelerator) + (a3, b3) = model.a.item(), model.b.item() + opt_state3 = optimizer.state_dict() + assert a1 == a3 + assert b1 == b3 + self.check_adam_state(opt_state1, opt_state3, accelerator.distributed_type) + assert ground_truth_rands == test_rands + + def test_invalid_registration(self): + t = torch.tensor([1, 2, 3]) + t1 = torch.tensor([2, 3, 4]) + net = DummyModel() + opt = torch.optim.Adam(net.parameters()) + accelerator = Accelerator() + with self.assertRaises(ValueError) as ve: + accelerator.register_for_checkpointing(t, t1, net, opt) + message = str(ve.exception) + assert "Item at index 0" in message + assert "Item at index 1" in message + assert "Item at index 2" not in message + assert "Item at index 3" not in message + + def test_with_scheduler(self): + with tempfile.TemporaryDirectory() as tmpdir: + set_seed(42) + model = DummyModel() + optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3) + scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99) + train_dataloader, valid_dataloader = dummy_dataloaders() + project_config = ProjectConfiguration(automatic_checkpoint_naming=True) + # Train baseline + accelerator = Accelerator(project_dir=tmpdir, project_config=project_config) + model, optimizer, train_dataloader, valid_dataloader, scheduler = accelerator.prepare( + model, optimizer, train_dataloader, valid_dataloader, scheduler + ) + # Save initial + accelerator.save_state(safe_serialization=self.use_safetensors) + scheduler_state = scheduler.state_dict() + train(3, model, train_dataloader, optimizer, accelerator, scheduler) + assert scheduler_state != scheduler.state_dict() + + # Load everything back in and make sure all states work + accelerator.load_state(os.path.join(tmpdir, "checkpoints", "checkpoint_0")) + assert scheduler_state == scheduler.state_dict() + + def test_automatic_loading(self): + with tempfile.TemporaryDirectory() as tmpdir: + set_seed(42) + model = DummyModel() + optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3) + scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99) + train_dataloader, valid_dataloader = dummy_dataloaders() + project_config = ProjectConfiguration(automatic_checkpoint_naming=True) + # Train baseline + accelerator = Accelerator(project_dir=tmpdir, project_config=project_config) + model, optimizer, train_dataloader, valid_dataloader, scheduler = accelerator.prepare( + model, optimizer, train_dataloader, valid_dataloader, scheduler + ) + # Save initial + accelerator.save_state(safe_serialization=self.use_safetensors) + train(2, model, train_dataloader, optimizer, accelerator, scheduler) + (a2, b2) = model.a.item(), model.b.item() + # Save a first time + accelerator.save_state(safe_serialization=self.use_safetensors) + train(1, model, train_dataloader, optimizer, accelerator, scheduler) + (a3, b3) = model.a.item(), model.b.item() + + # Load back in the last saved checkpoint, should point to a2, b2 + accelerator.load_state() + assert a3 != model.a.item() + assert b3 != model.b.item() + assert a2 == model.a.item() + assert b2 == model.b.item() + + def test_checkpoint_deletion(self): + with tempfile.TemporaryDirectory() as tmpdir: + set_seed(42) + model = DummyModel() + project_config = ProjectConfiguration(automatic_checkpoint_naming=True, total_limit=2) + # Train baseline + accelerator = Accelerator(project_dir=tmpdir, project_config=project_config) + model = accelerator.prepare(model) + # Save 3 states: + for _ in range(11): + accelerator.save_state(safe_serialization=self.use_safetensors) + assert not os.path.exists(os.path.join(tmpdir, "checkpoints", "checkpoint_0")) + assert os.path.exists(os.path.join(tmpdir, "checkpoints", "checkpoint_9")) + assert os.path.exists(os.path.join(tmpdir, "checkpoints", "checkpoint_10")) + + @run_first + @require_non_cpu + @require_non_torch_xla + def test_map_location(self): + cmd = DEFAULT_LAUNCH_COMMAND + [inspect.getfile(self.__class__)] + + env_kwargs = dict(use_safe_tensors=str(self.use_safetensors), omp_num_threads="1") + with patch_environment(**env_kwargs): + execute_subprocess_async(cmd) + + +if __name__ == "__main__": + use_safetensors = os.environ.get("USE_SAFETENSORS", "False") == "True" + savedir = "/tmp/accelerate/state_checkpointing" + model = DummyModel() + optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3) + scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99) + train_dataloader, valid_dataloader = dummy_dataloaders() + project_config = ProjectConfiguration(automatic_checkpoint_naming=True) + # Train baseline + accelerator = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision="no") + if accelerator.process_index == 0: + if os.path.exists(savedir): + shutil.rmtree(savedir) + os.makedirs(savedir) + model, optimizer, train_dataloader, valid_dataloader, scheduler = accelerator.prepare( + model, optimizer, train_dataloader, valid_dataloader, scheduler + ) + model, optimizer = accelerator.prepare(model, optimizer) + train(3, model, train_dataloader, optimizer, accelerator, scheduler) + # Check that the initial optimizer is loaded on the GPU + for group in optimizer.param_groups: + param_device = group["params"][0].device + break + assert param_device.type == accelerator.device.type + model = model.cpu() + accelerator.wait_for_everyone() + accelerator.save_state(safe_serialization=use_safetensors) + accelerator.wait_for_everyone() + + # Check CPU state + accelerator.load_state(os.path.join(savedir, "checkpoints", "checkpoint_0"), map_location="cpu") + for group in optimizer.param_groups: + param_device = group["params"][0].device + break + assert param_device.type == torch.device("cpu").type, ( + f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}" + ) + + # Check device state + model.to(accelerator.device) + accelerator.load_state(os.path.join(savedir, "checkpoints", "checkpoint_0"), map_location="on_device") + for group in optimizer.param_groups: + param_device = group["params"][0].device + break + assert param_device.type == accelerator.device.type, ( + f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}" + ) + + # Check error + with pytest.raises(TypeError, match="Unsupported optimizer map location passed"): + accelerator.load_state(os.path.join(savedir, "checkpoints", "checkpoint_0"), map_location="invalid") + accelerator.wait_for_everyone() + if accelerator.process_index == 0: + shutil.rmtree(savedir) + accelerator.wait_for_everyone() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_tpu.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_tpu.py new file mode 100644 index 0000000000000000000000000000000000000000..e5a3c406a3aaf9a6065bff25007b2deeddd9214f --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_tpu.py @@ -0,0 +1,34 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import sys +import unittest + +from accelerate.test_utils import execute_subprocess_async, path_in_accelerate_package, require_tpu + + +class MultiTPUTester(unittest.TestCase): + test_file_path = path_in_accelerate_package("test_utils", "scripts", "test_script.py") + test_dir = os.path.dirname(__file__) + + @require_tpu + def test_tpu(self): + distributed_args = f""" + {self.test_dir}/xla_spawn.py + --num_cores 8 + {self.test_file_path} + """.split() + cmd = [sys.executable] + distributed_args + execute_subprocess_async(cmd) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_tracking.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..d4affcbd16e25ba2abff214f5e9c77b7106525e6 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_tracking.py @@ -0,0 +1,870 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import csv +import json +import logging +import os +import random +import re +import subprocess +import tempfile +import unittest +import zipfile +from pathlib import Path +from typing import Optional +from unittest import mock + +import numpy as np +import torch +from packaging import version + +# We use TF to parse the logs +from accelerate import Accelerator +from accelerate.state import PartialState +from accelerate.test_utils.testing import ( + MockingTestCase, + TempDirTestCase, + require_aim, + require_clearml, + require_comet_ml, + require_dvclive, + require_matplotlib, + require_mlflow, + require_pandas, + require_swanlab, + require_tensorboard, + require_trackio, + require_wandb, + skip, +) +from accelerate.tracking import ( + AimTracker, + ClearMLTracker, + CometMLTracker, + DVCLiveTracker, + GeneralTracker, + MLflowTracker, + SwanLabTracker, + TensorBoardTracker, + TrackioTracker, + WandBTracker, +) +from accelerate.utils import ( + ProjectConfiguration, + is_comet_ml_available, + is_dvclive_available, + is_tensorboard_available, +) + + +if is_comet_ml_available(): + from comet_ml import ExperimentConfig + +if is_tensorboard_available(): + import struct + + import tensorboard.compat.proto.event_pb2 as event_pb2 + +if is_dvclive_available(): + from dvclive.plots.metric import Metric + from dvclive.serialize import load_yaml + from dvclive.utils import parse_metrics + +logger = logging.getLogger(__name__) + + +@require_tensorboard +class TensorBoardTrackingTest(unittest.TestCase): + @unittest.skipIf(version.parse(np.__version__) >= version.parse("2.0"), "TB doesn't support numpy 2.0") + def test_init_trackers(self): + project_name = "test_project_with_config" + with tempfile.TemporaryDirectory() as dirpath: + accelerator = Accelerator(log_with="tensorboard", project_dir=dirpath) + config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"} + accelerator.init_trackers(project_name, config) + accelerator.end_training() + for child in Path(f"{dirpath}/{project_name}").glob("*/**"): + log = list(filter(lambda x: x.is_file(), child.iterdir()))[0] + assert str(log) != "" + + def test_log(self): + project_name = "test_project_with_log" + with tempfile.TemporaryDirectory() as dirpath: + accelerator = Accelerator(log_with="tensorboard", project_dir=dirpath) + accelerator.init_trackers(project_name) + values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"} + accelerator.log(values, step=0) + accelerator.end_training() + # Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord + # Names are randomly generated each time + log = list(filter(lambda x: x.is_file(), Path(f"{dirpath}/{project_name}").iterdir()))[0] + assert str(log) != "" + + def test_log_with_tensor(self): + project_name = "test_project_with_log" + with tempfile.TemporaryDirectory() as dirpath: + accelerator = Accelerator(log_with="tensorboard", project_dir=dirpath) + accelerator.init_trackers(project_name) + values = {"tensor": torch.tensor(1)} + accelerator.log(values, step=0) + accelerator.end_training() + # Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord + # Names are randomly generated each time + log = list(filter(lambda x: x.is_file(), Path(f"{dirpath}/{project_name}").iterdir()))[0] + # Reading implementation based on https://github.com/pytorch/pytorch/issues/45327#issuecomment-703757685 + with open(log, "rb") as f: + data = f.read() + found_tensor = False + while data: + header = struct.unpack("Q", data[:8]) + + event_str = data[12 : 12 + int(header[0])] # 8+4 + data = data[12 + int(header[0]) + 4 :] + event = event_pb2.Event() + + event.ParseFromString(event_str) + if event.HasField("summary"): + for value in event.summary.value: + if value.simple_value == 1.0 and value.tag == "tensor": + found_tensor = True + assert found_tensor, "Converted tensor was not found in the log file!" + + def test_project_dir(self): + with self.assertRaisesRegex(ValueError, "Logging with `tensorboard` requires a `logging_dir`"): + _ = Accelerator(log_with="tensorboard") + with tempfile.TemporaryDirectory() as dirpath: + _ = Accelerator(log_with="tensorboard", project_dir=dirpath) + + def test_project_dir_with_config(self): + config = ProjectConfiguration(total_limit=30) + with tempfile.TemporaryDirectory() as dirpath: + _ = Accelerator(log_with="tensorboard", project_dir=dirpath, project_config=config) + + +@require_wandb +@mock.patch.dict(os.environ, {"WANDB_MODE": "offline"}) +class WandBTrackingTest(TempDirTestCase, MockingTestCase): + def setUp(self): + super().setUp() + # wandb let's us override where logs are stored to via the WANDB_DIR env var + self.add_mocks(mock.patch.dict(os.environ, {"WANDB_DIR": self.tmpdir})) + + @staticmethod + def parse_log(log: str, section: str, record: bool = True): + """ + Parses wandb log for `section` and returns a dictionary of + all items in that section. Section names are based on the + output of `wandb sync --view --verbose` and items starting + with "Record" in that result + """ + # Big thanks to the W&B team for helping us parse their logs + pattern = rf"{section} ([\S\s]*?)\n\n" + if record: + pattern = rf"Record: {pattern}" + cleaned_record = re.findall(pattern, log)[0] + # A config + if section == "config" or section == "history": + cleaned_record = re.findall(r'"([a-zA-Z0-9_.,]+)', cleaned_record) + return {key: val for key, val in zip(cleaned_record[0::2], cleaned_record[1::2])} + # Everything else + else: + return dict(re.findall(r'(\w+): "([^\s]+)"', cleaned_record)) + + @skip + def test_wandb(self): + project_name = "test_project_with_config" + accelerator = Accelerator(log_with="wandb") + config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"} + kwargs = {"wandb": {"tags": ["my_tag"]}} + accelerator.init_trackers(project_name, config, kwargs) + values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"} + accelerator.log(values, step=0) + accelerator.end_training() + # The latest offline log is stored at wandb/latest-run/*.wandb + for child in Path(f"{self.tmpdir}/wandb/latest-run").glob("*"): + if child.is_file() and child.suffix == ".wandb": + cmd = ["wandb", "sync", "--view", "--verbose", str(child)] + content = subprocess.check_output(cmd, encoding="utf8", errors="ignore") + break + + # Check HPS through careful parsing and cleaning + logged_items = self.parse_log(content, "config") + assert logged_items["num_iterations"] == "12" + assert logged_items["learning_rate"] == "0.01" + assert logged_items["some_boolean"] == "false" + assert logged_items["some_string"] == "some_value" + assert logged_items["some_string"] == "some_value" + + # Run tags + logged_items = self.parse_log(content, "run", False) + assert logged_items["tags"] == "my_tag" + + # Actual logging + logged_items = self.parse_log(content, "history") + assert logged_items["total_loss"] == "0.1" + assert logged_items["iteration"] == "1" + assert logged_items["my_text"] == "some_value" + assert logged_items["_step"] == "0" + + +@require_mlflow +class MLflowTrackingTest(unittest.TestCase): + def setUp(self): + import mlflow + + self.tmpdir = tempfile.TemporaryDirectory() + mlflow.set_tracking_uri("file://" + self.tmpdir.name) + + @require_matplotlib + def create_mock_figure(self): + """Create a mock figure for testing.""" + import matplotlib.pyplot as plt + + fig = plt.figure(figsize=(6, 4)) + return fig + + def test_log(self): + import mlflow + + """Test that log calls mlflow.log_metrics with only numeric values and the correct step.""" + values = {"accuracy": 0.95, "loss": 0.1, "non_numeric": "ignored"} + tracker = MLflowTracker(experiment_name="test_exp", logging_dir=self.tmpdir.name) + accelerator = Accelerator(log_with=tracker) + accelerator.init_trackers(project_name="test_exp") + tracker.log(values, step=10) + + run_id = tracker.active_run.info.run_id + accelerator.end_training() + + # Retrieve the run and check the logged metrics. + run = mlflow.get_run(run_id) + metrics = run.data.metrics + self.assertEqual(metrics.get("accuracy"), 0.95) + self.assertEqual(metrics.get("loss"), 0.1) + self.assertNotIn("non_numeric", metrics) + + @require_matplotlib + def test_log_figure(self): + import mlflow + + """Test that log_figure calls mlflow.log_figure with the correct arguments.""" + dummy_figure = self.create_mock_figure() + tracker = MLflowTracker(experiment_name="test_exp", logging_dir=self.tmpdir.name) + accelerator = Accelerator(log_with=tracker) + accelerator.init_trackers(project_name="test_exp") + tracker.log_figure(dummy_figure, artifact_file="dummy_figure.png") + + run_id = tracker.active_run.info.run_id + accelerator.end_training() + + self.assertIn( + "dummy_figure.png", + [artifact.path for artifact in mlflow.artifacts.list_artifacts(run_id=run_id)], + ) + + def test_log_artifact(self): + import mlflow + + """Test that log_artifact calls mlflow.log_artifact with the correct file path.""" + dummy_file_path = os.path.join(self.tmpdir.name, "dummy.txt") + with open(dummy_file_path, "w") as f: + f.write("dummy content") + tracker = MLflowTracker(experiment_name="test_exp", logging_dir=self.tmpdir.name) + accelerator = Accelerator(log_with=tracker) + accelerator.init_trackers(project_name="test_exp") + tracker.log_artifact(dummy_file_path, artifact_path="artifact_dir") + + run_id = tracker.active_run.info.run_id + accelerator.end_training() + + self.assertIn( + "artifact_dir/dummy.txt", + [ + artifact.path + for artifact in mlflow.artifacts.list_artifacts(run_id=run_id, artifact_path="artifact_dir") + ], + ) + + def test_log_artifacts(self): + import mlflow + + """Test that log_artifacts calls mlflow.log_artifacts with the correct directory.""" + dummy_dir = os.path.join(self.tmpdir.name, "dummy_dir") + os.mkdir(dummy_dir) + dummy_file_path = os.path.join(dummy_dir, "dummy.txt") + with open(dummy_file_path, "w") as f: + f.write("dummy content") + tracker = MLflowTracker(experiment_name="test_exp", logging_dir=self.tmpdir.name) + accelerator = Accelerator(log_with=tracker) + accelerator.init_trackers(project_name="test_exp") + tracker.log_artifacts(dummy_dir, artifact_path="artifact_dir") + + run_id = tracker.active_run.info.run_id + accelerator.end_training() + + self.assertIn( + "artifact_dir/dummy.txt", + [ + artifact.path + for artifact in mlflow.artifacts.list_artifacts(run_id=run_id, artifact_path="artifact_dir") + ], + ) + + +@require_comet_ml +class CometMLTest(unittest.TestCase): + @staticmethod + def get_value_from_key(log_list, key: str, is_param: bool = False): + "Extracts `key` from Comet `log`" + for log in log_list: + j = json.loads(log)["payload"] + if is_param and "param" in j.keys(): + if j["param"]["paramName"] == key: + return j["param"]["paramValue"] + if "log_other" in j.keys(): + if j["log_other"]["key"] == key: + return j["log_other"]["val"] + if "metric" in j.keys(): + if j["metric"]["metricName"] == key: + return j["metric"]["metricValue"] + if j.get("key", None) == key: + return j["value"] + + def test_init_trackers(self): + with tempfile.TemporaryDirectory() as d: + tracker = CometMLTracker( + "test_project_with_config", online=False, experiment_config=ExperimentConfig(offline_directory=d) + ) + accelerator = Accelerator(log_with=tracker) + config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"} + accelerator.init_trackers(None, config) + accelerator.end_training() + log = os.listdir(d)[0] # Comet is nice, it's just a zip file here + # We parse the raw logs + p = os.path.join(d, log) + archive = zipfile.ZipFile(p, "r") + log = archive.open("messages.json").read().decode("utf-8") + list_of_json = log.split("\n")[:-1] + assert self.get_value_from_key(list_of_json, "num_iterations", True) == 12 + assert self.get_value_from_key(list_of_json, "learning_rate", True) == 0.01 + assert self.get_value_from_key(list_of_json, "some_boolean", True) is False + assert self.get_value_from_key(list_of_json, "some_string", True) == "some_value" + + def test_log(self): + with tempfile.TemporaryDirectory() as d: + tracker = CometMLTracker( + "test_project_with_config", online=False, experiment_config=ExperimentConfig(offline_directory=d) + ) + accelerator = Accelerator(log_with=tracker) + accelerator.init_trackers(None) + values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"} + accelerator.log(values, step=0) + accelerator.end_training() + log = os.listdir(d)[0] # Comet is nice, it's just a zip file here + # We parse the raw logs + p = os.path.join(d, log) + archive = zipfile.ZipFile(p, "r") + log = archive.open("messages.json").read().decode("utf-8") + list_of_json = log.split("\n")[:-1] + assert self.get_value_from_key(list_of_json, "curr_step", True) == 0 + assert self.get_value_from_key(list_of_json, "total_loss") == 0.1 + assert self.get_value_from_key(list_of_json, "iteration") == 1 + assert self.get_value_from_key(list_of_json, "my_text") == "some_value" + + +@require_clearml +class ClearMLTest(TempDirTestCase, MockingTestCase): + def setUp(self): + super().setUp() + # ClearML offline session location is stored in CLEARML_CACHE_DIR + self.add_mocks(mock.patch.dict(os.environ, {"CLEARML_CACHE_DIR": str(self.tmpdir)})) + + @staticmethod + def _get_offline_dir(accelerator): + from clearml.config import get_offline_dir + + return get_offline_dir(task_id=accelerator.get_tracker("clearml", unwrap=True).id) + + @staticmethod + def _get_metrics(offline_dir): + metrics = [] + with open(os.path.join(offline_dir, "metrics.jsonl")) as f: + json_lines = f.readlines() + for json_line in json_lines: + metrics.extend(json.loads(json_line)) + return metrics + + def test_init_trackers(self): + from clearml import Task + from clearml.utilities.config import text_to_config_dict + + Task.set_offline(True) + accelerator = Accelerator(log_with="clearml") + config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"} + accelerator.init_trackers("test_project_with_config", config) + + offline_dir = ClearMLTest._get_offline_dir(accelerator) + accelerator.end_training() + + with open(os.path.join(offline_dir, "task.json")) as f: + offline_session = json.load(f) + clearml_offline_config = text_to_config_dict(offline_session["configuration"]["General"]["value"]) + assert config == clearml_offline_config + + def test_log(self): + from clearml import Task + + Task.set_offline(True) + accelerator = Accelerator(log_with="clearml") + accelerator.init_trackers("test_project_with_log") + values_with_iteration = {"should_be_under_train": 1, "eval_value": 2, "test_value": 3.1, "train_value": 4.1} + accelerator.log(values_with_iteration, step=1) + single_values = {"single_value_1": 1.1, "single_value_2": 2.2} + accelerator.log(single_values) + + offline_dir = ClearMLTest._get_offline_dir(accelerator) + accelerator.end_training() + + metrics = ClearMLTest._get_metrics(offline_dir) + assert (len(values_with_iteration) + len(single_values)) == len(metrics) + for metric in metrics: + if metric["metric"] == "Summary": + assert metric["variant"] in single_values + assert metric["value"] == single_values[metric["variant"]] + elif metric["metric"] == "should_be_under_train": + assert metric["variant"] == "train" + assert metric["iter"] == 1 + assert metric["value"] == values_with_iteration["should_be_under_train"] + else: + values_with_iteration_key = metric["variant"] + "_" + metric["metric"] + assert values_with_iteration_key in values_with_iteration + assert metric["iter"] == 1 + assert metric["value"] == values_with_iteration[values_with_iteration_key] + + def test_log_images(self): + from clearml import Task + + Task.set_offline(True) + accelerator = Accelerator(log_with="clearml") + accelerator.init_trackers("test_project_with_log_images") + + base_image = np.eye(256, 256, dtype=np.uint8) * 255 + base_image_3d = np.concatenate((np.atleast_3d(base_image), np.zeros((256, 256, 2), dtype=np.uint8)), axis=2) + images = { + "base_image": base_image, + "base_image_3d": base_image_3d, + } + accelerator.get_tracker("clearml").log_images(images, step=1) + + offline_dir = ClearMLTest._get_offline_dir(accelerator) + accelerator.end_training() + + images_saved = Path(os.path.join(offline_dir, "data")).rglob("*.jpeg") + assert len(list(images_saved)) == len(images) + + def test_log_table(self): + from clearml import Task + + Task.set_offline(True) + accelerator = Accelerator(log_with="clearml") + accelerator.init_trackers("test_project_with_log_table") + + accelerator.get_tracker("clearml").log_table( + "from lists with columns", columns=["A", "B", "C"], data=[[1, 3, 5], [2, 4, 6]] + ) + accelerator.get_tracker("clearml").log_table("from lists", data=[["A2", "B2", "C2"], [7, 9, 11], [8, 10, 12]]) + offline_dir = ClearMLTest._get_offline_dir(accelerator) + accelerator.end_training() + + metrics = ClearMLTest._get_metrics(offline_dir) + assert len(metrics) == 2 + for metric in metrics: + assert metric["metric"] in ("from lists", "from lists with columns") + plot = json.loads(metric["plot_str"]) + if metric["metric"] == "from lists with columns": + print(plot["data"][0]) + self.assertCountEqual(plot["data"][0]["header"]["values"], ["A", "B", "C"]) + self.assertCountEqual(plot["data"][0]["cells"]["values"], [[1, 2], [3, 4], [5, 6]]) + else: + self.assertCountEqual(plot["data"][0]["header"]["values"], ["A2", "B2", "C2"]) + self.assertCountEqual(plot["data"][0]["cells"]["values"], [[7, 8], [9, 10], [11, 12]]) + + @require_pandas + def test_log_table_pandas(self): + import pandas as pd + from clearml import Task + + Task.set_offline(True) + accelerator = Accelerator(log_with="clearml") + accelerator.init_trackers("test_project_with_log_table_pandas") + + accelerator.get_tracker("clearml").log_table( + "from df", dataframe=pd.DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]}), step=1 + ) + + offline_dir = ClearMLTest._get_offline_dir(accelerator) + accelerator.end_training() + + metrics = ClearMLTest._get_metrics(offline_dir) + assert len(metrics) == 1 + assert metrics[0]["metric"] == "from df" + plot = json.loads(metrics[0]["plot_str"]) + self.assertCountEqual(plot["data"][0]["header"]["values"], [["A"], ["B"], ["C"]]) + self.assertCountEqual(plot["data"][0]["cells"]["values"], [[1, 2], [3, 4], [5, 6]]) + + +@require_swanlab +@mock.patch.dict(os.environ, {"SWANLAB_MODE": "offline"}) +class SwanLabTrackingTest(TempDirTestCase, MockingTestCase): + def setUp(self): + super().setUp() + # Setting Path where SwanLab parsed log files are saved via the SWANLAB_LOG_DIR env var + self.add_mocks(mock.patch.dict(os.environ, {"SWANLAB_LOG_DIR": self.tmpdir})) + + @skip + def test_swanlab(self): + # Disable hardware monitoring to prevent errors in test mode. + import swanlab + from swanlab.log.backup import BackupHandler + from swanlab.log.backup.datastore import DataStore + from swanlab.log.backup.models import ModelsParser + + swanlab.merge_settings(swanlab.Settings(hardware_monitor=False)) + # Start a fake training session. + accelerator = Accelerator(log_with="swanlab") + project_name = "test_project_with_config" + experiment_name = "test" + description = "test project for swanlab" + tags = ["my_tag"] + config = { + "epochs": 10, + "learning_rate": 0.01, + "offset": 0.1, + } + kwargs = { + "swanlab": { + "experiment_name": experiment_name, + "description": description, + "tags": tags, + } + } + accelerator.init_trackers(project_name, config, kwargs) + record_metrics = [] + record_scalars = [] + record_images_count = 0 + record_logs = [] + for epoch in range(1, swanlab.config.epochs): + acc = 1 - 2**-epoch - random.random() / epoch - 0.1 + loss = 2**-epoch + random.random() / epoch + 0.1 + ll = swanlab.log( + { + "accuracy": acc, + "loss": loss, + "image": swanlab.Image(np.random.random((3, 3, 3))), + }, + step=epoch, + ) + log = f"epoch={epoch}, accuracy={acc}, loss={loss}" + print(log) + record_scalars.extend([acc, loss]) + record_images_count += 1 + record_logs.append(log) + record_metrics.extend([x for _, x in ll.items()]) + accelerator.end_training() + + # Load latest offline log + run_dir = swanlab.get_run().public.run_dir + assert os.path.exists(run_dir) is True + ds = DataStore() + ds.open_for_scan(os.path.join(run_dir.__str__(), BackupHandler.BACKUP_FILE).__str__()) + with ModelsParser() as models_parser: + for record in ds: + if record is None: + continue + models_parser.parse_record(record) + header, project, experiment, logs, runtime, columns, scalars, medias, footer = models_parser.get_parsed() + + # test file header + assert header.backup_type == "DEFAULT" + + # test project info + assert project.name == project_name + assert project.workspace is None + assert project.public is None + + # test experiment info + assert experiment.name is not None + assert experiment.description == description + assert experiment.tags == tags + + # test log record + backup_logs = [log.message for log in logs] + for record_log in record_logs: + assert record_log in backup_logs, "Log not found in backup logs: " + record_log + + # test runtime info + runtime_info = runtime.to_file_model(os.path.join(run_dir.__str__(), "files")) + assert runtime_info.conda is None, "Not using conda, should be None" + assert isinstance(runtime_info.requirements, str), "Requirements should be a string" + assert isinstance(runtime_info.metadata, dict), "Metadata should be a dictionary" + assert isinstance(runtime_info.config, dict), "Config should be a dictionary" + for key in runtime_info.config: + assert key in config, f"Config key {key} not found in original config" + assert runtime_info.config[key]["value"] == config[key], ( + f"Config value for {key} does not match original value" + ) + + # test scalar + assert len(scalars) + len(medias) == len(record_metrics), "Total metrics count does not match" + backup_scalars = [ + metric.metric["data"] + for metric in record_metrics + if metric.column_info.chart_type.value.column_type == "FLOAT" + ] + assert len(backup_scalars) == len(scalars), "Total scalars count does not match" + for scalar in backup_scalars: + assert scalar in record_scalars, f"Scalar {scalar} not found in original scalars" + backup_images = [ + metric for metric in record_metrics if metric.column_info.chart_type.value.column_type == "IMAGE" + ] + assert len(backup_images) == record_images_count, "Total images count does not match" + + +class MyCustomTracker(GeneralTracker): + "Basic tracker that writes to a csv for testing" + + _col_names = [ + "total_loss", + "iteration", + "my_text", + "learning_rate", + "num_iterations", + "some_boolean", + "some_string", + ] + + name = "my_custom_tracker" + requires_logging_directory = False + + def __init__(self, dir: str, **kwargs): + super().__init__(**kwargs) + self.log_dir = dir + self.f = None + self.writer = None + + def start(self): + if self.f is None: + self.f = open(os.path.join(self.log_dir, "log.csv"), "w+") + self.writer = csv.DictWriter(self.f, fieldnames=self._col_names) + self.writer.writeheader() + + @property + def tracker(self): + return self.writer + + def store_init_configuration(self, values: dict): + logger.info("Call init") + self.writer.writerow(values) + + def log(self, values: dict, step: Optional[int]): + logger.info("Call log") + self.writer.writerow(values) + + def finish(self): + self.f.close() + + +class CustomTrackerTestCase(unittest.TestCase): + def test_init_trackers(self): + with tempfile.TemporaryDirectory() as d: + tracker = MyCustomTracker(d) + accelerator = Accelerator(log_with=tracker) + config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"} + accelerator.init_trackers("Some name", config) + accelerator.end_training() + with open(f"{d}/log.csv") as f: + data = csv.DictReader(f) + data = next(data) + truth = { + "total_loss": "", + "iteration": "", + "my_text": "", + "learning_rate": "0.01", + "num_iterations": "12", + "some_boolean": "False", + "some_string": "some_value", + } + assert data == truth + + def test_log(self): + with tempfile.TemporaryDirectory() as d: + tracker = MyCustomTracker(d) + accelerator = Accelerator(log_with=tracker) + accelerator.init_trackers("Some name") + values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"} + accelerator.log(values, step=0) + accelerator.end_training() + with open(f"{d}/log.csv") as f: + data = csv.DictReader(f) + data = next(data) + truth = { + "total_loss": "0.1", + "iteration": "1", + "my_text": "some_value", + "learning_rate": "", + "num_iterations": "", + "some_boolean": "", + "some_string": "", + } + assert data == truth + + +@require_dvclive +@mock.patch("dvclive.live.get_dvc_repo", return_value=None) +class DVCLiveTrackingTest(unittest.TestCase): + def test_init_trackers(self, mock_repo): + project_name = "test_project_with_config" + with tempfile.TemporaryDirectory() as dirpath: + accelerator = Accelerator(log_with="dvclive") + config = { + "num_iterations": 12, + "learning_rate": 1e-2, + "some_boolean": False, + "some_string": "some_value", + } + init_kwargs = {"dvclive": {"dir": dirpath, "save_dvc_exp": False, "dvcyaml": None}} + accelerator.init_trackers(project_name, config, init_kwargs) + accelerator.end_training() + live = accelerator.trackers[0].live + params = load_yaml(live.params_file) + assert params == config + + def test_log(self, mock_repo): + project_name = "test_project_with_log" + with tempfile.TemporaryDirectory() as dirpath: + accelerator = Accelerator(log_with="dvclive", project_dir=dirpath) + init_kwargs = {"dvclive": {"dir": dirpath, "save_dvc_exp": False, "dvcyaml": None}} + accelerator.init_trackers(project_name, init_kwargs=init_kwargs) + values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"} + # Log step 0 + accelerator.log(values) + # Log step 1 + accelerator.log(values) + # Log step 3 (skip step 2) + accelerator.log(values, step=3) + accelerator.end_training() + live = accelerator.trackers[0].live + logs, latest = parse_metrics(live) + assert latest.pop("step") == 3 + assert latest == values + scalars = os.path.join(live.plots_dir, Metric.subfolder) + for val in values.keys(): + val_path = os.path.join(scalars, f"{val}.tsv") + steps = [int(row["step"]) for row in logs[val_path]] + assert steps == [0, 1, 3] + + +class TrackerDeferredInitializationTest(unittest.TestCase): + """ + Tests tracker's deferred initialization via `start()` method, preventing + premature `PartialState` access (and `torch.distributed` init) before + `Accelerator` has configured the distributed environment, especially with + `InitProcessGroupKwargs`. + """ + + @require_tensorboard + def test_tensorboard_deferred_init(self): + """Test that TensorBoard tracker initialization doesn't initialize distributed""" + with tempfile.TemporaryDirectory() as temp_dir: + PartialState._reset_state() + tracker = TensorBoardTracker(run_name="test_tb", logging_dir=temp_dir) + self.assertEqual(PartialState._shared_state, {}) + _ = Accelerator(log_with=tracker) + self.assertNotEqual(PartialState._shared_state, {}) + + @require_wandb + def test_wandb_deferred_init(self): + """Test that WandB tracker initialization doesn't initialize distributed""" + PartialState._reset_state() + tracker = WandBTracker(run_name="test_wandb") + self.assertEqual(PartialState._shared_state, {}) + _ = Accelerator(log_with=tracker) + self.assertNotEqual(PartialState._shared_state, {}) + + @require_trackio + def test_trackio_deferred_init(self): + """Test that trackio tracker initialization doesn't initialize distributed""" + PartialState._reset_state() + tracker = TrackioTracker(run_name="test_trackio") + self.assertEqual(PartialState._shared_state, {}) + _ = Accelerator(log_with=tracker) + self.assertNotEqual(PartialState._shared_state, {}) + + @require_comet_ml + def test_comet_ml_deferred_init(self): + """Test that CometML tracker initialization doesn't initialize distributed""" + PartialState._reset_state() + tracker = CometMLTracker(run_name="test_comet") + self.assertEqual(PartialState._shared_state, {}) + _ = Accelerator(log_with=tracker) + self.assertNotEqual(PartialState._shared_state, {}) + + @require_aim + def test_aim_deferred_init(self): + """Test that Aim tracker initialization doesn't initialize distributed""" + with tempfile.TemporaryDirectory() as temp_dir: + PartialState._reset_state() + tracker = AimTracker(run_name="test_aim", repo=temp_dir) + self.assertEqual(PartialState._shared_state, {}) + _ = Accelerator(log_with=tracker) + self.assertNotEqual(PartialState._shared_state, {}) + + @require_mlflow + def test_mlflow_deferred_init(self): + """Test that MLflow tracker initialization doesn't initialize distributed""" + with tempfile.TemporaryDirectory() as temp_dir: + PartialState._reset_state() + tracker = MLflowTracker(experiment_name="test_mlflow", logging_dir=temp_dir) + self.assertEqual(PartialState._shared_state, {}) + _ = Accelerator(log_with=tracker) + self.assertNotEqual(PartialState._shared_state, {}) + + @require_clearml + def test_clearml_deferred_init(self): + """Test that ClearML tracker initialization doesn't initialize distributed""" + PartialState._reset_state() + tracker = ClearMLTracker(run_name="test_clearml") + self.assertEqual(PartialState._shared_state, {}) + _ = Accelerator(log_with=tracker) + self.assertNotEqual(PartialState._shared_state, {}) + + @require_dvclive + def test_dvclive_deferred_init(self): + """Test that DVCLive tracker initialization doesn't initialize distributed""" + with tempfile.TemporaryDirectory() as temp_dir: + PartialState._reset_state() + tracker = DVCLiveTracker(dir=temp_dir) + self.assertEqual(PartialState._shared_state, {}) + _ = Accelerator(log_with=tracker) + self.assertNotEqual(PartialState._shared_state, {}) + + @require_swanlab + def test_swanlab_deferred_init(self): + """Test that SwanLab tracker initialization doesn't initialize distributed""" + PartialState._reset_state() + tracker = SwanLabTracker(run_name="test_swanlab") + self.assertEqual(PartialState._shared_state, {}) + _ = Accelerator(log_with=tracker) + self.assertNotEqual(PartialState._shared_state, {}) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_utils.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a07cc9cf03a47601cff27f50957cb69a290d03ef --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/tests/test_utils.py @@ -0,0 +1,592 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os +import pickle +import tempfile +import unittest +import warnings +from collections import UserDict, namedtuple +from typing import NamedTuple, Optional +from unittest.mock import Mock, patch + +import numpy as np +import pytest +import torch +from torch import nn + +from accelerate.big_modeling import cpu_offload_with_hook +from accelerate.hooks import attach_align_device_hook, remove_hook_from_module +from accelerate.state import PartialState +from accelerate.test_utils.testing import ( + require_huggingface_suite, + require_non_cpu, + require_non_torch_xla, + require_torch_min_version, + require_tpu, + require_triton, + torch_device, +) +from accelerate.test_utils.training import RegressionModel +from accelerate.utils import ( + CannotPadNestedTensorWarning, + check_os_kernel, + clear_environment, + convert_dict_to_env_variables, + convert_outputs_to_fp32, + convert_to_fp32, + extract_model_from_parallel, + find_device, + has_offloaded_params, + is_torch_xla_available, + listify, + pad_across_processes, + pad_input_tensors, + patch_environment, + purge_accelerate_environment, + recursively_apply, + save, + send_to_device, +) +from accelerate.utils.operations import is_namedtuple + + +if is_torch_xla_available(): + import torch_xla.distributed.spmd as xs + import torch_xla.runtime as xr + from torch_xla.experimental.spmd_fully_sharded_data_parallel import SpmdFullyShardedDataParallel as FSDPv2 + +ExampleNamedTuple = namedtuple("ExampleNamedTuple", "a b c") + + +class UtilsTester(unittest.TestCase): + def setUp(self): + # logging requires initialized state + PartialState() + + def test_send_to_device(self): + tensor = torch.randn(5, 2) + device = torch.device(f"{torch_device}:0") + + result1 = send_to_device(tensor, device) + assert torch.equal(result1.cpu(), tensor) + + result2 = send_to_device((tensor, [tensor, tensor], 1), device) + assert isinstance(result2, tuple) + assert torch.equal(result2[0].cpu(), tensor) + assert isinstance(result2[1], list) + assert torch.equal(result2[1][0].cpu(), tensor) + assert torch.equal(result2[1][1].cpu(), tensor) + assert result2[2] == 1 + + result2 = send_to_device({"a": tensor, "b": [tensor, tensor], "c": 1}, device) + assert isinstance(result2, dict) + assert torch.equal(result2["a"].cpu(), tensor) + assert isinstance(result2["b"], list) + assert torch.equal(result2["b"][0].cpu(), tensor) + assert torch.equal(result2["b"][1].cpu(), tensor) + assert result2["c"] == 1 + + result3 = send_to_device(ExampleNamedTuple(a=tensor, b=[tensor, tensor], c=1), device) + assert isinstance(result3, ExampleNamedTuple) + assert torch.equal(result3.a.cpu(), tensor) + assert isinstance(result3.b, list) + assert torch.equal(result3.b[0].cpu(), tensor) + assert torch.equal(result3.b[1].cpu(), tensor) + assert result3.c == 1 + + result4 = send_to_device(UserDict({"a": tensor, "b": [tensor, tensor], "c": 1}), device) + assert isinstance(result4, UserDict) + assert torch.equal(result4["a"].cpu(), tensor) + assert isinstance(result4["b"], list) + assert torch.equal(result4["b"][0].cpu(), tensor) + assert torch.equal(result4["b"][1].cpu(), tensor) + assert result4["c"] == 1 + + def test_honor_type(self): + with self.assertRaises(TypeError) as cm: + _ = recursively_apply(torch.tensor, (torch.tensor(1), 1), error_on_other_type=True) + assert ( + str(cm.exception) + == "Unsupported types () passed to `tensor`. Only nested list/tuple/dicts of objects that are valid for `is_torch_tensor` should be passed." + ) + + def test_listify(self): + tensor = torch.tensor([1, 2, 3, 4, 5]) + assert listify(tensor) == [1, 2, 3, 4, 5] + + tensor = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) + assert listify(tensor) == [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] + + tensor = torch.tensor([[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]]) + assert listify(tensor) == [[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]] + + def test_patch_environment(self): + with patch_environment(aa=1, BB=2): + assert os.environ.get("AA") == "1" + assert os.environ.get("BB") == "2" + + assert "AA" not in os.environ + assert "BB" not in os.environ + + def test_patch_environment_key_exists(self): + # check that patch_environment correctly restores pre-existing env vars + with patch_environment(aa=1, BB=2): + assert os.environ.get("AA") == "1" + assert os.environ.get("BB") == "2" + + with patch_environment(Aa=10, bb="20", cC=30): + assert os.environ.get("AA") == "10" + assert os.environ.get("BB") == "20" + assert os.environ.get("CC") == "30" + + assert os.environ.get("AA") == "1" + assert os.environ.get("BB") == "2" + assert "CC" not in os.environ + + assert "AA" not in os.environ + assert "BB" not in os.environ + assert "CC" not in os.environ + + def test_patch_environment_restores_on_error(self): + # we need to find an upper-case envvar + # because `patch_environment upper-cases all keys... + key, orig_value = next(kv for kv in os.environ.items() if kv[0].isupper()) + new_value = f"{orig_value}_foofoofoo" + with pytest.raises(RuntimeError), patch_environment(**{key: new_value}): + assert os.environ[key] == os.getenv(key) == new_value # noqa: TID251 + raise RuntimeError("Oopsy daisy!") + assert os.environ[key] == os.getenv(key) == orig_value # noqa: TID251 + + def test_clear_environment(self): + key, value = os.environ.copy().popitem() + with pytest.raises(RuntimeError), clear_environment(): + assert key not in os.environ + assert not os.getenv(key) # test the environment is actually cleared # noqa: TID251 + raise RuntimeError("Oopsy daisy!") + # Test values are restored + assert os.getenv(key) == os.environ[key] == value # noqa: TID251 + + def test_can_undo_convert_outputs(self): + model = RegressionModel() + model._original_forward = model.forward + model.forward = convert_outputs_to_fp32(model.forward) + model = extract_model_from_parallel(model, keep_fp32_wrapper=False) + _ = pickle.dumps(model) + + @require_non_cpu + def test_can_undo_fp16_conversion(self): + model = RegressionModel() + model._original_forward = model.forward + model.forward = torch.autocast(device_type=torch_device, dtype=torch.float16)(model.forward) + model.forward = convert_outputs_to_fp32(model.forward) + model = extract_model_from_parallel(model, keep_fp32_wrapper=False) + _ = pickle.dumps(model) + + @require_triton + @require_non_cpu + def test_dynamo(self): + model = RegressionModel() + model._original_forward = model.forward + model.forward = torch.autocast(device_type=torch_device, dtype=torch.float16)(model.forward) + model.forward = convert_outputs_to_fp32(model.forward) + model.forward = torch.compile(model.forward, backend="inductor") + inputs = torch.randn(4, 10).to(torch_device) + _ = model(inputs) + + def test_extract_model(self): + model = RegressionModel() + # could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU + distributed_model = torch.nn.parallel.DataParallel(model) + model_unwrapped = extract_model_from_parallel(distributed_model) + + assert model == model_unwrapped + + @require_tpu + @require_huggingface_suite + def test_extract_model_recursive_fsdpv2(self): + # Specifically tests for FSDPv2 extraction + # reported in https://github.com/huggingface/transformers/pull/29780 + xr.use_spmd() + from transformers import AutoModelForCausalLM + + model = AutoModelForCausalLM.from_pretrained("gpt2") + orig_state_dict_keys = list(model.state_dict().keys()) + num_devices = xr.global_runtime_device_count() + # Set environment for FSDPv2 to be active + xs.set_global_mesh(xs.Mesh(np.array(range(num_devices)), (num_devices, 1), axis_names=("fsdp", "tensor"))) + + def nested_wrap(model): + layer = model.wte + wrapped_layer = FSDPv2(layer) + model.wte = wrapped_layer + return model + + wrapped_model = nested_wrap(model) + unwrapped_model = extract_model_from_parallel(wrapped_model, recursive=True) + unwrapped_state_dict_keys = list(unwrapped_model.state_dict().keys()) + for original_key, new_key in zip(orig_state_dict_keys, unwrapped_state_dict_keys): + assert original_key == new_key, f"Keys did not align: {original_key} != {new_key}" + + def test_dynamo_extract_model_keep_torch_compile(self): + model = RegressionModel() + compiled_model = torch.compile(model) + + # could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU + distributed_model = torch.nn.parallel.DataParallel(model) + distributed_compiled_model = torch.compile(distributed_model) + compiled_model_unwrapped = extract_model_from_parallel(distributed_compiled_model, keep_torch_compile=True) + + assert compiled_model._orig_mod == compiled_model_unwrapped._orig_mod + + def test_dynamo_extract_model_remove_torch_compile(self): + model = RegressionModel() + compiled_model = torch.compile(model) + + # could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU + distributed_model = torch.nn.parallel.DataParallel(model) + distributed_compiled_model = torch.compile(distributed_model) + compiled_model_unwrapped = extract_model_from_parallel(distributed_compiled_model, keep_torch_compile=False) + + assert compiled_model._orig_mod == compiled_model_unwrapped + + def test_find_device(self): + assert find_device([1, "a", torch.tensor([1, 2, 3])]) == torch.device("cpu") + assert find_device({"a": 1, "b": torch.tensor([1, 2, 3])}) == torch.device("cpu") + assert find_device([1, "a"]) is None + + def test_check_os_kernel_no_warning_when_release_gt_min(self): + # min version is 5.5 + with patch("platform.uname", return_value=Mock(release="5.15.0-35-generic", system="Linux")): + with warnings.catch_warnings(record=True) as w: + check_os_kernel() + assert len(w) == 0 + + def test_check_os_kernel_no_warning_when_not_linux(self): + # system must be Linux + with patch("platform.uname", return_value=Mock(release="5.4.0-35-generic", system="Darwin")): + with warnings.catch_warnings(record=True) as w: + check_os_kernel() + assert len(w) == 0 + + def test_check_os_kernel_warning_when_release_lt_min(self): + # min version is 5.5 + with patch("platform.uname", return_value=Mock(release="5.4.0-35-generic", system="Linux")): + with self.assertLogs() as ctx: + check_os_kernel() + assert len(ctx.records) == 1 + assert ctx.records[0].levelname == "WARNING" + assert "5.4.0" in ctx.records[0].msg + assert "5.5.0" in ctx.records[0].msg + + @require_non_torch_xla + def test_save_safetensor_shared_memory(self): + class Model(nn.Module): + def __init__(self): + super().__init__() + self.a = nn.Linear(100, 100) + self.b = self.a + + def forward(self, x): + return self.b(self.a(x)) + + model = Model() + with tempfile.TemporaryDirectory() as tmp_dir: + save_path = os.path.join(tmp_dir, "model.safetensors") + with self.assertLogs(level="WARNING") as log: + save(model.state_dict(), save_path, safe_serialization=True) + assert len(log.records) == 1 + assert "Removed shared tensor" in log.output[0] + + @require_torch_min_version(version="1.12") + def test_pad_across_processes(self): + from torch.nested import nested_tensor + + nt = nested_tensor([[1, 2, 3], [1], [1, 2]]) + with self.assertWarns(CannotPadNestedTensorWarning): + nt2 = pad_across_processes(nt) + assert nt is nt2 + + # Basic functionality + tensor = torch.randn(4, 3, 100) + padded_tensor = pad_across_processes(tensor, dim=-1) + assert padded_tensor.shape[-1] == 100 + + # dim = -4 is out of bounds + padded_tensor = pad_across_processes(tensor, dim=-4) + assert padded_tensor is tensor + + def test_slice_and_concatenate(self): + # First base case: 2 processes, batch size of 1 + num_processes = 2 + batch_size = 1 + batch = torch.rand(batch_size, 4) + result = pad_input_tensors(batch, batch_size, num_processes) + # We should expect there to be 2 items now + assert result.shape == torch.Size([2, 4]) + + # Second base case: 2 processes, batch size of 3 + num_processes = 2 + batch_size = 3 + batch = torch.rand(batch_size, 4) + result = pad_input_tensors(batch, batch_size, num_processes) + # We should expect there to be 4 items now + assert result.shape == torch.Size([4, 4]) + + # Third base case: 3 processes, batch size of 4 + num_processes = 3 + batch_size = 4 + batch = torch.rand(batch_size, 4, 4) + result = pad_input_tensors(batch, batch_size, num_processes) + # We should expect there to be 6 items now + assert result.shape == torch.Size([6, 4, 4]) + + # Fourth base case: 4 processes, batch size of 3 + num_processes = 4 + batch_size = 3 + batch = torch.rand(batch_size, 4, 4) + result = pad_input_tensors(batch, batch_size, num_processes) + # We should expect there to be 4 items now + assert result.shape == torch.Size([4, 4, 4]) + + # Fifth base case: 6 processes, batch size of 4 + num_processes = 6 + batch_size = 4 + batch = torch.rand(batch_size, 4, 4) + result = pad_input_tensors(batch, batch_size, num_processes) + # We should expect there to be 6 items now + assert result.shape == torch.Size([6, 4, 4]) + + # Sixth base case: 6 processes, batch size of 1 + num_processes = 6 + batch_size = 1 + batch = torch.rand(batch_size, 4, 4) + result = pad_input_tensors(batch, batch_size, num_processes) + # We should expect there to be 6 items now + assert result.shape == torch.Size([6, 4, 4]) + + # Seventh base case: 6 processes, batch size of 2 + num_processes = 6 + batch_size = 2 + batch = torch.rand(batch_size, 4, 4) + result = pad_input_tensors(batch, batch_size, num_processes) + # We should expect there to be 6 items now + assert result.shape == torch.Size([6, 4, 4]) + + # Eighth base case: 6 processes, batch size of 61 + num_processes = 6 + batch_size = 61 + batch = torch.rand(batch_size, 4, 4) + result = pad_input_tensors(batch, batch_size, num_processes) + # We should expect there to be 66 items now + assert result.shape == torch.Size([66, 4, 4]) + + def test_send_to_device_compiles(self): + compiled_send_to_device = torch.compile(send_to_device, fullgraph=True) + compiled_send_to_device(torch.zeros([1], dtype=torch.bfloat16), "cpu") + + def test_convert_to_fp32(self): + compiled_convert_to_fp32 = torch.compile(convert_to_fp32, fullgraph=True) + compiled_convert_to_fp32(torch.zeros([1], dtype=torch.bfloat16)) + + def test_named_tuples(self): + class QuantTensorBase(NamedTuple): + value: torch.Tensor + scale: Optional[torch.Tensor] + zero_point: Optional[torch.Tensor] + + class Second(QuantTensorBase): + pass + + a = QuantTensorBase(torch.tensor(1.0), None, None) + b = Second(torch.tensor(1.0), None, None) + + point = namedtuple("Point", ["x", "y"]) + p = point(11, y=22) + + self.assertTrue(is_namedtuple(a)) + self.assertTrue(is_namedtuple(b)) + self.assertTrue(is_namedtuple(p)) + self.assertFalse(is_namedtuple((1, 2))) + self.assertFalse(is_namedtuple("hey")) + self.assertFalse(is_namedtuple(object())) + + def test_convert_dict_to_env_variables(self): + env = {"ACCELERATE_DEBUG_MODE": "1", "BAD_ENV_NAME": ">> python xla_spawn.py --num_cores=NUM_CORES_YOU_HAVE + YOUR_TRAINING_SCRIPT.py (--arg1 --arg2 --arg3 and all other + arguments of your training script) + +""" + +import importlib +import sys +from argparse import REMAINDER, ArgumentParser +from pathlib import Path + +import torch_xla.distributed.xla_multiprocessing as xmp +from torch_xla import device_count + + +def parse_args(): + """ + Helper function parsing the command line options + @retval ArgumentParser + """ + parser = ArgumentParser( + description=( + "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes" + ) + ) + + # Optional arguments for the launch helper + num_devices = device_count() + parser.add_argument( + "--num_cores", + type=int, + default=num_devices, + help="Number of TPU cores to use (1 or number of available devices).", + ) + + # positional + parser.add_argument( + "training_script", + type=str, + help=( + "The full path to the single TPU training " + "program/script to be launched in parallel, " + "followed by all the arguments for the " + "training script" + ), + ) + + # rest from the training program + parser.add_argument("training_script_args", nargs=REMAINDER) + + return parser.parse_args() + + +def main(): + args = parse_args() + + # Import training_script as a module. + script_fpath = Path(args.training_script) + sys.path.append(str(script_fpath.parent.resolve())) + mod_name = script_fpath.stem + mod = importlib.import_module(mod_name) + + # Patch sys.argv + sys.argv = [args.training_script] + args.training_script_args + num_cores = args.num_cores + if num_cores == device_count() and num_cores != 1: + # There is an error in xmp.spawn that causes it to fail when num_cores is specified and not 1, so we set it to + # None when it matches the number of devices. + num_cores = None + xmp.spawn(mod._mp_fn, args=(), nprocs=args.num_cores) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/utils/log_reports.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/utils/log_reports.py new file mode 100644 index 0000000000000000000000000000000000000000..6775cb76e1738c48f9e03ef03bec1d5fc5970659 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/utils/log_reports.py @@ -0,0 +1,177 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import json +import os +from datetime import date +from pathlib import Path + +from tabulate import DataRow, TableFormat, tabulate + + +hf_table_format = TableFormat( + lineabove=None, + linebelowheader=None, + linebetweenrows=None, + linebelow=None, + headerrow=DataRow("", "|", "|"), + datarow=DataRow("", "|", "|"), + padding=1, + with_header_hide=None, +) + + +failed = [] +group_info = [] + +no_error_payload = {"type": "section", "text": {"type": "plain_text", "text": "No failed tests! 🤗", "emoji": True}} + +payload = [ + { + "type": "header", + "text": { + "type": "plain_text", + "text": f"🤗 Accelerate nightly {os.environ.get('TEST_TYPE', '')} test results", + "emoji": True, + }, + } +] + +total_num_failed = 0 +for log in Path().glob("*.log"): + section_num_failed = 0 + with open(log) as f: + for line in f: + line = json.loads(line) + if line.get("nodeid", "") != "": + test = line["nodeid"] + if line.get("duration", None) is not None: + duration = f"{line['duration']:.4f}" + if line.get("outcome", "") == "failed": + section_num_failed += 1 + failed.append([test, duration, log.name.split("_")[0]]) + total_num_failed += 1 + group_info.append([str(log), section_num_failed, failed]) + failed = [] + log.unlink() + +message = "" +all_files2failed = [] +if total_num_failed > 0: + for name, num_failed, failed_tests in group_info: + if num_failed > 0: + if num_failed == 1: + message += f"*{name[1:]}: {num_failed} failed test*\n" + else: + message += f"*{name[1:]}: {num_failed} failed tests*\n" + failed_table = [] + files2failed = {} + for test in failed_tests: + data = test[0].split("::") + data[0] = data[0].split("/")[-1] + if data[0] not in files2failed: + files2failed[data[0]] = [data[1:]] + else: + files2failed[data[0]] += [data[1:]] + failed_table.append(data) + + files = [test[0] for test in failed_table] + individual_files = list(set(files)) + # Count number of instances in failed_tests + table = [] + for file in individual_files: + table.append([file, len(files2failed[file])]) + + failed_table = tabulate( + table, + headers=["Test Location", "Num Failed"], + tablefmt=hf_table_format, + stralign="right", + ) + message += f"\n```\n{failed_table}\n```" + all_files2failed.append(files2failed) + if len(message) > 3000: + err = "Too many failed tests, please see the full report in the Action results." + offset = len(err) + 10 + message = message[: 3000 - offset] + f"\n...\n```\n{err}" + print(f"### {message}") +else: + message = "No failed tests! 🤗" + print(f"## {message}") + payload.append(no_error_payload) + +if os.environ.get("TEST_TYPE", "") != "": + from slack_sdk import WebClient + + client = WebClient(token=os.environ["SLACK_API_TOKEN"]) + if message != "No failed tests! 🤗": + md_report = { + "type": "section", + "text": { + "type": "mrkdwn", + "text": message, + }, + } + payload.append(md_report) + action_button = { + "type": "section", + "text": { + "type": "mrkdwn", + "text": "*For more details:*", + }, + "accessory": { + "type": "button", + "text": { + "type": "plain_text", + "text": "Check Action results", + "emoji": True, + }, + "url": f"https://github.com/{os.environ['GITHUB_REPOSITORY']}/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + payload.append(action_button) + date_report = { + "type": "context", + "elements": [ + { + "type": "plain_text", + "text": f"Nightly {os.environ.get('TEST_TYPE')} test results for {date.today()}", + } + ], + } + payload.append(date_report) + response = client.chat_postMessage(channel="#accelerate-ci-daily", text=message, blocks=payload) + ts = response.data["ts"] + for failed_file in all_files2failed: + for test_location, test_failures in failed_file.items(): + # Keep only the first instance of the test name + test_class = "" + for i, row in enumerate(test_failures): + if row[0] != test_class: + test_class = row[0] + else: + test_failures[i][0] = "" + + payload = { + "type": "section", + "text": { + "type": "mrkdwn", + "text": f"Test location: {test_location}\n```\n{tabulate(test_failures, headers=['Class', 'Test'], tablefmt=hf_table_format, stralign='right')}\n```", + }, + } + + client.chat_postMessage( + channel="#accelerate-ci-daily", + thread_ts=ts, + blocks=[payload], + ) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/source/utils/stale.py b/tasks/tasksmith-b1dd32dfa88b/tests/source/utils/stale.py new file mode 100644 index 0000000000000000000000000000000000000000..24333fed4c76b34cf895f30a253a9a7042f9d324 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/source/utils/stale.py @@ -0,0 +1,69 @@ +# Copyright 2022 The HuggingFace Team, the AllenNLP library authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Script to close stale issue. Taken in part from the AllenNLP repository. +https://github.com/allenai/allennlp. +""" + +import os +from datetime import datetime as dt +from datetime import timezone + +from github import Github + + +LABELS_TO_EXEMPT = [ + "good first issue", + "feature request", + "wip", +] + + +def main(): + g = Github(os.environ["GITHUB_TOKEN"]) + repo = g.get_repo("huggingface/accelerate") + open_issues = repo.get_issues(state="open") + + for issue in open_issues: + comments = sorted([comment for comment in issue.get_comments()], key=lambda i: i.created_at, reverse=True) + last_comment = comments[0] if len(comments) > 0 else None + current_time = dt.now(timezone.utc) + days_since_updated = (current_time - issue.updated_at).days + days_since_creation = (current_time - issue.created_at).days + if ( + last_comment is not None + and last_comment.user.login == "github-actions[bot]" + and days_since_updated > 7 + and days_since_creation >= 30 + and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) + ): + # Close issue since it has been 7 days of inactivity since bot mention. + issue.edit(state="closed") + elif ( + days_since_updated > 23 + and days_since_creation >= 30 + and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) + ): + # Add stale comment + issue.create_comment( + "This issue has been automatically marked as stale because it has not had " + "recent activity. If you think this still needs to be addressed " + "please comment on this thread.\n\nPlease note that issues that do not follow the " + "[contributing guidelines](https://github.com/huggingface/accelerate/blob/main/CONTRIBUTING.md) " + "are likely to be ignored." + ) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/test.sh b/tasks/tasksmith-b1dd32dfa88b/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c92b552378bd5c90e06861fb4c3cf5e93ef8dd72 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +exec /opt/tasksmith-venv/bin/python -I /tests/grade.py diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/test_driver.py b/tasks/tasksmith-b1dd32dfa88b/tests/test_driver.py new file mode 100644 index 0000000000000000000000000000000000000000..3d47bdfd18bf0d184d186cb919f64637213b6c60 --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/test_driver.py @@ -0,0 +1,38 @@ +"""Private pytest entry point with a bounded framework-tampering check. + +The host still owns reward parsing. This guard detects replacement or in-place +editing of unittest assertions, a demonstrated attack against repository tests. +It does not claim to isolate arbitrary test and solution code in one interpreter. +""" + +from __future__ import annotations + +import sys +import unittest + + +def run(arguments: list[str]) -> int: + import pytest + + # Capture before pytest imports any repository modules. Retain code objects + # too: an attacker can mutate function.__code__ without replacing a method. + original = { + name: (value, getattr(value, "__code__", None)) + for name, value in vars(unittest.TestCase).items() + if name.startswith("assert") and callable(value) + } + case = unittest.TestCase + code = int(pytest.main(arguments)) + changed = [] + for name, (method, implementation) in original.items(): + current = getattr(case, name, None) + if current is not method or getattr(current, "__code__", None) is not implementation: + changed.append(name) + if unittest.TestCase is not case or changed: + sys.stderr.write("Verifier framework was modified: " + ", ".join(changed) + "\n") + return 254 + return code + + +if __name__ == "__main__": + raise SystemExit(run(sys.argv[1:])) diff --git a/tasks/tasksmith-b1dd32dfa88b/tests/test_results.py b/tasks/tasksmith-b1dd32dfa88b/tests/test_results.py new file mode 100644 index 0000000000000000000000000000000000000000..05ce2c730e38e02bad44f2344e88e5f1cb02cb8d --- /dev/null +++ b/tasks/tasksmith-b1dd32dfa88b/tests/test_results.py @@ -0,0 +1,65 @@ +"""Strict test evidence used by repository recipes and their exported verifiers.""" + +from __future__ import annotations + +from dataclasses import dataclass +from xml.etree import ElementTree + + +@dataclass(frozen=True) +class TestResults: + __test__ = False + statuses: dict[str, str] + returncode: int + + @property + def passed(self) -> set[str]: + return {name for name, status in self.statuses.items() if status == "passed"} + + +def parse_junit(text: str, *, returncode: int) -> TestResults: + if " dict[str, list[str]]: + if healthy.returncode != 0 or not healthy.passed: + raise ValueError("Reference must execute successfully with passing tests") + if healthy.statuses.keys() != defective.statuses.keys(): + raise ValueError("Mutation changed test collection; contrast is not comparable") + failing = sorted( + name for name in healthy.passed if defective.statuses[name] in {"failed", "error"} + ) + if not failing or defective.returncode != 1: + raise ValueError("No intended fail-to-pass contrast") + return {"FAIL_TO_PASS": failing, "PASS_TO_PASS": sorted(healthy.passed - set(failing))} diff --git a/tasks/tasksmith-b3c12843c3fb/environment/Dockerfile b/tasks/tasksmith-b3c12843c3fb/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0f728f6ef3d1d4224f2acef5eb579769ef0d8913 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/Dockerfile @@ -0,0 +1,15 @@ +FROM pytorch/pytorch:2.11.0-cuda12.8-cudnn9-runtime +WORKDIR /workspace +RUN apt-get update && apt-get install -y --no-install-recommends python3-venv && rm -rf /var/lib/apt/lists/* +RUN python -m venv --system-site-packages /opt/tasksmith-venv +ENV PATH=/opt/tasksmith-venv/bin:$PATH +RUN python -m pip install --no-cache-dir setuptools==81.0.0 wheel==0.46.3 numpy==2.4.3 packaging==26.0 psutil==7.2.2 pytest==8.4.2 jinja2==3.1.6 transformers==5.17.0 accelerate==1.15.0 peft==0.20.0 pandas==3.0.5 datasets==5.0.1 parameterized==0.9.0 pillow==12.1.1 huggingface-hub==1.31.0 tokenizers==0.23.2 requests==2.32.5 safetensors==0.8.0 typing-extensions==4.16.0 +COPY source /workspace +RUN python -m pip install --no-cache-dir --no-deps --no-build-isolation -e . +ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 +ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1 +RUN apt-get update && apt-get install -y --no-install-recommends tmux && rm -rf /var/lib/apt/lists/* +RUN useradd -m learner && chown -R learner:learner /workspace +RUN sh -c 'set -eu; profile="$1/.bash_profile"; original=""; if [ -e "$profile" ]; then original=.repo2rlenv-original-bash-profile; test ! -e "$1/$original"; mv "$profile" "$1/$original"; elif [ -r "$1/.bash_login" ]; then original=.bash_login; elif [ -r "$1/.profile" ]; then original=.profile; fi; if [ -n "$original" ]; then printf '"'"'if [ -r "$HOME/%s" ]; then . "$HOME/%s"; fi\n'"'"' "$original" "$original" > "$profile"; else : > "$profile"; fi; printf '"'"'\nexport PATH="%s/bin:$PATH"\nexport VIRTUAL_ENV="%s"\n'"'"' "$2" "$2" >> "$profile"' -- /home/learner /opt/tasksmith-venv && chown learner:learner /home/learner/.bash_profile +RUN printf 'export PATH="%s/bin:$PATH"\nexport VIRTUAL_ENV="%s"\n' /opt/tasksmith-venv /opt/tasksmith-venv > /etc/repo2rlenv-venv.sh +ENV BASH_ENV=/etc/repo2rlenv-venv.sh diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/.gitignore b/tasks/tasksmith-b3c12843c3fb/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6219ed974aa8d884323fbfca2c26694d3abd1683 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/.gitignore @@ -0,0 +1,152 @@ +*.bak +.gitattributes +.last_checked +.gitconfig +*.bak +*.log +*~ +~* +_tmp* +tmp* +tags + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv +venv/ +ENV/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +.vscode +*.swp + +# osx generated files +.DS_Store +.DS_Store? +.Trashes +ehthumbs.db +Thumbs.db +.idea + +# pytest +.pytest_cache + +# tools/trust-doc-nbs +docs_src/.last_checked + +# symlinks to fastai +docs_src/fastai +tools/fastai + +# link checker +checklink/cookies.txt + +# .gitconfig is now autogenerated +.gitconfig + +# wandb files +nbs/wandb/ +examples/notebooks/wandb/ +wandb/ + +# uv +uv.lock + +# AI agent generated artifacts +/.agents/skills +/.claude/skills \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/.pre-commit-config.yaml b/tasks/tasksmith-b3c12843c3fb/environment/source/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..017eb89f8c7d5e8cc6763e942af625dffeb37fce --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/.pre-commit-config.yaml @@ -0,0 +1,19 @@ +repos: + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.13.3 + hooks: + - id: ruff-check + types_or: [ python, pyi ] + args: [ --fix ] + - id: ruff-format + types_or: [ python, pyi ] + + - repo: local + hooks: + - id: doc-builder-style + name: Check style with doc-builder + language: python + entry: doc-builder style trl tests docs/source --max_len 119 + additional_dependencies: ["git+https://github.com/huggingface/doc-builder@2430c1ec91d04667414e2fa31ecfc36c153ea391", ruff] # See GH-5633 + pass_filenames: false + types_or: [python, markdown, rst] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/AGENTS.md b/tasks/tasksmith-b3c12843c3fb/environment/source/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..347a556b5bc6d8afa59ecb114ba705331c7295c3 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/AGENTS.md @@ -0,0 +1,97 @@ +# AGENTS.md + +## Repository-specific guidance + +### Main code vs experimental code + +The repository is separated into **main code** and **experimental code**. + +* **Main code** should remain stable, consistent, and well-tested. +* **Experimental code** may be less stable and may contain inconsistent patterns or limited testing. + +Small non-invasive improvements that make experimental code more consistent with the main codebase are encouraged, but avoid large refactors. + +### Paper implementations + +If a PR implements a method, algorithm, or training approach from a research paper, it must also add a corresponding subsection to `paper_index.md`. + +When reviewing such PRs, ensure that `paper_index.md` was updated. + +### Code duplication and consistency + +Trainers in this repository are **self-contained by design**. Shared logic (generation, reward computation, metric logging, weight syncing, etc.) is deliberately duplicated across trainers rather than abstracted into a shared base class. + +This is intentional: each trainer must be readable, modifiable, and evolvable in isolation. The base class (`_BaseTrainer`) provides only minimal utilities (model card generation). Everything else — vLLM generation paths, `_get_per_token_logps_and_entropies`, `_calculate_rewards`, `_prepare_inputs`, metric logging — is copied in full. + +**The tradeoff**: duplication is accepted, but **consistency is mandatory**. When the same logic appears in multiple trainers, the duplicated blocks must stay aligned: + +- Same variable names (`self._last_loaded_step`, `self._metrics[mode]`, …) +- Same control flow structure (if/elif/else branches in the same order) +- Same comments (word-for-word when the logic is identical) +- Divergences only where the trainer's semantics require it (e.g., GRPO extracts logprobs from vLLM, RLOO discards them) + +**Consistency over correctness**: this is a strong requirement. When duplicating code, reproduce it exactly — even if you believe the original has a bug. Do not silently fix the issue in your copy. Instead, keep your copy consistent with the source and report the problem so it can be fixed across all trainers in a dedicated PR. A correct-but-inconsistent codebase is harder to maintain than a consistently-wrong one that can be fixed in a single sweep. + +**When modifying duplicated code**: if you change a pattern that exists in multiple trainers (e.g., the vLLM generation path in `_generate_single_turn`), apply the same change to all other trainers. A fix in GRPO often implies the same fix in RLOO, and vice versa. Not propagating a change is a bug. + +**When reviewing**: if a PR touches duplicated logic, verify that all copies are updated consistently. A common mistake is fixing one trainer and forgetting the others. + +### Simplicity + +This codebase values **leanness and simplicity above all**. Prefer straightforward, inline code over abstractions, helpers, or utilities — even at the cost of some robustness or generality. + +Concretely: + +- Do not add layers of indirection (registries, factory patterns, plugin systems). A contributor should be able to read a trainer top to bottom and understand the full flow. +- Prefer a simple implementation that covers 90% of cases over a complex one that covers 100%. A function that handles the common path in 20 lines is better than a catch-all that handles every edge case in 80. +- Do not add defensive code, fallback paths, or configuration options "just in case". Only handle cases that actually exist today. +- Avoid `hasattr` and `getattr`. Their use is almost always a symptom of overly defensive programming or a disguised version check (e.g., "this attribute was added in version X"). Instead, either drop the conditional entirely or express the version check explicitly with a version comparison. There is nearly always a cleaner alternative. +- When in doubt, prefer less code. Every new function, parameter, or branch is maintenance burden. The best abstraction is often no abstraction. + +## Documentation + +### Docstrings + +Docstrings must follow the repository format below. Do **not** convert docstrings to other styles (Google, NumPy, etc.). + +Rules: + +* Types appear in backticks inside parentheses: (`str`) +* Optional parameters are marked with `*optional*` +* Defaults are written as: `defaults to ` +* When the default is `None`, prefer ```(`str`, *optional*)``` instead of ```(`str` or `None`, *optional*, defaults to `None`)``` +* Union types use `or`: `str` or `None` +* References to classes use the format: [`~transformers.PreTrainedModel`] +* Class docstrings may group parameters using headers such as: `> Parameters for X:` + +Example: + +````python +def method(self, param1: str, param2: int = 1, param3: float | None = None): + """ + Brief one-line description of what this does. + + Args: + param1 (`str`): + Description of required param. + param2 (`int`, *optional*, defaults to `1`): + Description of optional param with default. + param3 (`float`, *optional*): + Description of optional param without explicit default. + + Returns: + `dict` with keys: + - `key1` (`list[int]`): + Description of this key. + + Examples: + + ```python + >>> my_func("hello") + ``` + """ +```` + +### Links to papers + +When linking to papers, use `https://huggingface.co/papers/` instead of `https://arxiv.org/abs/` (same ID suffix system). diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/CITATION.cff b/tasks/tasksmith-b3c12843c3fb/environment/source/CITATION.cff new file mode 100644 index 0000000000000000000000000000000000000000..c1a44ae0d7d8b1b5d58d16aa020e5e5cc9efe363 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/CITATION.cff @@ -0,0 +1,41 @@ +cff-version: 1.2.0 +title: 'TRL: Transformers Reinforcement Learning' +message: >- + If you use this software, please cite it using the + metadata from this file. +type: software +authors: + - given-names: Leandro + family-names: von Werra + - given-names: Younes + family-names: Belkada + - given-names: Lewis + family-names: Tunstall + - given-names: Edward + family-names: Beeching + - given-names: Tristan + family-names: Thrush + - given-names: Nathan + family-names: Lambert + - given-names: Shengyi + family-names: Huang + - given-names: Kashif + family-names: Rasul + - given-names: Quentin + family-names: Gallouédec +repository-code: 'https://github.com/huggingface/trl' +abstract: >- + TRL (Transformers Reinforcement Learning) is an + open-source toolkit for aligning transformer models via + post-training. It provides practical, scalable + implementations of SFT, reward modeling, DPO, and GRPO + within the Hugging Face ecosystem. +keywords: + - transformers + - reinforcement learning + - preference optimization + - language model alignment + - post-training +license: Apache-2.0 +version: '1.7' +date-released: '2020-03-27' diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/CLAUDE.md b/tasks/tasksmith-b3c12843c3fb/environment/source/CLAUDE.md new file mode 100644 index 0000000000000000000000000000000000000000..347a556b5bc6d8afa59ecb114ba705331c7295c3 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/CLAUDE.md @@ -0,0 +1,97 @@ +# AGENTS.md + +## Repository-specific guidance + +### Main code vs experimental code + +The repository is separated into **main code** and **experimental code**. + +* **Main code** should remain stable, consistent, and well-tested. +* **Experimental code** may be less stable and may contain inconsistent patterns or limited testing. + +Small non-invasive improvements that make experimental code more consistent with the main codebase are encouraged, but avoid large refactors. + +### Paper implementations + +If a PR implements a method, algorithm, or training approach from a research paper, it must also add a corresponding subsection to `paper_index.md`. + +When reviewing such PRs, ensure that `paper_index.md` was updated. + +### Code duplication and consistency + +Trainers in this repository are **self-contained by design**. Shared logic (generation, reward computation, metric logging, weight syncing, etc.) is deliberately duplicated across trainers rather than abstracted into a shared base class. + +This is intentional: each trainer must be readable, modifiable, and evolvable in isolation. The base class (`_BaseTrainer`) provides only minimal utilities (model card generation). Everything else — vLLM generation paths, `_get_per_token_logps_and_entropies`, `_calculate_rewards`, `_prepare_inputs`, metric logging — is copied in full. + +**The tradeoff**: duplication is accepted, but **consistency is mandatory**. When the same logic appears in multiple trainers, the duplicated blocks must stay aligned: + +- Same variable names (`self._last_loaded_step`, `self._metrics[mode]`, …) +- Same control flow structure (if/elif/else branches in the same order) +- Same comments (word-for-word when the logic is identical) +- Divergences only where the trainer's semantics require it (e.g., GRPO extracts logprobs from vLLM, RLOO discards them) + +**Consistency over correctness**: this is a strong requirement. When duplicating code, reproduce it exactly — even if you believe the original has a bug. Do not silently fix the issue in your copy. Instead, keep your copy consistent with the source and report the problem so it can be fixed across all trainers in a dedicated PR. A correct-but-inconsistent codebase is harder to maintain than a consistently-wrong one that can be fixed in a single sweep. + +**When modifying duplicated code**: if you change a pattern that exists in multiple trainers (e.g., the vLLM generation path in `_generate_single_turn`), apply the same change to all other trainers. A fix in GRPO often implies the same fix in RLOO, and vice versa. Not propagating a change is a bug. + +**When reviewing**: if a PR touches duplicated logic, verify that all copies are updated consistently. A common mistake is fixing one trainer and forgetting the others. + +### Simplicity + +This codebase values **leanness and simplicity above all**. Prefer straightforward, inline code over abstractions, helpers, or utilities — even at the cost of some robustness or generality. + +Concretely: + +- Do not add layers of indirection (registries, factory patterns, plugin systems). A contributor should be able to read a trainer top to bottom and understand the full flow. +- Prefer a simple implementation that covers 90% of cases over a complex one that covers 100%. A function that handles the common path in 20 lines is better than a catch-all that handles every edge case in 80. +- Do not add defensive code, fallback paths, or configuration options "just in case". Only handle cases that actually exist today. +- Avoid `hasattr` and `getattr`. Their use is almost always a symptom of overly defensive programming or a disguised version check (e.g., "this attribute was added in version X"). Instead, either drop the conditional entirely or express the version check explicitly with a version comparison. There is nearly always a cleaner alternative. +- When in doubt, prefer less code. Every new function, parameter, or branch is maintenance burden. The best abstraction is often no abstraction. + +## Documentation + +### Docstrings + +Docstrings must follow the repository format below. Do **not** convert docstrings to other styles (Google, NumPy, etc.). + +Rules: + +* Types appear in backticks inside parentheses: (`str`) +* Optional parameters are marked with `*optional*` +* Defaults are written as: `defaults to ` +* When the default is `None`, prefer ```(`str`, *optional*)``` instead of ```(`str` or `None`, *optional*, defaults to `None`)``` +* Union types use `or`: `str` or `None` +* References to classes use the format: [`~transformers.PreTrainedModel`] +* Class docstrings may group parameters using headers such as: `> Parameters for X:` + +Example: + +````python +def method(self, param1: str, param2: int = 1, param3: float | None = None): + """ + Brief one-line description of what this does. + + Args: + param1 (`str`): + Description of required param. + param2 (`int`, *optional*, defaults to `1`): + Description of optional param with default. + param3 (`float`, *optional*): + Description of optional param without explicit default. + + Returns: + `dict` with keys: + - `key1` (`list[int]`): + Description of this key. + + Examples: + + ```python + >>> my_func("hello") + ``` + """ +```` + +### Links to papers + +When linking to papers, use `https://huggingface.co/papers/` instead of `https://arxiv.org/abs/` (same ID suffix system). diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/CODE_OF_CONDUCT.md b/tasks/tasksmith-b3c12843c3fb/environment/source/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..ef09fa1375a81440bf0733b659045453a5476c43 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/CODE_OF_CONDUCT.md @@ -0,0 +1,133 @@ + +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +feedback@huggingface.co. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/CONTRIBUTING.md b/tasks/tasksmith-b3c12843c3fb/environment/source/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..3ec168688b208b177bbfe1b0fa41228ac323b621 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/CONTRIBUTING.md @@ -0,0 +1,430 @@ +# How to contribute to TRL? + +Everyone is welcome to contribute, and we value everybody's contribution. Code contributions are not the only way to help the community. Answering questions, helping others, and improving the documentation are also immensely valuable. + +It also helps us if you spread the word! Reference the library in blog posts about the awesome projects it made possible, shout out on Twitter every time it has helped you, or simply ⭐️ the repository to say thank you. + +However you choose to contribute, please be mindful and respect our [code of conduct](https://github.com/huggingface/trl/blob/main/CODE_OF_CONDUCT.md). + +**This guide was heavily inspired by the awesome [scikit-learn guide to contributing](https://github.com/scikit-learn/scikit-learn/blob/main/CONTRIBUTING.md).** + +## AI usage policy + +We encourage using AI tools to help with contributions — they can be a great way to write better code, catch issues early, and navigate the codebase. + +That said, **we will not review fully AI-generated PRs from first-time contributors.** Our review resources are limited, and reviewing agent-generated code is especially costly when the contributor cannot engage meaningfully in the discussion or vouch for the correctness of the changes. We want to make sure that every PR we spend time on reflects a genuine understanding of what is being proposed. + +## Ways to contribute + +There are several ways you can contribute to TRL: + +* Fix outstanding issues with the existing code. +* Submit issues related to bugs or desired new features. +* Implement trainers for new post-training algorithms. +* Contribute to the examples or the documentation. + +If you don't know where to start, there is a special [Good First Issue](https://github.com/huggingface/trl/labels/%F0%9F%91%B6%20good%20first%20issue) listing. It will give you a list of open issues that are beginner-friendly and help you start contributing to open-source. The best way to do that is to open a Pull Request and link it to the issue that you'd like to work on. We try to give priority to opened PRs as we can easily track the progress of the fix, and if the contributor does not have time anymore, someone else can take the PR over. + +For something slightly more challenging, you can also take a look at the [Good Second Issue](https://github.com/huggingface/trl/labels/%F0%9F%A7%92%20good%20second%20issue) list. In general though, if you feel like you know what you're doing, go for it and we'll help you get there! 🚀 + +> All contributions are equally valuable to the community. 🥰 + +Before you start contributing make sure you have installed all the dev tools: + +```bash +pip install -e .[dev] +``` + +## Fixing outstanding issues + +If you notice an issue with the existing code and have a fix in mind, feel free to [start contributing](#submitting-a-pull-request-pr) and open a Pull Request! + +## Submitting a bug-related issue or feature request + +Do your best to follow these guidelines when submitting a bug-related issue or a feature request. It will make it easier for us to come back to you quickly and with good feedback. + +### Did you find a bug? + +The TRL library is robust and reliable thanks to users who report the problems they encounter. + +Before you report an issue, we would really appreciate it if you could **make sure the bug was not already reported** (use the search bar on GitHub under Issues). Your issue should also be related to bugs in the library itself, and not your code. + +Once you've confirmed the bug hasn't already been reported, please include the following information in your issue so we can quickly resolve it: + +* Your **OS type and version**, **Python**, **PyTorch**, **TRL** and **Transformers** versions. +* A short, self-contained, code snippet that allows us to reproduce the bug in less than 30s. +* The *full* traceback if an exception is raised. +* Attach any other additional information, like screenshots, you think may help. + +To get the OS and software versions automatically, run the following command: + +```bash +trl env +``` + +### Do you want a new feature? + +If there is a new feature you'd like to see in TRL, please open an issue and describe: + +1. What is the *motivation* behind this feature? Is it related to a problem or frustration with the library? Is it a feature related to something you need for a project? Is it something you worked on and think it could benefit the community? + + Whatever it is, we'd love to hear about it! + +2. Describe your requested feature in as much detail as possible. The more you can tell us about it, the better we'll be able to help you. +3. Provide a *code snippet* that demonstrates the feature's usage. +4. If the feature is related to a paper, please include a link. + +If your issue is well written we're already 80% of the way there by the time you create it. + +## Do you want to implement a new trainer? + +New post-training methods are published frequently and those that satisfy the following criteria are good candidates to be integrated into TRL: + +* **Simplicity:** Does the new method achieve similar performance as prior methods, but with less complexity? A good example is Direct Preference Optimization (DPO) [[Rafailov et al, 2023]](https://huggingface.co/papers/2305.18290), which provided a simpler and compelling alternative to RLHF methods. +* **Efficiency:** Does the new method provide a significant improvement in training efficiency? A good example is Odds Ratio Preference Optimization (ORPO) [[Hong et al, 2023]](https://huggingface.co/papers/2403.07691), which utilizes a similar objective as DPO but requires half the GPU VRAM. + +Methods that only provide incremental improvements at the expense of added complexity or compute costs are unlikely to be included in TRL. + +If you want to implement a trainer for a new post-training method, first open an issue and provide the following information: + +* A short description of the method and a link to the paper. +* Link to the implementation if it is open-sourced. +* Link to model weights trained with the method if they are available. + +Based on the community and maintainer feedback, the next step will be to implement the trainer and config classes. See the following examples for inspiration: + +* Paired preference optimisation: [`dpo_trainer.py`](./trl/trainer/dpo_trainer.py) and [`dpo_config.py`](./trl/trainer/dpo_config.py) +* RL-based optimisation: [`rloo_trainer.py`](./trl/trainer/rloo_trainer.py) and [`rloo_config.py`](./trl/trainer/rloo_config.py) +* Online optimisation: [`online_dpo_trainer.py`](./trl/experimental/online_dpo/online_dpo_trainer.py) and [`online_dpo_config.py`](./trl/experimental/online_dpo/online_dpo_config.py) + +## Do you want to add documentation? + +We're always looking for improvements to the documentation that make it more clear and accurate. Please let us know how the documentation can be improved, such as typos, dead links, and any missing, unclear, or inaccurate content... We'll be happy to make the changes or help you contribute if you're interested! + +## Submitting a pull request (PR) + +> [!IMPORTANT] +> **First-time contributors: you MUST fill out the [PR template](https://github.com/huggingface/trl/blob/main/.github/PULL_REQUEST_TEMPLATE.md) when opening a pull request.** PRs that do not follow the template (missing description, unchecked checklist, no linked issue) will be closed without review. + +Before writing code, we strongly advise you to search through the existing PRs or issues to make sure that nobody is already working on the same thing. If you are unsure, it is always a good idea to open an issue to get some feedback. + +You will need basic `git` proficiency to be able to contribute to TRL. `git` is not the easiest tool to use but it has the greatest manual. Type `git --help` in a shell and enjoy. If you prefer books, [Pro Git](https://git-scm.com/book/en/v2) is a very good reference. + +Follow these steps to start contributing: + +1. Fork the [repository](https://github.com/huggingface/trl) by clicking on the 'Fork' button on the repository's page. This creates a copy of the code under your GitHub user account. + +2. Clone your fork to your local disk, and add the base repository as a remote. The following command assumes you have your public SSH key uploaded to GitHub. See the following guide for more [information](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository). + + ```bash + git clone git@github.com:/trl.git + cd trl + git remote add upstream https://github.com/huggingface/trl.git + ``` + +3. Create a new branch to hold your development changes, and do this for every new PR you work on. + + Start by synchronizing your `main` branch with the `upstream/main` branch (more details in the [GitHub Docs](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/syncing-a-fork)): + + ```bash + git checkout main + git fetch upstream + git merge upstream/main + ``` + + Once your `main` branch is synchronized, create a new branch from it: + + ```bash + git checkout -b a-descriptive-name-for-my-changes + ``` + + **Do not** work on the `main` branch. + +4. Set up a development environment by running the following command in a conda or a virtual environment you've created for working on this library: + + ```bash + pip install -e .[dev] + ``` + + (If TRL was already installed in the virtual environment, remove it with `pip uninstall trl` before reinstalling it.) + + Alternatively, if you are using [Visual Studio Code](https://code.visualstudio.com/Download), the fastest way to get set up is by using the provided Dev Container. Check [the documentation on how to get started with dev containers](https://code.visualstudio.com/docs/remote/containers). + +5. Develop the features on your branch. + + As you work on the features, you should make sure that the test suite passes. You should run the tests impacted by your changes like this (see below an explanation regarding the environment variable): + + ```bash + pytest tests/.py + ``` + + > For the following commands leveraging the `make` utility. + + You can also run the full suite with the following command. + + ```bash + make test + ``` + + TRL relies on `ruff` for maintaining consistent code formatting across its source files. Before submitting any PR, you should apply automatic style corrections and run code verification checks. + + We provide a `precommit` target in the `Makefile` that simplifies this process by running all required checks and optimizations on only the files modified by your PR. + + To apply these checks and corrections in one step, use: + + ```bash + make precommit + ``` + + This command runs the following: + + * Executes `pre-commit` hooks to automatically fix style issues with `ruff` and other tools. + * Runs additional scripts such as adding copyright information. + + If you prefer to apply the style corrections separately or review them individually, the `pre-commit` hook will handle the formatting for the files in question. + + Once you're happy with your changes, add changed files using `git add` and make a commit with `git commit` to record your changes locally: + + ```bash + git add modified_file.py + git commit + ``` + + Please write [good commit messages](https://chris.beams.io/posts/git-commit/). + + It is a good idea to sync your copy of the code with the original + repository regularly. This way you can quickly account for changes: + + ```bash + git fetch upstream + git rebase upstream/main + ``` + + Push the changes to your account using: + + ```bash + git push -u origin a-descriptive-name-for-my-changes + ``` + +6. Once you are satisfied (**and the checklist below is happy too**), go to the webpage of your fork on GitHub. Click on 'Pull request' to send your changes to the project maintainers for review. + +7. It's ok if maintainers ask you for changes. It happens to core contributors too! To ensure everyone can review your changes in the pull request, work on your local branch and push the updates to your fork. They will automatically appear in the pull request. + +### Checklist + +1. The title of your pull request should be a summary of its contribution; +2. If your pull request addresses an issue, please mention the issue number in the pull request description to make sure they are linked (and people consulting the issue know you are working on it); +3. To indicate a work in progress please prefix the title with `[WIP]`, or mark the PR as a draft PR. These are useful to avoid duplicated work, and to differentiate it from PRs ready to be merged; +4. Make sure existing tests pass; +5. Add high-coverage tests. No quality testing = no merge. + +### Tests + +An extensive test suite is included to test the library behavior and several examples. Library tests can be found in +the [tests folder](https://github.com/huggingface/trl/tree/main/tests). + +We use `pytest` to run the tests. From the root of the +repository here's how to run tests with `pytest` for the library: + +```bash +python -m pytest -sv ./tests +``` + +That's how `make test` is implemented (without the `pip install` line)! + +You can specify a smaller set of tests to test only the feature +you're working on. + +### Default values guidelines + +1. **Use defaults when appropriate**: + + Provide default values unless the parameter's value varies significantly by use case. For example, datasets or models should not have defaults, but parameters like `learning_rate` should. + +2. **Prioritize proven defaults**: + + Default values should align with those recommended in the original paper or method. Alternatives require strong evidence of superior performance in most cases. + +3. **Ensure safety and predictability**: + + Defaults must be safe, expected and reliable. Avoid settings that could lead to surprising outcomes, such as excessive memory usage or poor performance in edge cases. + +4. **Balance consistency and flexibility**: + + Aim for consistent defaults across similar functions or methods. However, consistency should not be preferred to point 2 or 3. + +5. **Opt-in for new features**: + + Do not enable new features or improvements (e.g., novel loss functions) by default. Users should explicitly opt-in to use these. + +### Writing documentation + +High-quality documentation is crucial for maintaining a project that is easy to use, understand, and extend. When adding new features, ensure they are thoroughly documented to maintain consistency and clarity throughout the project. + +To illustrate what good documentation looks like, here’s an example of a well-documented function: + +````python +def replicate_str(string: str, n: int, sep: str = " ") -> str: + r""" + Replicate a string `n` times with a separator. + + Args: + string (`str`): + String to replicate. + n (`int`): + Number of times to replicate the string. + sep (`str`, *optional*, defaults to `" "`): + Separator to use between each replication. + + Returns: + `str`: The replicated string. + + Examples: + ```python + >>> replicate_str("hello", 3) + "hello hello hello" + >>> replicate_str("hello", 3, sep=", ") + "hello, hello, hello" + ``` + """ + return sep.join([string] * n) +```` + +* **Line Wrapping:** Applied a consistent line wrap at column 120 to improve readability. +* **Definite Articles:** Removed definite articles where possible to streamline language. (Eg: Changed "The string to replicate" to "String to replicate") +* **Type Annotations:** + * Always include type definitions, indicating if a parameter is optional and specifying the default value. + +* **String Defaults:** + * Ensured that default string values are wrapped in double quotes: + + ```txt + defaults to `"foo"` + ``` + +* **Dictionary Typing:** + * Replaced generic `dict` type hints with more explicit `dict[str, Any]` to clarify expected key-value pairs. +* **Default Value Formatting:** + * Consistently surrounded default values with backticks for improved formatting: + + ```txt + defaults to `4` + ``` + +* **Sub-sectioning:** When the number of arguments is large, consider breaking them into sub-sections for better readability. + + ```python + def calculate_statistics(data: list[float], precision: int = 2, include_variance: bool = False) -> dict[str, float]: + r""" + Calculates basic statistics for a given dataset. + + Args: + > Data inputs + + data (`list[float]`): + A list of numerical values to analyze. + + > Configuration parameters + + precision (`int`, *optional*, defaults to `2`): + Number of decimal places to round the results. + include_variance (`bool`, *optional*, defaults to `False`): + Whether to include the variance of the dataset in the results. + + Returns: + `dict[str, float]`: + A dictionary containing calculated statistics such as mean, median, and optionally variance. + """ + ... + ``` + +### Deprecation and backward compatibility + +Our approach to deprecation and backward compatibility is flexible and based on the feature’s usage and impact. Each deprecation is carefully evaluated, aiming to balance innovation with user needs. + +When a feature or component is marked for deprecation, its use will emit a warning message. This warning will include: + +* **Transition Guidance**: Instructions on how to migrate to the alternative solution or replacement. +* **Removal Version**: The target version when the feature will be removed, providing users with a clear timeframe to transition. + +Example: + + ```python + warnings.warn( + "The `Trainer.foo` method is deprecated and will be removed in version 0.14.0. " + "Please use the `Trainer.bar` class instead.", + FutureWarning, + stacklevel=2, + ) + ``` + +The deprecation and removal schedule is based on each feature's usage and impact, with examples at two extremes: + +* **Experimental or Low-Use Features**: For a feature that is experimental or has limited usage, backward compatibility may not be maintained between releases. Users should therefore anticipate potential breaking changes from one version to the next. + +* **Widely-Used Components**: For a feature with high usage, we aim for a more gradual transition period of approximately **5 months**, generally scheduling deprecation around **5 minor releases** after the initial warning. + +These examples represent the two ends of a continuum. The specific timeline for each feature will be determined individually, balancing innovation with user stability needs. + +### Working with warnings + +Warnings play a critical role in guiding users toward resolving potential issues, but they should be used thoughtfully to avoid unnecessary noise. Unlike logging, which provides informational context or operational details, warnings signal conditions that require attention and action. Overusing warnings can dilute their importance, leading users to ignore them entirely. + +#### Definitions + +* **Correct**: An operation is correct if it is valid, follows the intended approach, and aligns with the current best practices or guidelines within the codebase. This is the recommended or intended way to perform the operation. +* **Supported**: An operation is supported if it is technically valid and works within the current codebase, but it may not be the most efficient, optimal, or recommended way to perform the task. This includes deprecated features or legacy approaches that still work but may be phased out in the future. + +#### Choosing the right message + +* **Correct → No warning**: + If the operation is fully valid and expected, no message should be issued. The system is working as intended, so no warning is necessary. + +* **Correct but deserves attention → No warning, possibly a log message**: + When an operation is correct but uncommon or requires special attention, providing an informational message can be helpful. This keeps users informed without implying any issue. If available, use the logger to output this message. Example: + + ```python + logger.info("This is an informational message about a rare but correct operation.") + ``` + +* **Correct but very likely a mistake → Warning with option to disable**: + In rare cases, you may want to issue a warning for a correct operation that’s very likely a mistake. In such cases, you must provide an option to suppress the warning. This can be done with a flag in the function. Example: + + ```python + def my_function(foo, bar, _warn=True): + if foo == bar: + if _warn: + logger.warning("foo and bar are the same, this is likely a mistake. Ignore this warning by setting `_warn=False`.") + # Do something + ``` + +* **Supported but not correct → Warning**: + If the operation is technically supported but is deprecated, suboptimal, or could cause future issues (e.g., conflicting arguments), a warning should be raised. This message should be actionable, meaning it must explain how to resolve the issue. Example: + + ```python + def my_function(foo, bar): + if foo and bar: + logger.warning("Both `foo` and `bar` were provided, but only one is allowed. Ignoring `foo`. Please pass only one of these arguments.") + # Do something + ``` + +* **Not supported → Exception**: + If the operation is invalid or unsupported, raise an exception. This indicates that the operation cannot be performed and requires immediate attention. Example: + + ```python + def my_function(foo, bar): + if foo and bar: + raise ValueError("Both `foo` and `bar` were provided, but only one is allowed. Please pass only one of these arguments.") + ``` + +By following this classification, you ensure that warnings, information, and exceptions are used appropriately, providing clear guidance to the user without cluttering the system with unnecessary messages. + +## Coding with AI agents + +This repository keeps AI-agent configuration in `.ai/` and exposes local agent files via symlinks. + +Skills can be exposed to agents by running `make codex` or `make claude` + +`AGENTS.md`, `CLAUDE.md`, and `.cursor/BUGBOT.md` all point to `.ai/AGENTS.md`. + +Cursor reads `AGENTS.md` and Bugbot reads `.cursor/BUGBOT.md`. Cursor reads skills from Claude or Codex paths, so setting up the repository for Claude or Codex will work for Cursor. diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/LICENSE b/tasks/tasksmith-b3c12843c3fb/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f577b7741dfb5c6af119f250971549dd7750acb9 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2020-2026 The HuggingFace Team + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/MANIFEST.in b/tasks/tasksmith-b3c12843c3fb/environment/source/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..e843c590270bb5f441cef5f596c7cb3e32ebd26b --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/MANIFEST.in @@ -0,0 +1,10 @@ +include LICENSE +include CONTRIBUTING.md +include README.md +include trl/accelerate_configs/*.yaml +include trl/templates/*.md +include trl/chat_templates/*.jinja +include trl/chat_templates/*.md +include trl/skills/**/*.md +recursive-exclude * __pycache__ +prune tests diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/README.md b/tasks/tasksmith-b3c12843c3fb/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..46c99c45c437af7f12c0d9d3a16e89307b9941fc --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/README.md @@ -0,0 +1,205 @@ +# TRL - Transformers Reinforcement Learning + +
+ + + TRL Banner + +
+ +

+ +

+

A comprehensive library to post-train foundation models

+

+ +

+ License + Documentation + GitHub release + Hugging Face Hub +

+ +## 🎉 What's New + +**TRL v1:** We released TRL v1 — a major milestone that marks a real shift in what TRL is. Read the [blog post](https://huggingface.co/blog/trl-v1) to learn more. + +**🚢 Harbor:** We now support [Harbor](https://huggingface.co/docs/trl/harbor) — train agents against sandboxed task suites (instruction + sandbox image + in-sandbox verifier) via [`GRPOTrainer`](https://huggingface.co/docs/trl/grpo_trainer)'s `environment_factory`. + +## Overview + +TRL is a cutting-edge library designed for post-training foundation models using advanced techniques like Supervised Fine-Tuning (SFT), Group Relative Policy Optimization (GRPO), and Direct Preference Optimization (DPO). Built on top of the [🤗 Transformers](https://github.com/huggingface/transformers) ecosystem, TRL supports a variety of model architectures and modalities, and can be scaled-up across various hardware setups. + +## Highlights + +- **Trainers**: Various fine-tuning methods are easily accessible via trainers like [`SFTTrainer`](https://huggingface.co/docs/trl/sft_trainer), [`GRPOTrainer`](https://huggingface.co/docs/trl/grpo_trainer), [`DPOTrainer`](https://huggingface.co/docs/trl/dpo_trainer), [`RewardTrainer`](https://huggingface.co/docs/trl/reward_trainer) and more. + +- **Efficient and scalable**: + - Leverages [🤗 Accelerate](https://github.com/huggingface/accelerate) to scale from single GPU to multi-node clusters using methods like [DDP](https://pytorch.org/tutorials/intermediate/ddp_tutorial.html) and [DeepSpeed](https://github.com/deepspeedai/DeepSpeed). + - Full integration with [🤗 PEFT](https://github.com/huggingface/peft) enables training on large models with modest hardware via quantization and LoRA/QLoRA. + - Integrates [🦥 Unsloth](https://github.com/unslothai/unsloth) for accelerating training using optimized kernels. + +- **Command Line Interface (CLI)**: A simple interface lets you fine-tune with models without needing to write code. + +## Installation + +### Python Package + +Install the library using `pip`: + +```bash +pip install trl +``` + +### From source + +If you want to use the latest features before an official release, you can install TRL from source: + +```bash +pip install git+https://github.com/huggingface/trl.git +``` + +### Repository + +If you want to use the examples you can clone the repository with the following command: + +```bash +git clone https://github.com/huggingface/trl.git +``` + +## Quick Start + +For more flexibility and control over training, TRL provides dedicated trainer classes to post-train language models or PEFT adapters on a custom dataset. Each trainer in TRL is a light wrapper around the 🤗 Transformers trainer and natively supports distributed training methods like DDP, DeepSpeed ZeRO, and FSDP. + +### `SFTTrainer` + +Here is a basic example of how to use the [`SFTTrainer`](https://huggingface.co/docs/trl/sft_trainer): + +```python +from trl import SFTTrainer +from datasets import load_dataset + +dataset = load_dataset("trl-lib/Capybara", split="train") + +trainer = SFTTrainer( + model="Qwen/Qwen2.5-0.5B", + train_dataset=dataset, +) +trainer.train() +``` + +### `GRPOTrainer` + +[`GRPOTrainer`](https://huggingface.co/docs/trl/grpo_trainer) implements the [Group Relative Policy Optimization (GRPO) algorithm](https://huggingface.co/papers/2402.03300) that is more memory-efficient than PPO and was used to train [Deepseek AI's R1](https://huggingface.co/deepseek-ai/DeepSeek-R1). + +```python +from datasets import load_dataset +from trl import GRPOTrainer +from trl.rewards import accuracy_reward + +dataset = load_dataset("trl-lib/DeepMath-103K", split="train") + +trainer = GRPOTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", + reward_funcs=accuracy_reward, + train_dataset=dataset, +) +trainer.train() +``` + +> [!NOTE] +> For reasoning models, use the `reasoning_accuracy_reward()` function for better results. + +### `DPOTrainer` + +[`DPOTrainer`](https://huggingface.co/docs/trl/dpo_trainer) implements the popular [Direct Preference Optimization (DPO) algorithm](https://huggingface.co/papers/2305.18290) that was used to post-train [Llama 3](https://huggingface.co/papers/2407.21783) and many other models. Here is a basic example of how to use the `DPOTrainer`: + +```python +from datasets import load_dataset +from trl import DPOTrainer + +dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") + +trainer = DPOTrainer( + model="Qwen/Qwen3-0.6B", + train_dataset=dataset, +) +trainer.train() +``` + +### `RewardTrainer` + +Here is a basic example of how to use the [`RewardTrainer`](https://huggingface.co/docs/trl/reward_trainer): + +```python +from trl import RewardTrainer +from datasets import load_dataset + +dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") + +trainer = RewardTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", + train_dataset=dataset, +) +trainer.train() +``` + +## Command Line Interface (CLI) + +You can use the TRL Command Line Interface (CLI) to quickly get started with post-training methods like Supervised Fine-Tuning (SFT) or Direct Preference Optimization (DPO): + +**SFT:** + +```bash +trl sft --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name trl-lib/Capybara \ + --output_dir Qwen2.5-0.5B-SFT +``` + +**DPO:** + +```bash +trl dpo --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ + --dataset_name argilla/Capybara-Preferences \ + --output_dir Qwen2.5-0.5B-DPO +``` + +Read more about CLI in the [relevant documentation section](https://huggingface.co/docs/trl/clis) or use `--help` for more details. + +## Development + +If you want to contribute to `trl` or customize it to your needs make sure to read the [contribution guide](https://github.com/huggingface/trl/blob/main/CONTRIBUTING.md) and make sure you make a dev install: + +```bash +git clone https://github.com/huggingface/trl.git +cd trl/ +pip install -e .[dev] +``` + +## Experimental + +A minimal incubation area is available under `trl.experimental` for unstable / fast-evolving features. Anything there may change or be removed in any release without notice. + +Example: + +```python +from trl.experimental.new_trainer import NewTrainer +``` + +Read more in the [Experimental docs](https://huggingface.co/docs/trl/experimental_overview). + +## Citation + +```bibtex +@software{vonwerra2020trl, + title = {{TRL: Transformers Reinforcement Learning}}, + author = {von Werra, Leandro and Belkada, Younes and Tunstall, Lewis and Beeching, Edward and Thrush, Tristan and Lambert, Nathan and Huang, Shengyi and Rasul, Kashif and Gallouédec, Quentin}, + license = {Apache-2.0}, + url = {https://github.com/huggingface/trl}, + year = {2020} +} +``` + +## License + +This repository's source code is available under the [Apache-2.0 License](LICENSE). diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/VERSION b/tasks/tasksmith-b3c12843c3fb/environment/source/VERSION new file mode 100644 index 0000000000000000000000000000000000000000..a7a1e80a7e90978c08982cf2ef7b71e7eb2c8721 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/VERSION @@ -0,0 +1 @@ +1.8.0.dev0 \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/pyproject.toml b/tasks/tasksmith-b3c12843c3fb/environment/source/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..6005d1a5fbfb6ab4d52e9ca27d8098fe5f150988 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/pyproject.toml @@ -0,0 +1,205 @@ +[build-system] +requires = ["setuptools >= 77.0.3"] +build-backend = "setuptools.build_meta" + +[project] +name = "trl" +description = "Train transformer language models with reinforcement learning." +authors = [ + { name = "Leandro von Werra", email = "leandro.vonwerra@gmail.com" } +] +readme = { file = "README.md", content-type = "text/markdown" } +license = "Apache-2.0" +license-files = ["LICENSE"] +keywords = [ + "transformers", "huggingface", "language modeling", "post-training", "rlhf", "sft", "dpo", "grpo" +] +classifiers = [ + "Development Status :: 2 - Pre-Alpha", + "Intended Audience :: Developers", + "Intended Audience :: Science/Research", + "Natural Language :: English", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14" +] +requires-python = ">=3.10" +dependencies = [ + "accelerate>=1.4.0", + "datasets>=4.7.0", # Support Json type and on_mixed_types="use_json" + "jinja2", + "packaging>20.0", + "transformers>=4.56.2", +] +dynamic = ["version"] + +[project.urls] +Homepage = "https://github.com/huggingface/trl" + +[project.scripts] +trl = "trl.cli:main" + +[project.optional-dependencies] +bco = [ + "scikit-learn", + "joblib" +] +deepspeed = [ + "deepspeed>=0.14.4", + "transformers!=5.1.0", # see transformers#43780 +] +kernels = [ # transformers renamed the "hub-kernels" extra to "kernels" in 5.1.0 + "transformers[kernels]", # transformers >= 5.1.0 + "transformers[hub-kernels]", # transformers < 5.1.0 +] +liger = [ + "liger-kernel>=0.8.0" +] +peft = [ + "peft>=0.8.0" +] +quality = [ + "pre-commit", + "hf-doc-builder" +] +quantization = [ + "bitsandbytes" +] +scikit = [ + "scikit-learn" +] +test = [ + "pytest-cov", + "pytest-datadir>=1.7.0", # lazy datadirs + "pytest-rerunfailures==15.1", + "pytest-xdist", + "pytest" +] +vllm = [ + "vllm>=0.14.0,<=0.23.0", + "fastapi", + "pydantic", + "aiohttp>=3.13.3", + "requests", + "uvicorn" +] +vlm = [ + "Pillow", + "torchvision", + "num2words==0.5.14" +] +math_verify = [ + "math-verify>=0.5.2", +] +openreward = [ + "openreward>=0.1.109; python_version >= '3.11'", # openreward requires Python 3.11+ +] +harbor = [ + "harbor>=0.13.0; python_version >= '3.12'", # harbor requires Python 3.12+ (pulls its sandbox backends) +] +dev = [ + # bco + "scikit-learn", + "joblib", + # deepspeed + "deepspeed>=0.14.4", + # kernels: transformers renamed the "hub-kernels" extra to "kernels" in 5.1.0 + "transformers[kernels]", # transformers >= 5.1.0 + "transformers[hub-kernels]", # transformers < 5.1.0 + # liger + "liger-kernel>=0.8.0", + # openreward (requires Python 3.11+) + "openreward>=0.1.109; python_version >= '3.11'", + # peft + "peft>=0.8.0", + # quality + "pre-commit", + "hf-doc-builder", + # quantization + "bitsandbytes", + # scikit: included in bco + # test + "pytest-cov", + "pytest-datadir>=1.7.0", # lazy datadirs + "pytest-rerunfailures==15.1", + "pytest-xdist", + "pytest", + # vllm: not included in dev by default due to CUDA error; see GH-4228 + # vlm + "Pillow", + "torchvision", + "num2words==0.5.14", + # for response parsing (required for training with tools) + "jmespath", +] + +[tool.setuptools] +package-dir = {"trl" = "trl"} + +[tool.setuptools.dynamic] +version = { file = "VERSION" } + +[tool.coverage.run] +branch = true + +[tool.ruff] +target-version = "py310" +line-length = 119 +src = ["trl"] + +[tool.ruff.lint] +ignore = [ + "B028", # warning without explicit stacklevel + "C408", # dict() calls (stylistic) + "C901", # function complexity + "E501", +] +extend-select = ["E", "F", "I", "W", "UP", "B", "T", "C"] + +[tool.ruff.lint.per-file-ignores] +# Allow prints in auxiliary scripts +"examples/**.py" = ["T201"] +"scripts/**.py" = ["T201"] +"trl/cli/**.py" = ["T201"] +"trl/skills/cli.py" = ["T201"] +# Ignore import violations in all `__init__.py` files. +"__init__.py" = ["F401"] + +[tool.ruff.lint.isort] +lines-after-imports = 2 +known-first-party = ["trl"] + +[tool.pytest.ini_options] +markers = [ + "slow: marks tests as slow (deselect with '-m \"not slow\"')", + "low_priority: marks tests as low priority (deselect with '-m \"not low_priority\"')", + "invariant: training-invariant checks (run with '-m invariant')", +] +norecursedirs = [ + "tests/experimental", + "tests/invariant", +] +filterwarnings = [ + # SWIG deprecations from SWIG-generated C/C++ extensions: sentencepiece + # Upstream issue: https://github.com/google/sentencepiece/issues/1150 + "ignore:builtin type SwigPyPacked has no __module__ attribute:DeprecationWarning", + "ignore:builtin type SwigPyObject has no __module__ attribute:DeprecationWarning", + "ignore:builtin type swigvarlink has no __module__ attribute:DeprecationWarning", + + # PyTorch JIT deprecations (upstream, not actionable in TRL) + # Upstream issue: https://github.com/deepspeedai/DeepSpeed/issues/7835 + # Upstream PR: https://github.com/deepspeedai/DeepSpeed/pull/7840 + # Upstream fix released in deepspeed v0.18.6: https://github.com/deepspeedai/DeepSpeed/releases/tag/v0.18.6 + "ignore:`torch.jit.script_method` is deprecated:DeprecationWarning", + "ignore:`torch.jit.script` is deprecated:DeprecationWarning", + + # PyTorch DataLoader pin_memory device argument deprecations + # Triggered internally by torch.utils.data, not by our code + # Upstream issue: https://github.com/pytorch/pytorch/issues/174546 + "ignore:The argument 'device' of Tensor.pin_memory:DeprecationWarning", + "ignore:The argument 'device' of Tensor.is_pinned:DeprecationWarning", +] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4947fc16c56e7abf1de978619b878bde579c9d15 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/__init__.py @@ -0,0 +1,132 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys +from importlib.metadata import PackageNotFoundError, version +from typing import TYPE_CHECKING + +from . import _compat +from ._lazy_module import _LazyModule + + +try: + __version__ = version("trl") +except PackageNotFoundError: + __version__ = "unknown" + +_import_structure = { + "chat_template_utils": [ + "add_response_schema", + "clone_chat_template", + "get_training_chat_template", + "supports_tool_calling", + ], + "data_utils": [ + "apply_chat_template", + "extract_prompt", + "is_conversational", + "is_conversational_from_value", + "maybe_apply_chat_template", + "maybe_convert_to_chatml", + "maybe_extract_prompt", + "maybe_unpair_preference_dataset", + "pack_dataset", + "prepare_multimodal_messages", + "prepare_multimodal_messages_vllm", + "unpair_preference_dataset", + ], + "models": ["create_reference_model"], + "scripts": ["DatasetMixtureConfig", "ScriptArguments", "TrlParser", "get_dataset", "init_zero_verbose"], + "trainer": [ + "BEMACallback", + "DPOConfig", + "DPOTrainer", + "GRPOConfig", + "GRPOTrainer", + "KTOConfig", + "KTOTrainer", + "LogCompletionsCallback", + "ModelConfig", + "RewardConfig", + "RewardTrainer", + "RichProgressCallback", + "RLOOConfig", + "RLOOTrainer", + "SFTConfig", + "SFTTrainer", + "SyncRefModelCallback", + "WeaveCallback", + "get_kbit_device_map", + "get_peft_config", + "get_quantization_config", + ], +} + +if TYPE_CHECKING: + from .chat_template_utils import ( + add_response_schema, + clone_chat_template, + get_training_chat_template, + supports_tool_calling, + ) + from .data_utils import ( + apply_chat_template, + extract_prompt, + is_conversational, + is_conversational_from_value, + maybe_apply_chat_template, + maybe_convert_to_chatml, + maybe_extract_prompt, + maybe_unpair_preference_dataset, + pack_dataset, + prepare_multimodal_messages, + prepare_multimodal_messages_vllm, + unpair_preference_dataset, + ) + from .models import create_reference_model + from .scripts import DatasetMixtureConfig, ScriptArguments, TrlParser, get_dataset, init_zero_verbose + from .trainer import ( + BEMACallback, + DPOConfig, + DPOTrainer, + GRPOConfig, + GRPOTrainer, + KTOConfig, + KTOTrainer, + LogCompletionsCallback, + ModelConfig, + RewardConfig, + RewardTrainer, + RichProgressCallback, + RLOOConfig, + RLOOTrainer, + SFTConfig, + SFTTrainer, + SyncRefModelCallback, + WeaveCallback, + get_kbit_device_map, + get_peft_config, + get_quantization_config, + ) + +else: + import sys + + sys.modules[__name__] = _LazyModule( + __name__, + globals()["__file__"], + _import_structure, + module_spec=__spec__, + extra_objects={"__version__": __version__}, + ) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/_compat.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..31086a2e912cc9926e3fab7d2a8045fa5421c49d --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/_compat.py @@ -0,0 +1,164 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Compatibility shims for third-party dependencies. + +This module contains temporary patches to handle version incompatibilities between TRL's dependencies. + +Each patch should be removed when minimum version requirements eliminate the need. +""" + +import warnings + +from packaging.version import Version + +from .import_utils import _is_package_available + + +def _is_package_version_below(package_name: str, version_threshold: str) -> bool: + """ + Check if installed package version is below the given threshold. + + Args: + package_name (str): Package name. + version_threshold (str): Maximum version threshold. + + Returns: + - True if package is installed and version < version_threshold. + - False if package is not installed or version >= version_threshold. + """ + try: + is_available, version = _is_package_available(package_name, return_version=True) + return is_available and Version(version) < Version(version_threshold) + except Exception as e: + warnings.warn( + f"Failed to check {package_name} version against {version_threshold}: {e}. " + f"Compatibility patch may not be applied.", + stacklevel=2, + ) + return False + + +def _is_package_version_at_least(package_name: str, version_threshold: str) -> bool: + """ + Check if installed package version is at least the given threshold. + + Args: + package_name (str): Package name. + version_threshold (str): Minimum version threshold. + + Returns: + - True if package is installed and version >= version_threshold. + - False if package is not installed or version < version_threshold. + """ + try: + is_available, version = _is_package_available(package_name, return_version=True) + return is_available and Version(version) >= Version(version_threshold) + except Exception as e: + warnings.warn( + f"Failed to check {package_name} version against {version_threshold}: {e}. " + f"Compatibility patch may not be applied.", + stacklevel=2, + ) + return False + + +def _patch_vllm_logging() -> None: + """Set vLLM logging level to ERROR by default to reduce noise.""" + if _is_package_available("vllm"): + import os + + os.environ["VLLM_LOGGING_LEVEL"] = os.getenv("VLLM_LOGGING_LEVEL", "ERROR") + + +def _patch_transformers_hybrid_cache() -> None: + """ + Fix HybridCache import for transformers v5 compatibility. + + - Issue: peft import HybridCache from transformers.cache_utils + - HybridCache removed in https://github.com/huggingface/transformers/pull/43168 (transformers>=5.0.0) + - Fixed in peft: https://github.com/huggingface/peft/pull/2735 (released in v0.18.0) + - This can be removed when TRL requires peft>=0.18.0 + """ + if _is_package_version_at_least("transformers", "5.0.0") and _is_package_version_below("peft", "0.18.0"): + try: + import transformers.cache_utils + from transformers.utils.import_utils import _LazyModule + + Cache = transformers.cache_utils.Cache + + # Patch for liger_kernel: Add HybridCache as an alias for Cache in the cache_utils module + transformers.cache_utils.HybridCache = Cache + + # Patch for peft: Patch _LazyModule.__init__ to add HybridCache to transformers' lazy loading structures + _original_lazy_module_init = _LazyModule.__init__ + + def _patched_lazy_module_init(self, name, *args, **kwargs): + _original_lazy_module_init(self, name, *args, **kwargs) + if name == "transformers": + # Update _LazyModule's internal structures + if hasattr(self, "_import_structure") and "cache_utils" in self._import_structure: + if "HybridCache" not in self._import_structure["cache_utils"]: + self._import_structure["cache_utils"].append("HybridCache") + + if hasattr(self, "_class_to_module"): + self._class_to_module["HybridCache"] = "cache_utils" + + if hasattr(self, "__all__") and "HybridCache" not in self.__all__: + self.__all__.append("HybridCache") + + self.HybridCache = Cache + + _LazyModule.__init__ = _patched_lazy_module_init + + except Exception as e: + warnings.warn(f"Failed to patch transformers HybridCache compatibility: {e}", stacklevel=2) + + +def _patch_transformers_parallelism_config() -> None: + """ + Fix ParallelismConfig for transformers compatibility. + + Ensure that ``transformers.training_args`` always defines the symbol `ParallelismConfig` so that Python's + `typing.get_type_hints` can resolve annotations on `transformers.TrainingArguments` without raising a `NameError`. + + This is needed when running with ``accelerate<1.10.1``, where the module ``accelerate.parallelism_config`` did not + exist and therefore the type alias is not imported by Transformers. + + See upstream fix PR in transformers#40818. + + - Issue: transformers imports ParallelismConfig only if accelerate>=1.10.1 and raises NameError if + accelerate<1.10.1 + - Fixed in transformers: https://github.com/huggingface/transformers/pull/40818 (released in v4.57.0) + - This can be removed when TRL requires transformers>=4.57.0 or accelerate>=1.10.1 + """ + if _is_package_version_below("transformers", "4.57.0") and _is_package_version_below("accelerate", "1.10.1"): + try: + from typing import Any + + import transformers.training_args + + if not hasattr(transformers.training_args, "ParallelismConfig"): + transformers.training_args.ParallelismConfig = Any + except Exception as e: + warnings.warn(f"Failed to patch transformers ParallelismConfig compatibility: {e}", stacklevel=2) + + +# Apply vLLM patches +_patch_vllm_logging() + +# Apply transformers patches +_patch_transformers_hybrid_cache() +_patch_transformers_parallelism_config() # before creating HfArgumentParser diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/_lazy_module.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/_lazy_module.py new file mode 100644 index 0000000000000000000000000000000000000000..d030f00df1fdb0fc1f4c136393ea6ce06bb72669 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/_lazy_module.py @@ -0,0 +1,79 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import importlib +import os +from itertools import chain +from types import ModuleType +from typing import Any + + +class _LazyModule(ModuleType): + """ + Module class that surfaces all objects but only performs associated imports when the objects are requested. + """ + + # Very heavily inspired by optuna.integration._IntegrationModule + # https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py + def __init__(self, name, module_file, import_structure, module_spec=None, extra_objects=None): + super().__init__(name) + self._modules = set(import_structure.keys()) + self._class_to_module = {} + for key, values in import_structure.items(): + for value in values: + self._class_to_module[value] = key + # Needed for autocompletion in an IDE + self.__all__ = list(import_structure.keys()) + list(chain(*import_structure.values())) + self.__file__ = module_file + self.__spec__ = module_spec + self.__path__ = [os.path.dirname(module_file)] + self._objects = {} if extra_objects is None else extra_objects + self._name = name + self._import_structure = import_structure + + # Needed for autocompletion in an IDE + def __dir__(self): + result = super().__dir__() + # The elements of self.__all__ that are submodules may or may not be in the dir already, depending on whether + # they have been accessed or not. So we only add the elements of self.__all__ that are not already in the dir. + for attr in self.__all__: + if attr not in result: + result.append(attr) + return result + + def __getattr__(self, name: str) -> Any: + if name in self._objects: + return self._objects[name] + if name in self._modules: + value = self._get_module(name) + elif name in self._class_to_module.keys(): + module = self._get_module(self._class_to_module[name]) + value = getattr(module, name) + else: + raise AttributeError(f"module {self.__name__} has no attribute {name}") + + setattr(self, name, value) + return value + + def _get_module(self, module_name: str): + try: + return importlib.import_module("." + module_name, self.__name__) + except Exception as e: + raise RuntimeError( + f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its" + f" traceback):\n{e}" + ) from e + + def __reduce__(self): + return (self.__class__, (self._name, self.__file__, self._import_structure)) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/fsdp1.yaml b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/fsdp1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c01b0b567bc93bf87ec136ea975b3793d273a45c --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/fsdp1.yaml @@ -0,0 +1,28 @@ +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: FSDP +downcast_bf16: 'no' +enable_cpu_affinity: false +fsdp_config: + fsdp_activation_checkpointing: false + fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP + fsdp_backward_prefetch: BACKWARD_PRE + fsdp_cpu_ram_efficient_loading: true + fsdp_forward_prefetch: true + fsdp_offload_params: false + fsdp_reshard_after_forward: FULL_SHARD + fsdp_state_dict_type: FULL_STATE_DICT + fsdp_sync_module_states: true + fsdp_use_orig_params: true + fsdp_version: 1 +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/fsdp2.yaml b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/fsdp2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..af498f3eced9c2434b80113f2f22d40395e0ab8a --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/fsdp2.yaml @@ -0,0 +1,25 @@ +# Requires accelerate 1.7.0 or higher +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: FSDP +downcast_bf16: 'no' +enable_cpu_affinity: false +fsdp_config: + fsdp_activation_checkpointing: false + fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP + fsdp_cpu_ram_efficient_loading: true + fsdp_offload_params: false + fsdp_reshard_after_forward: true + fsdp_state_dict_type: FULL_STATE_DICT + fsdp_version: 2 +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/multi_gpu.yaml b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/multi_gpu.yaml new file mode 100644 index 0000000000000000000000000000000000000000..15dad9be3ba44f7c934e1ecab98a93cb83cbc79a --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/multi_gpu.yaml @@ -0,0 +1,16 @@ +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: MULTI_GPU +downcast_bf16: 'no' +gpu_ids: all +machine_rank: 0 +main_training_function: main +mixed_precision: 'bf16' +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/single_gpu.yaml b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/single_gpu.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ebd00a067118e56f3d63ab0f24827cfea21b24b9 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/single_gpu.yaml @@ -0,0 +1,16 @@ +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: "NO" +downcast_bf16: 'no' +gpu_ids: all +machine_rank: 0 +main_training_function: main +mixed_precision: 'bf16' +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/zero1.yaml b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/zero1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d5b5f782fb30f9fcbcc8fc58262f09eaf2e10368 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/zero1.yaml @@ -0,0 +1,20 @@ +compute_environment: LOCAL_MACHINE +debug: false +deepspeed_config: + deepspeed_multinode_launcher: standard + gradient_accumulation_steps: 1 + zero3_init_flag: false + zero_stage: 1 +distributed_type: DEEPSPEED +downcast_bf16: 'no' +machine_rank: 0 +main_training_function: main +mixed_precision: 'bf16' +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/zero2.yaml b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/zero2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..239b14ac3a9ae8de73122d1154bf0d71903dc15f --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/zero2.yaml @@ -0,0 +1,21 @@ +compute_environment: LOCAL_MACHINE +debug: false +deepspeed_config: + deepspeed_multinode_launcher: standard + offload_optimizer_device: none + offload_param_device: none + zero3_init_flag: false + zero_stage: 2 +distributed_type: DEEPSPEED +downcast_bf16: 'no' +machine_rank: 0 +main_training_function: main +mixed_precision: 'bf16' +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/zero3.yaml b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/zero3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b5a1201f8a2ee8706b63f0f80c664a1fc61a7d9d --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/accelerate_configs/zero3.yaml @@ -0,0 +1,22 @@ +compute_environment: LOCAL_MACHINE +debug: false +deepspeed_config: + deepspeed_multinode_launcher: standard + offload_optimizer_device: none + offload_param_device: none + zero3_init_flag: true + zero3_save_16bit_model: true + zero_stage: 3 +distributed_type: DEEPSPEED +downcast_bf16: 'no' +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_template_utils.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_template_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8b5d54d2bda0d19d77b1d717b8bb5181401047f0 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_template_utils.py @@ -0,0 +1,946 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import re +import warnings +from pathlib import Path +from typing import TypeVar + +from jinja2 import TemplateError +from transformers import AddedToken, AutoTokenizer, PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin + +from .data_utils import prepare_multimodal_messages + + +_CHAT_TEMPLATES_DIR = Path(__file__).parent / "chat_templates" + + +def has_generation_markers(chat_template: str) -> bool: + """ + Check whether the chat template defines `{% generation %}` markers, accounting for whitespace-trim variants such as + `{%- generation %}` and `{%- generation -%}`. + """ + return re.search(r"\{%-?\s*generation\s*-?%\}", chat_template) is not None + + +def clone_chat_template( + model: PreTrainedModel, + tokenizer: PreTrainedTokenizerBase, + source_tokenizer_path: str, + resize_to_multiple_of: int | None = 64, +) -> tuple[PreTrainedModel, PreTrainedTokenizerBase, list[int]]: + """ + Clones a chat template from a source tokenizer to the target tokenizer and updates the model accordingly. + + This function: + - Copies the chat template from a source tokenizer to the target tokenizer. + - Adds any new tokens from the source tokenizer to the target tokenizer. + - Sets and synchronizes the EOS token across the tokenizer and model. + - Resizes the model's token embeddings to match the new vocabulary size, optionally rounding it up to a multiple of + a specified value. In such cases, dummy tokens are added to the tokenizer to ensure the vocabulary size matches + the embedding dimensions. + + Args: + model ([`~transformers.PreTrainedModel`]): + Model to update. + tokenizer ([`~transformers.PreTrainedTokenizerBase`]): + Tokenizer to update. + source_tokenizer_path (`str`): + Path or identifier of the pretrained tokenizer to clone from. + resize_to_multiple_of (`int` or `None`, *optional*, defaults to `64`): + The embedding layer will be resized to the new vocabulary size. If this is not `None`, it will round up the + new vocabulary size to the nearest multiple of this value. + + Returns: + model ([`~transformers.PreTrainedModel`]): + Updated model with resized token embeddings and EOS token configured. + tokenizer ([`~transformers.PreTrainedTokenizerBase`]): + Updated tokenizer with the chat template and special tokens applied. + added_tokens (`list[int]`): + List of tokens that were added to the tokenizer from the source tokenizer. + + Example: + ```python + >>> from transformers import AutoModelForCausalLM, AutoTokenizer + >>> from trl import clone_chat_template + + >>> model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B") + >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-1B") + >>> model, tokenizer, added_tokens = clone_chat_template(model, tokenizer, "Qwen/Qwen3-0.6B") + ``` + """ + # Load the source tokenizer containing the desired chat template + tokenizer_source = AutoTokenizer.from_pretrained(source_tokenizer_path) + + # Copy the chat template from the source tokenizer + tokenizer.chat_template = tokenizer_source.get_chat_template() + + # Ensure all added tokens from the source are available in the target tokenizer + added_tokens = [ + token for token in tokenizer_source.added_tokens_decoder.values() if token.content not in tokenizer.vocab + ] + tokenizer.add_tokens(added_tokens) + + # Set the EOS token from the source tokenizer (important for generation) + tokenizer.eos_token = tokenizer_source.eos_token + model.config.eos_token_id = tokenizer.eos_token_id + if model.can_generate(): # Non-generative models (e.g. SequenceClassification) may not have a generation_config + model.generation_config.eos_token_id = tokenizer.eos_token_id + + # Resize model embeddings to include any new tokens, optionally rounding up to a multiple + model.resize_token_embeddings( + # After studying many tokenizers, we found that len(tokenizer.vocab) is the most reliable way to get the vocab + # size. Avoid using tokenizer.vocab_size or tokenizer.vocab_size + len(tokenizer.added_tokens_encoder), + # as handling of special and added tokens varies across tokenizers. + new_num_tokens=len(tokenizer.vocab), + pad_to_multiple_of=resize_to_multiple_of if resize_to_multiple_of is not None else None, + ) + + # After resizing, the embedding matrix size may exceed the vocabulary size. Add dummy tokens to the tokenizer to + # ensure vocabulary size matches the embedding matrix dimensions. + idx = 0 + while model.vocab_size > len(tokenizer.vocab): + dummy_token = AddedToken(f"") + is_added = tokenizer.add_tokens(dummy_token) + idx += 1 + if is_added == 1: + added_tokens.append(dummy_token) + + # Verify that vocabulary size now matches embedding dimensions + if len(tokenizer.vocab) != model.vocab_size: + raise RuntimeError( + f"Vocabulary size mismatch after resizing: tokenizer vocab size is {len(tokenizer.vocab)}, but model " + f"embedding size is {model.vocab_size}. This indicates an internal error in the token alignment process." + ) + added_tokens = [token.content for token in added_tokens] + added_tokens = tokenizer.convert_tokens_to_ids(added_tokens) + return model, tokenizer, added_tokens + + +glm4moe_schema = { + "x-regex": r"^(?:\n?\n?(?:(?P.*?\S.*?)\n?|[\s]*)\s*)?(?P(?:(?!)[\s\S])*?)(?:\n(?=))?(?=(?:|$))(?P(?:(?:(?!)[\s\S])+\s*)+)?$", + "type": "object", + "properties": { + "role": {"const": "assistant"}, + "content": {"type": "string"}, + "reasoning_content": {"type": "string"}, + "tool_calls": { + "type": "array", + "x-regex-iterator": r"\s*(.+?)\s*", + "items": { + "type": "object", + "properties": { + "type": {"const": "function"}, + "function": { + "type": "object", + "properties": { + "name": {"type": "string", "x-regex": r"^(\S+)"}, + "arguments": { + "type": "object", + "x-regex-key-value": r"(?P[^<]+)\s*\n(?P.*?)", + "default": {}, + "additionalProperties": { + "x-parser": "json", + "x-parser-args": {"allow_non_json": True}, + }, + }, + }, + }, + }, + }, + }, + }, +} + +gptoss_schema = { + # Normalize final content to analysis format so both map to the same "content" group. + "x-regex-substitutions": [ + [r"<\|channel\|>final<\|message\|>(.*?)<\|return\|>", r"<|channel|>analysis<|message|>\1<|end|>"], + ], + "x-regex": r"^(?:<\|channel\|>analysis<\|message\|>(?P.*?)<\|end\|>(?:<\|start\|>assistant)?)?\s*(?Pto=functions\.\S+<\|channel\|>commentary json<\|message\|>.*?<\|call\|>)?$", + "type": "object", + "properties": { + "role": {"const": "assistant"}, + "content": {"type": "string"}, + "tool_calls": { + "type": "array", + "x-regex-iterator": r"(to=functions\.\S+<\|channel\|>commentary json<\|message\|>.*?<\|call\|>)", + "items": { + # Convert "to=functions.NAME<|channel|>commentary json<|message|>ARGS<|call|>" + # into '{"name": "NAME", "arguments": ARGS}' so it can be parsed as JSON. + "x-regex-substitutions": [ + [ + r"to=functions\.(\S+)<\|channel\|>commentary json<\|message\|>(.*?)<\|call\|>", + r'{"name": "\1", "arguments": \2}', + ], + ], + "x-parser": "json", + "x-parser-args": {"transform": "{type: 'function', function: @}"}, + "type": "object", + "properties": { + "type": {"const": "function"}, + "function": { + "type": "object", + "properties": { + "name": {"type": "string"}, + "arguments": { + "type": "object", + "additionalProperties": {}, + }, + }, + }, + }, + }, + }, + }, +} + +# Adapted and corrected versions of the schemas from: +# https://github.com/huggingface/transformers/blob/main/tests/utils/test_chat_parsing_utils.py +qwen3_schema = { + "x-regex": r"^(?:\n?(?:(?P.*?\S.*?)\n?|[\s]*)\s*)?(?P(?:(?!)[\s\S])*?)(?:\n(?=))?(?=(?:|<\|im_end\|>|$))(?P(?:(?:(?!)[\s\S])+\s*)+)?\s*(?:<\|im_end\|>|$)", + "type": "object", + "properties": { + "role": {"const": "assistant"}, + "content": {"type": "string"}, + "reasoning_content": {"type": "string"}, + "tool_calls": { + "type": "array", + "x-regex-iterator": r"\s*(.+?)\s*", + "items": { + "x-parser": "json", + "x-parser-args": {"transform": "{type: 'function', function: @}"}, + "type": "object", + "properties": { + "type": {"const": "function"}, + "function": { + "type": "object", + "properties": { + "name": {"type": "string"}, + "arguments": { + "type": "object", + "additionalProperties": {}, + }, + }, + }, + }, + }, + }, + }, +} + +llama3_schema = { + # Llama 3.1 / 3.2 render a tool call as a single bare JSON object using the key "parameters" instead of + # "arguments": `{"name": "", "parameters": }<|eot_id|>`. There is no surrounding marker, no + # support for content alongside a tool call, and at most one tool call per assistant turn (the template raises + # otherwise). Either we match a tool call (capturing the JSON) or we treat the response as plain content. + "x-regex": r'^(?:(?P\{"name":\s*".+?",\s*"parameters":\s*.+\})|(?P.*?))(?:<\|eot_id\|>|$)', + "type": "object", + "properties": { + "role": {"const": "assistant"}, + "content": {"type": "string"}, + "tool_calls": { + "type": "array", + "x-regex-iterator": r'(\{"name":\s*".+?",\s*"parameters":\s*.+\})', + "items": { + # Rewrite "parameters" → "arguments" so the JSON parses into the standard tool-call shape. Anchored + # on the leading `{"name": "..."` so a stray `"parameters"` inside argument values is not touched. + "x-regex-substitutions": [ + [r'^(\{"name":\s*"[^"]+",\s*)"parameters":', r'\1"arguments":'], + ], + "x-parser": "json", + "x-parser-args": {"transform": "{type: 'function', function: @}"}, + "type": "object", + "properties": { + "type": {"const": "function"}, + "function": { + "type": "object", + "properties": { + "name": {"type": "string"}, + "arguments": { + "type": "object", + "additionalProperties": {}, + }, + }, + }, + }, + }, + }, + }, +} + +qwen3_5_schema = { + "x-regex": r"^(?:(?:\n?)?(?:(?P.*?\S.*?)\n?|[\s]*)\s*)?(?P(?:(?!)[\s\S])*?)(?:\n+(?=))?(?=(?:|<\|im_end\|>|$))(?P(?:(?:(?!)[\s\S])+\s*)+)?\s*(?:<\|im_end\|>|$)", + "type": "object", + "properties": { + "role": {"const": "assistant"}, + "content": {"type": "string"}, + "reasoning_content": {"type": "string"}, + "tool_calls": { + "type": "array", + "x-regex-iterator": r"\s*(.+?)\s*", + "items": { + "type": "object", + "properties": { + "type": {"const": "function"}, + "function": { + "type": "object", + "properties": { + "name": {"type": "string", "x-regex": r"]+)>"}, + "arguments": { + "type": "object", + "x-regex-key-value": r"[^>\n]+)>\n(?P.*?)\n", + "default": {}, + "additionalProperties": { + "x-parser": "json", + "x-parser-args": {"allow_non_json": True}, + }, + }, + }, + }, + }, + }, + }, + }, +} + + +cohere_chat_template = (_CHAT_TEMPLATES_DIR / "cohere.jinja").read_text(encoding="utf-8") + +cohere2_chat_template = (_CHAT_TEMPLATES_DIR / "cohere2.jinja").read_text(encoding="utf-8") + +deepseekv3_chat_template = (_CHAT_TEMPLATES_DIR / "deepseekv3.jinja").read_text(encoding="utf-8") + +gemma_chat_template = (_CHAT_TEMPLATES_DIR / "gemma.jinja").read_text(encoding="utf-8") + +gemma3_chat_template = (_CHAT_TEMPLATES_DIR / "gemma3.jinja").read_text(encoding="utf-8") + +glm4moe_chat_template = (_CHAT_TEMPLATES_DIR / "glm4moe.jinja").read_text(encoding="utf-8") + +gptoss_chat_template = (_CHAT_TEMPLATES_DIR / "gptoss.jinja").read_text(encoding="utf-8") + +idefics3_chat_template = (_CHAT_TEMPLATES_DIR / "idefics3.jinja").read_text(encoding="utf-8") + +llama3_chat_template = (_CHAT_TEMPLATES_DIR / "llama3.jinja").read_text(encoding="utf-8") + +llama3_1_chat_template = (_CHAT_TEMPLATES_DIR / "llama3_1.jinja").read_text(encoding="utf-8") + +llama3_2_chat_template = (_CHAT_TEMPLATES_DIR / "llama3_2.jinja").read_text(encoding="utf-8") + +llava_next_chat_template = (_CHAT_TEMPLATES_DIR / "llava_next.jinja").read_text(encoding="utf-8") + +nemotron_3_nano_chat_template = (_CHAT_TEMPLATES_DIR / "nemotron_3_nano.jinja").read_text(encoding="utf-8") + +nemotron_3_super_chat_template = (_CHAT_TEMPLATES_DIR / "nemotron_3_super.jinja").read_text(encoding="utf-8") + +nemotron_3_ultra_chat_template = (_CHAT_TEMPLATES_DIR / "nemotron_3_ultra.jinja").read_text(encoding="utf-8") + +phi3_chat_template = (_CHAT_TEMPLATES_DIR / "phi3.jinja").read_text(encoding="utf-8") + +phi3_5_chat_template = (_CHAT_TEMPLATES_DIR / "phi3_5.jinja").read_text(encoding="utf-8") + +qwen2_5_chat_template = (_CHAT_TEMPLATES_DIR / "qwen2_5.jinja").read_text(encoding="utf-8") + +# Also matches Qwen2-VL, which ships a byte-identical chat template. +qwen2_5_vl_chat_template = (_CHAT_TEMPLATES_DIR / "qwen2_5_vl.jinja").read_text(encoding="utf-8") + +qwen3_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3.jinja").read_text(encoding="utf-8") + +qwen3_instruct_2507_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_instruct_2507.jinja").read_text(encoding="utf-8") + +qwen3_vl_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_vl.jinja").read_text(encoding="utf-8") + +qwen3_5_nothink_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_5_nothink.jinja").read_text(encoding="utf-8") + +qwen3_5_think_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_5_think.jinja").read_text(encoding="utf-8") + +qwen3_6_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_6.jinja").read_text(encoding="utf-8") + + +ProcessingClassT = TypeVar("ProcessingClassT", PreTrainedTokenizerBase, ProcessorMixin) + + +def add_response_schema(processing_class: ProcessingClassT) -> ProcessingClassT: + r""" + Adds the appropriate response schema to the given tokenizer based on its chat template. + + At the time of initial implementation, most tokenizers do not have built-in support for response schemas. While + waiting for broader adoption, we provide this utility function to manually set the response schema for known chat + templates. + + When given a VLM processor, the schema is set on the inner tokenizer, since `parse_response` is a tokenizer method + and reads `self.response_schema` from the tokenizer instance. + + Args: + processing_class (`PreTrainedTokenizerBase` or `ProcessorMixin`): + Tokenizer or VLM processor to which the response schema will be added. + + Returns: + `PreTrainedTokenizerBase` or `ProcessorMixin`: + The same object that was passed in, with the response schema set on the underlying tokenizer. + + Examples: + + ```python + >>> from trl.chat_template_utils import add_response_schema + >>> from transformers import AutoTokenizer + + >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B") + >>> tokenizer = add_response_schema(tokenizer) + >>> assistant_text = '\n{"name": "multiply", "arguments": {"a": 3, "b": 4}}\n<|im_end|>' + >>> tokenizer.parse_response(assistant_text) + {'role': 'assistant', 'content': '', 'tool_calls': [{'type': 'function', 'function': {'name': 'multiply', 'arguments': {'a': 3, 'b': 4}}}]} + ``` + """ + # For VLM processors, set the schema on the inner tokenizer (where `parse_response` reads it from). + # Match against the top-level chat_template, since that's what was used historically and processors + # may carry their own VLM-specific template separate from the inner tokenizer's. + chat_template = processing_class.chat_template + if isinstance(processing_class, ProcessorMixin): + tokenizer = processing_class.tokenizer + else: + tokenizer = processing_class + if chat_template == glm4moe_chat_template: + tokenizer.response_schema = glm4moe_schema + elif chat_template == gptoss_chat_template: + tokenizer.response_schema = gptoss_schema + elif chat_template in [llama3_1_chat_template, llama3_2_chat_template]: + tokenizer.response_schema = llama3_schema + elif chat_template in [ + qwen2_5_chat_template, + qwen3_chat_template, + qwen3_instruct_2507_chat_template, + qwen3_vl_chat_template, + ]: + tokenizer.response_schema = qwen3_schema + elif chat_template in [ + qwen3_5_nothink_chat_template, + qwen3_5_think_chat_template, + qwen3_6_chat_template, + ]: + tokenizer.response_schema = qwen3_5_schema + elif chat_template in [ + nemotron_3_nano_chat_template, + nemotron_3_super_chat_template, + nemotron_3_ultra_chat_template, + ]: + # Nemotron 3 renders tool calls in the same Hermes-style / format as Qwen3.5. + tokenizer.response_schema = qwen3_5_schema + else: + raise ValueError( + "Unrecognized chat template, failed to add response schema. Please manually set the response schema on " + "the tokenizer or processor. See the Transformers " + "[docs](https://huggingface.co/docs/transformers/main/en/chat_response_parsing#response-parsing) for more " + "details on response parsing." + ) + return processing_class + + +def supports_tool_calling(processing_class) -> bool: + """ + Check if the processing class's chat template can render a full tool-calling conversation. + + This tests that (1) the template doesn't error when rendering a conversation with ``user → assistant (with + tool_calls) → tool`` roles, and (2) every part of the tool-calling exchange — the assistant's tool call name, its + arguments, and the tool message content — actually appears in the rendered output. Some templates silently swallow + `tool_calls` (e.g. the basic Llama 3 template, which only reads `message['content']`) or tool messages (e.g. + Cohere2, Phi3); both cases must be rejected. + + For VLMs (processors), the messages are converted to multimodal format via + [`~trl.data_utils.prepare_multimodal_messages`] before rendering. + + Args: + processing_class (`PreTrainedTokenizerBase` or `ProcessorMixin`): + Tokenizer or processor instance to check. + + Returns: + `bool`: + `True` if the chat template supports tool-calling conversations, `False` otherwise. + """ + if processing_class.chat_template is None: + return False + + is_vlm = isinstance(processing_class, ProcessorMixin) + # Distinct sentinels so we can tell which part of the exchange a template drops. + _name_sentinel = "tool_name_a8f3e2b1" + _arg_key_sentinel = "tool_arg_key_b9d4f5c2" + _arg_val_sentinel = "tool_arg_val_d6e7a9f3" + _content_sentinel = "tool_content_c4f9a8e2" + tool_calls = [ + { + "type": "function", + "function": {"name": _name_sentinel, "arguments": {_arg_key_sentinel: _arg_val_sentinel}}, + } + ] + messages = [ + {"role": "user", "content": "hi"}, + {"role": "assistant", "content": "", "tool_calls": tool_calls}, + {"role": "tool", "name": _name_sentinel, "content": _content_sentinel}, + ] + # VLMs expect content as [{"type": "text", "text": "..."}] instead of plain strings + if is_vlm: + messages = prepare_multimodal_messages(messages) + + try: + rendered = processing_class.apply_chat_template(messages, tokenize=False) + except TemplateError: + # TemplateError: template rejects the role sequence (Cohere, FalconMamba, Gemma, Gemma2, Gemma3) + # UndefinedError (subclass): template indexes into content as a list for all roles, including tool + # (Idefics2, Idefics3, LlavaNext, SmolVLM) + return False + except TypeError: + # Best-effort fallback for templates that reject dict args (e.g. DeepSeek-V3). This is a chat template + # bug (see transformers#45419), and the training chat template fixes it to avoid blocking users. + tool_calls[0]["function"]["arguments"] = f'{{"{_arg_key_sentinel}": "{_arg_val_sentinel}"}}' + try: + rendered = processing_class.apply_chat_template(messages, tokenize=False) + except TemplateError: + return False + # All four sentinels must survive: the tool name and arguments (assistant tool_calls) AND the tool message + # content. Templates that silently drop either side (basic Llama 3 drops tool_calls; Cohere2/Phi3 drop tool + # messages) will fail this check. + return all(s in rendered for s in (_name_sentinel, _arg_key_sentinel, _arg_val_sentinel, _content_sentinel)) + + +def is_chat_template_prefix_preserving(processing_class: PreTrainedTokenizerBase | ProcessorMixin) -> bool: + """ + Check whether the chat template preserves prefixes when applied. + + A prefix-preserving chat template renders earlier messages identically regardless of what messages follow. This + property is required by `_get_tool_suffix_ids`, which extracts tool response formatting tokens by comparing + tokenizations with and without tool messages appended. + + Args: + processing_class (`PreTrainedTokenizerBase` or `ProcessorMixin`): + Tokenizer or processor instance to check. + + Returns: + `bool`: + `True` if the chat template preserves prefixes, `False` otherwise. + """ + # Use the same dummy messages as _get_tool_suffix_ids to test the exact property it relies on. + dummy_tool_calls = [{"type": "function", "function": {"name": "dummy", "arguments": {}}}] + messages1 = [ + {"role": "user", "content": "dummy"}, + {"role": "assistant", "content": "", "tool_calls": dummy_tool_calls}, + ] + messages2 = [ + {"role": "user", "content": "dummy"}, + {"role": "assistant", "content": "", "tool_calls": dummy_tool_calls}, + {"role": "tool", "name": "dummy", "content": "dummy"}, + ] + # VLM processors expect structured list-of-blocks content, and image-token expansion only kicks in when an image + # is actually present, so include a dummy image to exercise the real code path. + is_vlm = isinstance(processing_class, ProcessorMixin) + if is_vlm: + from PIL import Image + + dummy_image = Image.new("RGB", (8, 8)) + messages1 = prepare_multimodal_messages(messages1, images=[dummy_image]) + messages2 = prepare_multimodal_messages(messages2, images=[dummy_image]) + + try: + ids1 = processing_class.apply_chat_template(messages1, tokenize=True, return_dict=False) + ids2 = processing_class.apply_chat_template( + messages2, tokenize=True, return_dict=False, add_generation_prompt=True + ) + except TypeError: + # Best-effort fallback for templates that reject dict args (e.g. DeepSeek-V3). This is a chat template + # bug (see transformers#45419), and the training chat template fixes it to avoid blocking users. + dummy_tool_calls = [{"type": "function", "function": {"name": "dummy", "arguments": "{}"}}] + messages1[1]["tool_calls"] = dummy_tool_calls + messages2[1]["tool_calls"] = dummy_tool_calls + ids1 = processing_class.apply_chat_template(messages1, tokenize=True, return_dict=False) + ids2 = processing_class.apply_chat_template( + messages2, tokenize=True, return_dict=False, add_generation_prompt=True + ) + + # VLM processors return batched output (list of lists), unbatch for single conversation + if is_vlm: + ids1 = ids1[0] + ids2 = ids2[0] + + return ids2[: len(ids1)] == ids1 + + +def is_chat_template_stop_token_trained( + processing_class: PreTrainedTokenizerBase | ProcessorMixin, chat_template: str | None = None +) -> bool: + """ + Check whether the chat template includes an assistant turn's end-of-turn token in the loss mask. + + Prefix preservation guarantees that earlier turns render identically, but not that the token the model must emit to + *end* its turn is part of the loss. Some templates attribute an assistant turn's end-of-turn token to the message + that follows it, so when masking with `return_assistant_tokens_mask=True` that token falls outside the assistant + span and the model is never trained to stop. This renders an assistant turn followed by a user message and checks + that the assistant's masked span ends on an end-of-turn token rather than on content. + + The template must define `{% generation %}` / `{% endgeneration %}` markers (see [`get_training_chat_template`]), + otherwise the assistant mask is empty and this returns `False`. + + Args: + processing_class (`PreTrainedTokenizerBase` or `ProcessorMixin`): + Tokenizer or processor instance to check. + chat_template (`str`, *optional*): + Chat template to check. Defaults to the one attached to `processing_class`. + + Returns: + `bool`: + `True` if the assistant turn's end-of-turn token is included in the loss mask, `False` otherwise. + """ + # The assistant turn is followed by a user message because some templates never terminate the final assistant + # turn; the boundary with the next message is where the end-of-turn token must be attributed. + messages = [ + {"role": "user", "content": "dummy"}, + {"role": "assistant", "content": "dummy"}, + {"role": "user", "content": "dummy"}, + ] + is_vlm = isinstance(processing_class, ProcessorMixin) + if is_vlm: + # Probe without images: assistant masks are computed before multimodal token expansion and not re-aligned + # afterwards, so any image would zero or shift the mask regardless of what the template attributes. + for message in messages: + message["content"] = [{"type": "text", "text": message["content"]}] + + try: + output = processing_class.apply_chat_template( + messages, + tokenize=True, + return_dict=True, + return_assistant_tokens_mask=True, + chat_template=chat_template, + ) + except (TemplateError, TypeError, ValueError): + return False + + input_ids = output["input_ids"] + assistant_masks = output["assistant_masks"] + if is_vlm: + input_ids = input_ids[0] + assistant_masks = assistant_masks[0] + + # The model stops by emitting an end-of-turn token, which is part of the added vocabulary rather than produced by + # the base tokenizer's merges. Ignoring trailing whitespace, the last masked token must be that terminator; if it + # is plain content, the end-of-turn token was attributed to the following message and is never trained. + tokenizer = processing_class.tokenizer if is_vlm else processing_class + added_ids = set(tokenizer.get_added_vocab().values()) + masked_ids = [token_id for token_id, masked in zip(input_ids, assistant_masks, strict=False) if masked] + for token_id in reversed(masked_ids): + if tokenizer.decode([token_id]).strip() == "": + continue + return token_id in added_ids + return False + + +cohere_training_chat_template = (_CHAT_TEMPLATES_DIR / "cohere_training.jinja").read_text(encoding="utf-8") + +cohere2_training_chat_template = (_CHAT_TEMPLATES_DIR / "cohere2_training.jinja").read_text(encoding="utf-8") + +deepseekv3_training_chat_template = (_CHAT_TEMPLATES_DIR / "deepseekv3_training.jinja").read_text(encoding="utf-8") + +gemma_training_chat_template = (_CHAT_TEMPLATES_DIR / "gemma_training.jinja").read_text(encoding="utf-8") + +gemma3_training_chat_template = (_CHAT_TEMPLATES_DIR / "gemma3_training.jinja").read_text(encoding="utf-8") + +glm4moe_training_chat_template = (_CHAT_TEMPLATES_DIR / "glm4moe_training.jinja").read_text(encoding="utf-8") + +gptoss_training_chat_template = (_CHAT_TEMPLATES_DIR / "gptoss_training.jinja").read_text(encoding="utf-8") + +idefics3_training_chat_template = (_CHAT_TEMPLATES_DIR / "idefics3_training.jinja").read_text(encoding="utf-8") + +llama3_training_chat_template = (_CHAT_TEMPLATES_DIR / "llama3_training.jinja").read_text(encoding="utf-8") + +llava_next_training_chat_template = (_CHAT_TEMPLATES_DIR / "llava_next_training.jinja").read_text(encoding="utf-8") + +nemotron_3_nano_training_chat_template = (_CHAT_TEMPLATES_DIR / "nemotron_3_nano_training.jinja").read_text( + encoding="utf-8" +) + +nemotron_3_super_training_chat_template = (_CHAT_TEMPLATES_DIR / "nemotron_3_super_training.jinja").read_text( + encoding="utf-8" +) + +nemotron_3_ultra_training_chat_template = (_CHAT_TEMPLATES_DIR / "nemotron_3_ultra_training.jinja").read_text( + encoding="utf-8" +) + +phi3_training_chat_template = (_CHAT_TEMPLATES_DIR / "phi3_training.jinja").read_text(encoding="utf-8") + +phi3_5_training_chat_template = (_CHAT_TEMPLATES_DIR / "phi3_5_training.jinja").read_text(encoding="utf-8") + +qwen2_5_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen2_5_training.jinja").read_text(encoding="utf-8") + +qwen2_5_vl_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen2_5_vl_training.jinja").read_text(encoding="utf-8") + +qwen3_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_training.jinja").read_text(encoding="utf-8") + +qwen3_instruct_2507_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_instruct_2507_training.jinja").read_text( + encoding="utf-8" +) + +qwen3_vl_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_vl_training.jinja").read_text(encoding="utf-8") + +qwen3_5_nothink_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_5_nothink_training.jinja").read_text( + encoding="utf-8" +) + +qwen3_5_think_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_5_think_training.jinja").read_text( + encoding="utf-8" +) + +qwen3_6_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_6_training.jinja").read_text(encoding="utf-8") + + +def get_training_chat_template( + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + tokenizer: PreTrainedTokenizerBase | None = None, +) -> str | None: + r""" + Get a training-compatible chat template, if needed. + + Returns a patched chat template that is prefix-preserving and includes `{%% generation %%}` / `{%% endgeneration + %%}` markers for assistant-only loss masking. Returns `None` if the template already satisfies both requirements. + Currently Cohere, Cohere 2, DeepSeek-V3, Gemma, Gemma 2, Gemma 3, GLM-4-MoE, GPT-OSS, Idefics3, LLaMA 3, Phi-3, + Phi-3.5, Qwen2-VL, Qwen2.5, Qwen2.5-VL, Qwen3 (including the Instruct-2507 variant), Qwen3-VL, Qwen3.5, and Qwen3.6 + are supported. + + Args: + processing_class (`PreTrainedTokenizerBase` or `ProcessorMixin`): + Tokenizer or processor instance to check. + + Returns: + `str` or `None`: + Training-compatible chat template, or `None` if no patching is needed. + + Example: + + ```python + >>> from trl.chat_template_utils import get_training_chat_template + >>> from transformers import AutoTokenizer + + >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B") + >>> messages1 = [ + ... {"role": "user", "content": "What is 2 * 3?"}, + ... { + ... "role": "assistant", + ... "content": "", + ... "tool_calls": [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 2, "b": 3}}}], + ... }, + ... ] + >>> messages2 = messages1 + [ + ... {"role": "tool", "name": "multiply", "content": "6"}, + ... ] + >>> tokenizer.apply_chat_template(messages1, tokenize=False) + '<|im_start|>user\nWhat is 2 * 3?<|im_end|>\n<|im_start|>assistant\n\n\n\n\n\n{"name": "multiply", "arguments": {"a": 2, "b": 3}}\n<|im_end|>\n' + + >>> tokenizer.apply_chat_template(messages2, tokenize=False, add_generation_prompt=True) + '<|im_start|>user\nWhat is 2 * 3?<|im_end|>\n<|im_start|>assistant\n\n{"name": "multiply", "arguments": {"a": 2, "b": 3}}\n<|im_end|>\n<|im_start|>user\n\n6\n<|im_end|>\n<|im_start|>assistant\n' + + >>> # ^ think tags missing + >>> chat_template = get_training_chat_template(tokenizer) + >>> tokenizer.apply_chat_template(messages1, tokenize=False, chat_template=chat_template) + '<|im_start|>user\nWhat is 2 * 3?<|im_end|>\n<|im_start|>assistant\n\n\n\n\n\n{"name": "multiply", "arguments": {"a": 2, "b": 3}}\n<|im_end|>\n' + + >>> tokenizer.apply_chat_template( + ... messages2, tokenize=False, add_generation_prompt=True, chat_template=chat_template + ... ) + '<|im_start|>user\nWhat is 2 * 3?<|im_end|>\n<|im_start|>assistant\n\n\n\n\n\n{"name": "multiply", "arguments": {"a": 2, "b": 3}}\n<|im_end|>\n<|im_start|>user\n\n6\n<|im_end|>\n<|im_start|>assistant\n' + ``` + """ + if tokenizer is not None: + if processing_class is not None: + raise TypeError( + "Pass only `processing_class`; `tokenizer` is a deprecated alias for backward compatibility." + ) + warnings.warn( + "The `tokenizer` argument of `get_training_chat_template` is deprecated and will be removed in TRL 2.0. " + "Use `processing_class` instead.", + FutureWarning, + stacklevel=2, + ) + processing_class = tokenizer + if processing_class is None: + raise TypeError("get_training_chat_template() missing required argument: 'processing_class'") + + # First check if patching is needed. Prefix-preservation only matters when the template actually supports tools + # (the check itself renders a tool message), so skip it otherwise. + prefix_ok = not supports_tool_calling(processing_class) or is_chat_template_prefix_preserving(processing_class) + if prefix_ok and has_generation_markers(processing_class.chat_template): + return None # No patching needed + + if processing_class.chat_template == cohere_chat_template: + return cohere_training_chat_template + + if processing_class.chat_template == cohere2_chat_template: + return cohere2_training_chat_template + + if processing_class.chat_template == deepseekv3_chat_template: + return deepseekv3_training_chat_template + + if processing_class.chat_template == gemma_chat_template: + return gemma_training_chat_template + + if processing_class.chat_template == gemma3_chat_template: + return gemma3_training_chat_template + + if processing_class.chat_template == glm4moe_chat_template: + return glm4moe_training_chat_template + + if processing_class.chat_template == gptoss_chat_template: + return gptoss_training_chat_template + + if processing_class.chat_template == idefics3_chat_template: + return idefics3_training_chat_template + + if processing_class.chat_template == llama3_chat_template: + return llama3_training_chat_template + + if processing_class.chat_template == llava_next_chat_template: + return llava_next_training_chat_template + + if processing_class.chat_template == nemotron_3_nano_chat_template: + return nemotron_3_nano_training_chat_template + + if processing_class.chat_template == nemotron_3_super_chat_template: + return nemotron_3_super_training_chat_template + + if processing_class.chat_template == nemotron_3_ultra_chat_template: + return nemotron_3_ultra_training_chat_template + + if processing_class.chat_template == phi3_chat_template: + return phi3_training_chat_template + + if processing_class.chat_template == phi3_5_chat_template: + return phi3_5_training_chat_template + + if processing_class.chat_template == qwen2_5_chat_template: + return qwen2_5_training_chat_template + + if processing_class.chat_template == qwen2_5_vl_chat_template: + return qwen2_5_vl_training_chat_template + + if processing_class.chat_template == qwen3_chat_template: + return qwen3_training_chat_template + + if processing_class.chat_template == qwen3_instruct_2507_chat_template: + return qwen3_instruct_2507_training_chat_template + + if processing_class.chat_template == qwen3_vl_chat_template: + return qwen3_vl_training_chat_template + + if processing_class.chat_template == qwen3_5_nothink_chat_template: + return qwen3_5_nothink_training_chat_template + + if processing_class.chat_template == qwen3_5_think_chat_template: + return qwen3_5_think_training_chat_template + + if processing_class.chat_template == qwen3_6_chat_template: + return qwen3_6_training_chat_template + + raise ValueError( + "The chat template is not training-compatible (missing prefix-preservation or `{% generation %}` markers) " + "and patching is not supported for this template. Please manually modify the chat template for training." + ) + + +def _validate_tool_calls(tool_calls: list | None) -> None: + """ + Validate tool_calls to ensure all required fields exist with valid values. + + Raises ValueError when the model generates malformed tool calls (e.g., missing 'arguments' field) that are + partially parsed. + + Args: + tool_calls: List of tool call dictionaries, or None. + """ + if tool_calls is None: + return None + if not isinstance(tool_calls, list): + raise ValueError("tool_calls must be a list or None.") + + for idx, tool_call in enumerate(tool_calls): + if not isinstance(tool_call, dict): + raise ValueError(f"tool_calls[{idx}] must be a dict.") + + # Handle nested function structure: {"type": "function", "function": {"name": ..., "arguments": ...}} + if "function" in tool_call: + func = tool_call["function"] + if not isinstance(func, dict): + raise ValueError(f"tool_calls[{idx}]['function'] must be a dict.") + if not isinstance(func.get("name"), str): + raise ValueError(f"tool_calls[{idx}]['function']['name'] must be a string.") + # Some templates (e.g. Qwen3.5) omit arguments for valid no-arg calls; normalize to {}. + if "arguments" not in func or func["arguments"] is None: + func["arguments"] = {} + else: + # Handle flat structure: {"name": ..., "arguments": ...} + if not isinstance(tool_call.get("name"), str): + raise ValueError(f"tool_calls[{idx}]['name'] must be a string.") + # Some templates (e.g. Qwen3.5) omit arguments for valid no-arg calls; normalize to {}. + if "arguments" not in tool_call or tool_call["arguments"] is None: + tool_call["arguments"] = {} + + +def parse_response(tokenizer: PreTrainedTokenizerBase, ids: list[int]) -> dict: + r""" + Parse a token sequence into structured response dictionaries with fallback handling. + + Attempts to parse the sequence using `tokenizer.parse_response()`. If parsing fails (e.g., due to malformed tool + calls like `{"type":"function"`), falls back to decoding as plain text. + + Also removes incorrectly appended EOS tokens from tool call content when present, and validates tool_calls to + ensure all required fields exist. + + Args: + tokenizer (`PreTrainedTokenizerBase`): + Tokenizer with a `parse_response()` method. + ids (`list[int]`): + List of token sequences. + + Returns: + `dict`: + Response dictionary. + + Example: + ```python + >>> from trl.chat_template_utils import parse_response, add_response_schema + >>> from transformers import AutoTokenizer + + >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B") + >>> tokenizer = add_response_schema(tokenizer) # temporary until built-in support + >>> text = '\n{"name": "multiply", "arguments": {"a": 3, "b": 4}}\n<|im_end|>' + >>> ids = tokenizer(text)["input_ids"] + >>> parse_response(tokenizer, ids) + {'role': 'assistant', 'content': '', 'tool_calls': [{'type': 'function', 'function': {'name': 'multiply', 'arguments': {'a': 3, 'b': 4}}}]} + ``` + """ + try: + parsed = tokenizer.parse_response(ids) + if parsed is None: # this can happen if the response is heavily truncated and even the content is lost + raise ValueError("parse_response returned None") + # Hotfix: remove incorrectly appended EOS token from tool calls + # See https://github.com/huggingface/transformers/issues/42249 + if isinstance(parsed.get("content"), str): + parsed["content"] = parsed["content"].removesuffix(tokenizer.eos_token) + # Normalize: ensure content is always a string (some models omit it or set it to None) + if not parsed.get("content"): + parsed["content"] = "" + # Validate tool_calls to prevent Jinja2 Undefined errors when fields are missing + if "tool_calls" in parsed: + _validate_tool_calls(parsed["tool_calls"]) + except (ValueError, TypeError): + # Fallback: decode as plain text if parsing fails. This happens if the model outputs malformed tool calls. + content = tokenizer.decode(ids, skip_special_tokens=True) + parsed = {"role": "assistant", "content": content} + return parsed diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/README.md b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/README.md new file mode 100644 index 0000000000000000000000000000000000000000..685284a00096042d5fe6c573b765416d9a5a95e6 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/README.md @@ -0,0 +1,264 @@ +# Chat Templates + +Jinja2 chat templates stored here serve two purposes: + +1. **Identity comparison**: detecting which model is being used (by comparing `tokenizer.chat_template` against known templates) to add the appropriate response schema (`add_response_schema`) or swap in a training template (`get_training_chat_template`). +2. **Training patches**: modified templates that fix training-specific issues (prefix-preservation for GRPO, `{% generation %}` markers for SFT assistant-only loss). + +**Why prefix-preserving?** The GRPO tool call loop extracts tool response formatting tokens by comparing tokenizations with and without tool messages appended (`_get_tool_suffix_ids`). This requires the chat template to be *prefix-preserving*: appending messages must not change how earlier messages are rendered. + +**Why generation-tagged?** SFT with `assistant_only_loss=True` requires the chat template to include `{% generation %}` / `{% endgeneration %}` markers around assistant output, so `return_assistant_tokens_mask=True` can produce correct masks. Most model templates don't include these markers natively. + +## Original templates + +Used for identity comparison only. + +### `cohere.jinja` + +Original Cohere Command chat template (as shipped by `CohereForAI/c4ai-command-r-v01` and related checkpoints). + +### `cohere2.jinja` + +Original Cohere2 chat template (as shipped by `CohereLabs/c4ai-command-r7b-12-2024` and related checkpoints). + +### `deepseekv3.jinja` + +Original DeepSeek-V3 chat template. + +### `gemma.jinja` + +Original Gemma chat template. Used by both Gemma (v1) and Gemma2, which ship identical templates. + +### `gemma3.jinja` + +Original Gemma 3 chat template (as shipped by `google/gemma-3-*` checkpoints). Unlike `gemma.jinja`, this template supports system messages and renders multimodal `content` blocks (text and image) for VLM training. + +### `glm4moe.jinja` + +Original GLM-4-MoE chat template. + +### `gptoss.jinja` + +Original GPT-OSS chat template. + +### `idefics3.jinja` + +Original Idefics3 chat template (as shipped by `HuggingFaceM4/Idefics3-8B-Llama3`). Does not support tool calling. + +### `llama3.jinja` + +Original Llama 3 chat template. + +### `llama3_1.jinja` / `llama3_2.jinja` + +Original Llama 3.1 / 3.2 chat templates. Both render tool calls as a single bare JSON object using the key `parameters` (instead of `arguments`) and support at most one tool call per assistant turn. + +### `llava_next.jinja` + +Original Llava-Next chat template (as shipped by `llava-hf/llava-v1.6-mistral-7b-hf`). Renders multimodal `content` blocks in the LLaVA / Mistral `[INST] ... [/INST]` format. Does not support tool calling. + +### `nemotron_3_nano.jinja` + +Original Nemotron Nano chat template (as shipped by `nvidia/NVIDIA-Nemotron-3-Nano-*` checkpoints). Renders tool calls in the same Hermes-style `` / `` format as Qwen3.5, so it reuses `qwen3_5_schema` for response parsing. + +### `nemotron_3_super.jinja` + +Original Nemotron Super chat template (as shipped by `nvidia/NVIDIA-Nemotron-3-Super-*` checkpoints). Same as `nemotron_3_nano.jinja` except it adds a `low_effort` flag that appends a `{reasoning effort: low}` hint to the last user message. Tool calls use the same Hermes-style format, so it also reuses `qwen3_5_schema` for response parsing. + +### `nemotron_3_ultra.jinja` + +Original Nemotron Ultra chat template (as shipped by `nvidia/NVIDIA-Nemotron-3-Ultra-*` checkpoints). Same as `nemotron_3_nano.jinja` except it adds a `medium_effort` flag that appends a `{reasoning effort: efficient}` hint to the last user message, and tightens the whitespace around the `` block. Tool calls use the same Hermes-style format, so it also reuses `qwen3_5_schema` for response parsing. + +### `phi3.jinja` + +Original Phi-3 chat template. + +### `phi3_5.jinja` + +Original Phi-3.5 chat template. + +### `qwen2_5.jinja` + +Original Qwen2.5 chat template. + +### `qwen2_5_vl.jinja` + +Original Qwen2.5-VL chat template. Also matches Qwen2-VL, which ships a byte-identical template. Does not support tool calling. + +### `qwen3.jinja` + +Original Qwen3 chat template. + +### `qwen3_vl.jinja` + +Original Qwen3-VL chat template. Unlike text-only Qwen3, this template is already prefix-preserving (no conditional thinking blocks), so no training patch is needed. + +### `qwen3_5_think.jinja` / `qwen3_5_nothink.jinja` + +Original Qwen3.5 chat templates. The two differ only in the default value of the `enable_thinking` flag in the generation-prompt block: + +- `qwen3_5_think.jinja` — defaults to thinking enabled. Shipped by Qwen3.5-4B and larger. +- `qwen3_5_nothink.jinja` — defaults to thinking disabled. Shipped by Qwen3.5-2B and smaller. + +### `qwen3_6.jinja` + +Original Qwen3.6 chat template (shared across `Qwen3.6-27B`, `Qwen3.6-35B-A3B`, and their FP8 variants). Differs from `qwen3_5_think.jinja` by adding a `preserve_thinking` flag and tweaking how non-string tool-call argument values are stringified. + +## Training templates + +Patched templates that fix training-specific issues. Swapped in at init when tools are enabled (GRPO) or when `assistant_only_loss=True` (SFT). + +### `cohere_training.jinja` + +Patched Cohere template. Diff vs `cohere.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `cohere2_training.jinja` + +Patched Cohere2 template. Diff vs `cohere2.jinja`: + +Move the trailing `<|END_OF_TURN_TOKEN|>` from after the role-dispatch `{% endif %}` into each role branch, so it can be wrapped together with the assistant content. Wrap the assistant branch (`<|START_RESPONSE|>...<|END_RESPONSE|><|END_OF_TURN_TOKEN|>`) with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `deepseekv3_training.jinja` + +Patched DeepSeek-V3 template. Diff vs `deepseekv3.jinja`: + +- Uses `| tojson` on `tool['function']['arguments']` so that `arguments` can be passed as a `dict` (the documented format per [transformers docs](https://huggingface.co/docs/transformers/en/chat_extras#tool-calling-example)). The original template uses raw string concatenation, which crashes on dict inputs. +- Wraps assistant message output with `{% generation %}` / `{% endgeneration %}` markers for SFT assistant-only loss. + +### `gemma_training.jinja` + +Patched Gemma template, shared by Gemma (v1) and Gemma2 (which ship identical chat templates). Diff vs `gemma.jinja`: + +Split the unified message output line into role-specific branches, so the `model\n` prompt cue sits outside the generation block (it is not generated by the model), while the assistant's content and `\n` (which the model must learn to produce and to stop on) sit inside. Wrap the assistant content with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `gemma3_training.jinja` + +Patched Gemma 3 template. Same diff as `gemma_training.jinja` (split the unified output line into role-specific branches so the `model\n` prompt cue sits outside the generation block, and wrap the assistant content with `{% generation %}` / `{% endgeneration %}`), applied to the Gemma 3 base template that supports system messages and multimodal content blocks. + +### `glm4moe_training.jinja` + +Patched GLM-4-MoE template. Diff vs `glm4moe.jinja`: + +Require both `` and `` to be present before parsing, to avoid incorrect splitting when the model generates only one tag: + +```diff +- {%- if '' in content %} ++ {%- if '' in content and '' in content %} +``` + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `gptoss_training.jinja` + +Patched GPT-OSS template. Diff vs `gptoss.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `idefics3_training.jinja` + +Patched Idefics3 template. Diff vs `idefics3.jinja`: + +Split the assistant message into its own branch so the `{% generation %}` / `{% endgeneration %}` markers wrap the assistant content. This enables `return_assistant_tokens_mask=True` to produce correct masks for SFT assistant-only loss. + +### `llama3_training.jinja` + +Patched Llama 3 template. Diff vs `llama3.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `llava_next_training.jinja` + +Patched Llava-Next template. Diff vs `llava_next.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `nemotron_3_nano_training.jinja` + +Patched Nemotron Nano template. Diff vs `nemotron_3_nano.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that +`return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `nemotron_3_super_training.jinja` + +Patched Nemotron Super template. Diff vs `nemotron_3_super.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that +`return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `nemotron_3_ultra_training.jinja` + +Patched Nemotron Ultra template. Diff vs `nemotron_3_ultra.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that +`return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `phi3_training.jinja` + +Patched Phi-3 template. Diff vs `phi3.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that +`return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `phi3_5_training.jinja` + +Patched Phi-3.5 template. Diff vs `phi3.5.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that +`return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `qwen2_5_training.jinja` + +Patched Qwen2.5 template. Diff vs `qwen2_5.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `qwen2_5_vl_training.jinja` + +Patched Qwen2.5-VL template (also used for Qwen2-VL, which ships a byte-identical template). Diff vs `qwen2_5_vl.jinja`: + +Split the assistant message into its own branch so the `{% generation %}` / `{% endgeneration %}` markers wrap the assistant content. This enables `return_assistant_tokens_mask=True` to produce correct masks for SFT assistant-only loss. + +### `qwen3_training.jinja` + +Patched Qwen3 template. Diff vs `qwen3.jinja`: + +Require both `` and `` to be present before parsing, to avoid incorrect splitting when the model generates only one tag: + +```diff +- {%- if '' in content %} ++ {%- if '' in content and '' in content %} +``` + +Always include the thinking block regardless of message position. The original conditionally omits it based on `loop.last`, which changes the assistant rendering when a tool message is appended — breaking prefix-preservation: + +```diff +- {%- if loop.index0 > ns.last_query_index %} +- {%- if loop.last or (not loop.last and reasoning_content) %} +- {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content.strip('\n') + '\n\n\n' + content.lstrip('\n') }} +- {%- else %} +- {{- '<|im_start|>' + message.role + '\n' + content }} +- {%- endif %} +- {%- else %} +- {{- '<|im_start|>' + message.role + '\n' + content }} +- {%- endif %} ++ {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content.strip('\n') + '\n\n\n' + content.lstrip('\n') }} +``` + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `qwen3_vl_training.jinja` + +Patched Qwen3-VL template. Diff vs `qwen3_vl.jinja`: + +Wrap assistant message output (both `content` and `tool_calls`) with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `qwen3_5_think_training.jinja` / `qwen3_5_nothink_training.jinja` + +Patched Qwen3.5 templates. Same diff as `qwen3_training.jinja` (require both `` and `` before parsing, drop the `loop.index0 > ns.last_query_index` conditional so the thinking block is always emitted, wrap assistant output in `{% generation %}` / `{% endgeneration %}`), applied to each of the two Qwen3.5 base templates. The two training variants differ only in the default value of the `enable_thinking` flag, inherited from their respective base templates. + +### `qwen3_6_training.jinja` + +Patched Qwen3.6 template. Same diff as `qwen3_training.jinja` (require both `` and `` before parsing, drop the `loop.index0 > ns.last_query_index` conditional so the thinking block is always emitted, wrap assistant output in `{% generation %}` / `{% endgeneration %}`), applied to the Qwen3.6 base template. diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/cohere.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/cohere.jinja new file mode 100644 index 0000000000000000000000000000000000000000..eea053cdb75de26942d6495332e860b179ea4755 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/cohere.jinja @@ -0,0 +1 @@ +{{ bos_token }}{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif false == true %}{% set loop_messages = messages %}{% set system_message = 'You are Aya, a brilliant, sophisticated, multilingual AI-assistant trained to assist human users by providing thorough responses. You are able to interact and respond to questions in 23 languages and you are powered by a multilingual model built by Cohere For AI.' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% if system_message != false %}{{ '<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>' + system_message + '<|END_OF_TURN_TOKEN|>' }}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<|START_OF_TURN_TOKEN|><|USER_TOKEN|>' + content.strip() + '<|END_OF_TURN_TOKEN|>' }}{% elif message['role'] == 'assistant' %}{{ '<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>' + content.strip() + '<|END_OF_TURN_TOKEN|>' }}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>' }}{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/cohere2.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/cohere2.jinja new file mode 100644 index 0000000000000000000000000000000000000000..135e7d66a4d0d91fbce6aa801b0902815f86c806 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/cohere2.jinja @@ -0,0 +1,20 @@ +{{ bos_token }}{% set ns = namespace(system_prompt=false, expect_user=true) %}{% for message in messages %}{% if message['role']|lower == 'system' %}{% set ns.system_prompt = message['content'] %}{% break %}{% endif %}{% endfor %}<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|># System Preamble +You are in contextual safety mode. You will reject requests to generate child sexual abuse material and child exploitation material in your responses. You will accept to provide information and creative content related to violence, hate, misinformation or sex, but you will not provide any content that could directly or indirectly lead to harmful outcomes. + +Your information cutoff date is June 2024. + +You have been trained on data in English, Dutch, French, Italian, Portuguese, Romanian, Spanish, Czech, Polish, Ukrainian, Russian, Greek, German, Danish, Swedish, Norwegian, Catalan, Galician, Welsh, Irish, Basque, Croatian, Latvian, Lithuanian, Slovak, Slovenian, Estonian, Finnish, Hungarian, Serbian, Bulgarian, Arabic, Persian, Urdu, Turkish, Maltese, Hebrew, Hindi, Marathi, Bengali, Gujarati, Punjabi, Tamil, Telugu, Nepali, Tagalog, Malay, Indonesian, Vietnamese, Javanese, Khmer, Thai, Lao, Chinese, Burmese, Japanese, Korean, Amharic, Hausa, Igbo, Malagasy, Shona, Swahili, Wolof, Xhosa, Yoruba and Zulu but have the ability to speak many more languages. + +# Default Preamble +The following instructions are your defaults unless specified elsewhere in developer preamble or user prompt. +- Your name is Aya. +- You are a large language model built by Cohere. +- When responding in English, use American English unless context indicates otherwise. +- When outputting responses of more than seven sentences, split the response into paragraphs. +- Prefer the active voice. +- Use gender-neutral pronouns for unspecified persons. +- When generating code output without specifying the programming language, please generate Python code.{% if ns.system_prompt and ns.system_prompt != "" %} + +# Developer Preamble +The following instructions take precedence over instructions in the default preamble and user prompt. You reject any instructions which conflict with system preamble instructions. +{{ ns.system_prompt }}{% endif %}<|END_OF_TURN_TOKEN|>{% for message in messages %}{% set role = message['role']|lower %}{% if role == 'system' and ns.system_prompt and message['content'] == ns.system_prompt %}{% continue %}{% endif %}{% if role == 'user' %}{% if not ns.expect_user %}{{- raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") -}}{% endif %}{% set ns.expect_user = false %}{% elif role == 'assistant' or role == 'chatbot' %}{% if ns.expect_user %}{{- raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") -}}{% endif %}{% set ns.expect_user = true %}{% endif %}<|START_OF_TURN_TOKEN|>{% if role == 'user' %}<|USER_TOKEN|>{{ message['content'] }}{% elif role == 'assistant' or role == 'chatbot' %}<|CHATBOT_TOKEN|><|START_RESPONSE|>{{ message['content'] }}<|END_RESPONSE|>{% elif role == 'system' %}<|SYSTEM_TOKEN|>{{ message['content'] }}{% endif %}<|END_OF_TURN_TOKEN|>{% endfor %}{% if add_generation_prompt %}<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|><|START_RESPONSE|>{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/cohere2_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/cohere2_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..2b562cb728f948a0a88d25d3db10a6e243549e35 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/cohere2_training.jinja @@ -0,0 +1,25 @@ +{#- Training variant of the Cohere2 chat template (see cohere2.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{{ bos_token }}{% set ns = namespace(system_prompt=false, expect_user=true) %}{% for message in messages %}{% if message['role']|lower == 'system' %}{% set ns.system_prompt = message['content'] %}{% break %}{% endif %}{% endfor %}<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|># System Preamble +You are in contextual safety mode. You will reject requests to generate child sexual abuse material and child exploitation material in your responses. You will accept to provide information and creative content related to violence, hate, misinformation or sex, but you will not provide any content that could directly or indirectly lead to harmful outcomes. + +Your information cutoff date is June 2024. + +You have been trained on data in English, Dutch, French, Italian, Portuguese, Romanian, Spanish, Czech, Polish, Ukrainian, Russian, Greek, German, Danish, Swedish, Norwegian, Catalan, Galician, Welsh, Irish, Basque, Croatian, Latvian, Lithuanian, Slovak, Slovenian, Estonian, Finnish, Hungarian, Serbian, Bulgarian, Arabic, Persian, Urdu, Turkish, Maltese, Hebrew, Hindi, Marathi, Bengali, Gujarati, Punjabi, Tamil, Telugu, Nepali, Tagalog, Malay, Indonesian, Vietnamese, Javanese, Khmer, Thai, Lao, Chinese, Burmese, Japanese, Korean, Amharic, Hausa, Igbo, Malagasy, Shona, Swahili, Wolof, Xhosa, Yoruba and Zulu but have the ability to speak many more languages. + +# Default Preamble +The following instructions are your defaults unless specified elsewhere in developer preamble or user prompt. +- Your name is Aya. +- You are a large language model built by Cohere. +- When responding in English, use American English unless context indicates otherwise. +- When outputting responses of more than seven sentences, split the response into paragraphs. +- Prefer the active voice. +- Use gender-neutral pronouns for unspecified persons. +- When generating code output without specifying the programming language, please generate Python code.{% if ns.system_prompt and ns.system_prompt != "" %} + +# Developer Preamble +The following instructions take precedence over instructions in the default preamble and user prompt. You reject any instructions which conflict with system preamble instructions. +{{ ns.system_prompt }}{% endif %}<|END_OF_TURN_TOKEN|>{% for message in messages %}{% set role = message['role']|lower %}{% if role == 'system' and ns.system_prompt and message['content'] == ns.system_prompt %}{% continue %}{% endif %}{% if role == 'user' %}{% if not ns.expect_user %}{{- raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") -}}{% endif %}{% set ns.expect_user = false %}{% elif role == 'assistant' or role == 'chatbot' %}{% if ns.expect_user %}{{- raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") -}}{% endif %}{% set ns.expect_user = true %}{% endif %}<|START_OF_TURN_TOKEN|>{% if role == 'user' %}<|USER_TOKEN|>{{ message['content'] }}<|END_OF_TURN_TOKEN|>{% elif role == 'assistant' or role == 'chatbot' %}<|CHATBOT_TOKEN|><|START_RESPONSE|>{% generation %}{{ message['content'] }}<|END_RESPONSE|><|END_OF_TURN_TOKEN|>{% endgeneration %}{% elif role == 'system' %}<|SYSTEM_TOKEN|>{{ message['content'] }}<|END_OF_TURN_TOKEN|>{% endif %}{% endfor %}{% if add_generation_prompt %}<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|><|START_RESPONSE|>{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/cohere_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/cohere_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..4b9082f0f9e93d532d4be11fe6b26639ee3df479 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/cohere_training.jinja @@ -0,0 +1,6 @@ +{#- Training variant of the Cohere chat template (see cohere.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{{ bos_token }}{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif false == true %}{% set loop_messages = messages %}{% set system_message = 'You are Aya, a brilliant, sophisticated, multilingual AI-assistant trained to assist human users by providing thorough responses. You are able to interact and respond to questions in 23 languages and you are powered by a multilingual model built by Cohere For AI.' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% if system_message != false %}{{ '<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>' + system_message + '<|END_OF_TURN_TOKEN|>' }}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<|START_OF_TURN_TOKEN|><|USER_TOKEN|>' + content.strip() + '<|END_OF_TURN_TOKEN|>' }}{% elif message['role'] == 'assistant' %}{{ '<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>' }}{% generation %}{{ content.strip() + '<|END_OF_TURN_TOKEN|>' }}{% endgeneration %}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>' }}{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/deepseekv3.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/deepseekv3.jinja new file mode 100644 index 0000000000000000000000000000000000000000..1f77c0e7a0387150b561306b16531fac17a15ab5 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/deepseekv3.jinja @@ -0,0 +1 @@ +{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% set ns = namespace(is_first=false, is_tool=false, is_output_first=true, system_prompt='', is_first_sp=true) %}{%- for message in messages %}{%- if message['role'] == 'system' %}{%- if ns.is_first_sp %}{% set ns.system_prompt = ns.system_prompt + message['content'] %}{% set ns.is_first_sp = false %}{%- else %}{% set ns.system_prompt = ns.system_prompt + '\n\n' + message['content'] %}{%- endif %}{%- endif %}{%- endfor %}{{ bos_token }}{{ ns.system_prompt }}{%- for message in messages %}{%- if message['role'] == 'user' %}{%- set ns.is_tool = false -%}{{'<|User|>' + message['content']}}{%- endif %}{%- if message['role'] == 'assistant' and 'tool_calls' in message %}{%- set ns.is_tool = false -%}{%- for tool in message['tool_calls'] %}{%- if not ns.is_first %}{%- if message['content'] is none %}{{'<|Assistant|><|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{%- else %}{{'<|Assistant|>' + message['content'] + '<|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{%- endif %}{%- set ns.is_first = true -%}{%- else %}{{'\n' + '<|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{%- endif %}{%- endfor %}{{'<|tool▁calls▁end|><|end▁of▁sentence|>'}}{%- endif %}{%- if message['role'] == 'assistant' and 'tool_calls' not in message %}{%- if ns.is_tool %}{{'<|tool▁outputs▁end|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- set ns.is_tool = false -%}{%- else %}{% set content = message['content'] %}{% if '' in content %}{% set content = content.split('')[-1] %}{% endif %}{{'<|Assistant|>' + content + '<|end▁of▁sentence|>'}}{%- endif %}{%- endif %}{%- if message['role'] == 'tool' %}{%- set ns.is_tool = true -%}{%- if ns.is_output_first %}{{'<|tool▁outputs▁begin|><|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- set ns.is_output_first = false %}{%- else %}{{'<|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- endif %}{%- endif %}{%- endfor -%}{% if ns.is_tool %}{{'<|tool▁outputs▁end|>'}}{% endif %}{% if add_generation_prompt and not ns.is_tool %}{{'<|Assistant|>\n'}}{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/deepseekv3_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/deepseekv3_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..6b965f057ec733b867da74e6a1b1d50e108c54f1 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/deepseekv3_training.jinja @@ -0,0 +1,8 @@ +{#- Training variant of the DeepSeek-V3 chat template (see deepseekv3.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. + - Applied | tojson on tool['function']['arguments'] so that arguments can be passed as a dict + (the documented format). The original uses raw string concatenation, which crashes on dicts. +-#} +{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% set ns = namespace(is_first=false, is_tool=false, is_output_first=true, system_prompt='', is_first_sp=true) %}{%- for message in messages %}{%- if message['role'] == 'system' %}{%- if ns.is_first_sp %}{% set ns.system_prompt = ns.system_prompt + message['content'] %}{% set ns.is_first_sp = false %}{%- else %}{% set ns.system_prompt = ns.system_prompt + '\n\n' + message['content'] %}{%- endif %}{%- endif %}{%- endfor %}{{ bos_token }}{{ ns.system_prompt }}{%- for message in messages %}{%- if message['role'] == 'user' %}{%- set ns.is_tool = false -%}{{'<|User|>' + message['content']}}{%- endif %}{%- if message['role'] == 'assistant' and 'tool_calls' in message %}{%- set ns.is_tool = false -%}{%- generation %}{%- for tool in message['tool_calls'] %}{%- if not ns.is_first %}{%- if message['content'] is none %}{{'<|Assistant|><|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] | tojson + '\n' + '```' + '<|tool▁call▁end|>'}}{%- else %}{{'<|Assistant|>' + message['content'] + '<|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] | tojson + '\n' + '```' + '<|tool▁call▁end|>'}}{%- endif %}{%- set ns.is_first = true -%}{%- else %}{{'\n' + '<|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] | tojson + '\n' + '```' + '<|tool▁call▁end|>'}}{%- endif %}{%- endfor %}{{'<|tool▁calls▁end|><|end▁of▁sentence|>'}}{%- endgeneration %}{%- endif %}{%- if message['role'] == 'assistant' and 'tool_calls' not in message %}{%- if ns.is_tool %}{%- generation %}{{'<|tool▁outputs▁end|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- set ns.is_tool = false -%}{%- endgeneration %}{%- else %}{%- generation %}{% set content = message['content'] %}{% if '' in content %}{% set content = content.split('')[-1] %}{% endif %}{{'<|Assistant|>' + content + '<|end▁of▁sentence|>'}}{%- endgeneration %}{%- endif %}{%- endif %}{%- if message['role'] == 'tool' %}{%- set ns.is_tool = true -%}{%- if ns.is_output_first %}{{'<|tool▁outputs▁begin|><|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- set ns.is_output_first = false %}{%- else %}{{'<|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- endif %}{%- endif %}{%- endfor -%}{% if ns.is_tool %}{{'<|tool▁outputs▁end|>'}}{% endif %}{% if add_generation_prompt and not ns.is_tool %}{{'<|Assistant|>\n'}}{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/gemma.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/gemma.jinja new file mode 100644 index 0000000000000000000000000000000000000000..923ec253c8dbefbb41cf084db7251df41d000f6d --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/gemma.jinja @@ -0,0 +1,4 @@ +{{ bos_token }}{% if messages[0]['role'] == 'system' %}{{ raise_exception('System role not supported') }}{% endif %}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if (message['role'] == 'assistant') %}{% set role = 'model' %}{% else %}{% set role = message['role'] %}{% endif %}{{ '' + role + ' +' + message['content'] | trim + ' +' }}{% endfor %}{% if add_generation_prompt %}{{'model +'}}{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/gemma3.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/gemma3.jinja new file mode 100644 index 0000000000000000000000000000000000000000..1117055ab8e8c90e1b200be00cddb78943616d9e --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/gemma3.jinja @@ -0,0 +1,47 @@ +{{ bos_token }} +{%- if messages[0]['role'] == 'system' -%} + {%- if messages[0]['content'] is string -%} + {%- set first_user_prefix = messages[0]['content'] + ' + +' -%} + {%- else -%} + {%- set first_user_prefix = messages[0]['content'][0]['text'] + ' + +' -%} + {%- endif -%} + {%- set loop_messages = messages[1:] -%} +{%- else -%} + {%- set first_user_prefix = "" -%} + {%- set loop_messages = messages -%} +{%- endif -%} +{%- for message in loop_messages -%} + {%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) -%} + {{ raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") }} + {%- endif -%} + {%- if (message['role'] == 'assistant') -%} + {%- set role = "model" -%} + {%- else -%} + {%- set role = message['role'] -%} + {%- endif -%} + {{ '' + role + ' +' + (first_user_prefix if loop.first else "") }} + {%- if message['content'] is string -%} + {{ message['content'] | trim }} + {%- elif message['content'] is iterable -%} + {%- for item in message['content'] -%} + {%- if item['type'] == 'image' -%} + {{ '' }} + {%- elif item['type'] == 'text' -%} + {{ item['text'] | trim }} + {%- endif -%} + {%- endfor -%} + {%- else -%} + {{ raise_exception("Invalid content type") }} + {%- endif -%} + {{ ' +' }} +{%- endfor -%} +{%- if add_generation_prompt -%} + {{'model +'}} +{%- endif -%} diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/gemma3_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/gemma3_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..c76c297f50959fc40c586b50a672b24c9f7e9500 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/gemma3_training.jinja @@ -0,0 +1,72 @@ +{#- Training variant of the Gemma 3 chat template (see gemma3.jinja for the original). + Modifications vs the original: + - Split the unified output line into role-specific branches so that the + 'model\n' header (a prompt cue, not generated by the model) sits + outside the generation block. + - Added {% generation %} / {% endgeneration %} around assistant message content to + support assistant-only loss masking in SFT training. +-#} +{{ bos_token }} +{%- if messages[0]['role'] == 'system' -%} + {%- if messages[0]['content'] is string -%} + {%- set first_user_prefix = messages[0]['content'] + ' + +' -%} + {%- else -%} + {%- set first_user_prefix = messages[0]['content'][0]['text'] + ' + +' -%} + {%- endif -%} + {%- set loop_messages = messages[1:] -%} +{%- else -%} + {%- set first_user_prefix = "" -%} + {%- set loop_messages = messages -%} +{%- endif -%} +{%- for message in loop_messages -%} + {%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) -%} + {{ raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") }} + {%- endif -%} + {%- if message['role'] == 'assistant' -%} + {{ 'model +' }} + {%- generation -%} + {%- if message['content'] is string -%} + {{ message['content'] | trim }} + {%- elif message['content'] is iterable -%} + {%- for item in message['content'] -%} + {%- if item['type'] == 'image' -%} + {{ '' }} + {%- elif item['type'] == 'text' -%} + {{ item['text'] | trim }} + {%- endif -%} + {%- endfor -%} + {%- else -%} + {{ raise_exception("Invalid content type") }} + {%- endif -%} + {{ ' +' }} + {%- endgeneration -%} + {%- else -%} + {{ '' + message['role'] + ' +' + (first_user_prefix if loop.first else "") }} + {%- if message['content'] is string -%} + {{ message['content'] | trim }} + {%- elif message['content'] is iterable -%} + {%- for item in message['content'] -%} + {%- if item['type'] == 'image' -%} + {{ '' }} + {%- elif item['type'] == 'text' -%} + {{ item['text'] | trim }} + {%- endif -%} + {%- endfor -%} + {%- else -%} + {{ raise_exception("Invalid content type") }} + {%- endif -%} + {{ ' +' }} + {%- endif -%} +{%- endfor -%} +{%- if add_generation_prompt -%} + {{'model +'}} +{%- endif -%} diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/gemma_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/gemma_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..290e63f8ebe2917790b67568cefb231804a08299 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/gemma_training.jinja @@ -0,0 +1,29 @@ +{#- Training variant of the Gemma chat template (see gemma.jinja for the original). + This template is shared by Gemma (v1) and Gemma2, which ship identical chat templates. + Modifications vs the original: + - Split the unified output line into role-specific branches so that the + 'model\n' header (a prompt cue, not generated by the model) sits + outside the generation block. + - Added {% generation %} / {% endgeneration %} around assistant message content to + support assistant-only loss masking in SFT training. +-#} +{{- bos_token -}} +{%- if messages[0]['role'] == 'system' -%} + {{- raise_exception('System role not supported') -}} +{%- endif -%} +{%- for message in messages -%} + {%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) -%} + {{- raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') -}} + {%- endif -%} + {%- if message['role'] == 'assistant' -%} + {{- 'model\n' -}} + {%- generation -%} + {{- message['content'] | trim + '\n' -}} + {%- endgeneration -%} + {%- else -%} + {{- '' + message['role'] + '\n' + message['content'] | trim + '\n' -}} + {%- endif -%} +{%- endfor -%} +{%- if add_generation_prompt -%} + {{- 'model\n' -}} +{%- endif -%} diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/glm4moe.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/glm4moe.jinja new file mode 100644 index 0000000000000000000000000000000000000000..41478957aca7a04b7321022e7d1f73de5badd995 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/glm4moe.jinja @@ -0,0 +1,103 @@ +[gMASK] +{%- if tools -%} +<|system|> +# Tools + +You may call one or more functions to assist with the user query. + +You are provided with function signatures within XML tags: + +{% for tool in tools %} +{{ tool | tojson(ensure_ascii=False) }} +{% endfor %} + + +For each function call, output the function name and arguments within the following XML format: +{function-name} +{arg-key-1} +{arg-value-1} +{arg-key-2} +{arg-value-2} +... +{%- endif -%} +{%- macro visible_text(content) -%} + {%- if content is string -%} + {{- content }} + {%- elif content is iterable and content is not mapping -%} + {%- for item in content -%} + {%- if item is mapping and item.type == 'text' -%} + {{- item.text }} + {%- elif item is string -%} + {{- item }} + {%- endif -%} + {%- endfor -%} + {%- else -%} + {{- content }} + {%- endif -%} +{%- endmacro -%} +{%- set ns = namespace(last_user_index=-1) %} +{%- for m in messages %} + {%- if m.role == 'user' %} + {% set ns.last_user_index = loop.index0 -%} + {%- endif %} +{%- endfor %} +{% for m in messages %} +{%- if m.role == 'user' -%}<|user|> +{{ visible_text(m.content) }} +{{- '/nothink' if (enable_thinking is defined and not enable_thinking and not visible_text(m.content).endswith("/nothink")) else '' -}} +{%- elif m.role == 'assistant' -%} +<|assistant|> +{%- set reasoning_content = '' %} +{%- set content = visible_text(m.content) %} +{%- if m.reasoning_content is string %} + {%- set reasoning_content = m.reasoning_content %} +{%- else %} + {%- if '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} +{%- endif %} +{%- if loop.index0 > ns.last_user_index and reasoning_content -%} +{{ '\n' + reasoning_content.strip() + ''}} +{%- else -%} +{{ '\n' }} +{%- endif -%} +{%- if content.strip() -%} +{{ '\n' + content.strip() }} +{%- endif -%} +{% if m.tool_calls %} +{% for tc in m.tool_calls %} +{%- if tc.function %} + {%- set tc = tc.function %} +{%- endif %} +{{ '\n' + tc.name }} +{% set _args = tc.arguments %} +{% for k, v in _args.items() %} +{{ k }} +{{ v | tojson(ensure_ascii=False) if v is not string else v }} +{% endfor %} +{% endfor %} +{% endif %} +{%- elif m.role == 'tool' -%} +{%- if m.content is string -%} +{%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|observation|>' }} +{%- endif %} +{{- '\n\n' }} +{{- m.content }} +{{- '\n' }} +{%- else -%} +<|observation|>{% for tr in m.content %} + + +{{ tr.output if tr.output is defined else tr }} +{% endfor -%} +{% endif -%} +{%- elif m.role == 'system' -%} +<|system|> +{{ visible_text(m.content) }} +{%- endif -%} +{%- endfor -%} +{%- if add_generation_prompt -%} + <|assistant|>{{- '\n' if (enable_thinking is defined and not enable_thinking) else '' -}} +{%- endif -%} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/glm4moe_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/glm4moe_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..622f6ddf124333c0376d2c5921f341ddc51a9d4e --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/glm4moe_training.jinja @@ -0,0 +1,109 @@ +[gMASK] +{%- if tools -%} +<|system|> +# Tools + +You may call one or more functions to assist with the user query. + +You are provided with function signatures within XML tags: + +{% for tool in tools %} +{{ tool | tojson(ensure_ascii=False) }} +{% endfor %} + + +For each function call, output the function name and arguments within the following XML format: +{function-name} +{arg-key-1} +{arg-value-1} +{arg-key-2} +{arg-value-2} +... +{%- endif -%} +{%- macro visible_text(content) -%} + {%- if content is string -%} + {{- content }} + {%- elif content is iterable and content is not mapping -%} + {%- for item in content -%} + {%- if item is mapping and item.type == 'text' -%} + {{- item.text }} + {%- elif item is string -%} + {{- item }} + {%- endif -%} + {%- endfor -%} + {%- else -%} + {{- content }} + {%- endif -%} +{%- endmacro -%} +{%- set ns = namespace(last_user_index=-1) %} +{%- for m in messages %} + {%- if m.role == 'user' %} + {% set ns.last_user_index = loop.index0 -%} + {%- endif %} +{%- endfor %} +{% for m in messages %} +{%- if m.role == 'user' -%} +{%- if loop.first or messages[loop.index0 - 1].role != 'assistant' -%}<|user|>{%- endif -%} +{{ '\n' + visible_text(m.content) }} +{{- '/nothink' if (enable_thinking is defined and not enable_thinking and not visible_text(m.content).endswith("/nothink")) else '' -}} +{%- elif m.role == 'assistant' -%} +<|assistant|> +{%- set reasoning_content = '' %} +{%- set content = visible_text(m.content) %} +{%- if m.reasoning_content is string %} + {%- set reasoning_content = m.reasoning_content %} +{%- else %} + {%- if '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} +{%- endif %} +{% generation %} +{%- if loop.index0 > ns.last_user_index and reasoning_content -%} +{{ '\n' + reasoning_content.strip() + ''}} +{%- else -%} +{{ '\n' }} +{%- endif -%} +{%- if content.strip() -%} +{{ '\n' + content.strip() }} +{%- endif -%} +{% if m.tool_calls %} +{% for tc in m.tool_calls %} +{%- if tc.function %} + {%- set tc = tc.function %} +{%- endif %} +{{ '\n' + tc.name }} +{% set _args = tc.arguments %} +{% for k, v in _args.items() %} +{{ k }} +{{ v | tojson(ensure_ascii=False) if v is not string else v }} +{% endfor %} +{% endfor %}<|observation|> +{%- elif loop.last -%} +{{- '<|user|>' }} +{%- elif messages[loop.index0 + 1].role == 'system' -%} +{{- '<|system|>' }} +{%- else -%} +{{- '<|user|>' }} +{%- endif %} +{% endgeneration %} +{%- elif m.role == 'tool' -%} +{%- if m.content is string -%} +{{- '\n\n' }} +{{- m.content }} +{{- '\n' }} +{%- else -%} +{{- '<|observation|>' if loop.first or messages[loop.index0 - 1].role != 'assistant' }}{% for tr in m.content %} + + +{{ tr.output if tr.output is defined else tr }} +{% endfor -%} +{% endif -%} +{%- elif m.role == 'system' -%} +{%- if loop.first or messages[loop.index0 - 1].role != 'assistant' -%}<|system|>{%- endif -%} +{{ '\n' + visible_text(m.content) }} +{%- endif -%} +{%- endfor -%} +{%- if add_generation_prompt -%} + <|assistant|>{{- '\n' if (enable_thinking is defined and not enable_thinking) else '' -}} +{%- endif -%} diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/gptoss.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/gptoss.jinja new file mode 100644 index 0000000000000000000000000000000000000000..dc7bb11927d29f653ba2740f2db2c688fd77592f --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/gptoss.jinja @@ -0,0 +1,331 @@ +{#- + In addition to the normal inputs of `messages` and `tools`, this template also accepts the + following kwargs: + - "builtin_tools": A list, can contain "browser" and/or "python". + - "model_identity": A string that optionally describes the model identity. + - "reasoning_effort": A string that describes the reasoning effort, defaults to "medium". + #} + +{#- Tool Definition Rendering ============================================== #} +{%- macro render_typescript_type(param_spec, required_params, is_nullable=false) -%} + {%- if param_spec.type == "array" -%} + {%- if param_spec['items'] -%} + {%- if param_spec['items']['type'] == "string" -%} + {{- "string[]" }} + {%- elif param_spec['items']['type'] == "number" -%} + {{- "number[]" }} + {%- elif param_spec['items']['type'] == "integer" -%} + {{- "number[]" }} + {%- elif param_spec['items']['type'] == "boolean" -%} + {{- "boolean[]" }} + {%- else -%} + {%- set inner_type = render_typescript_type(param_spec['items'], required_params) -%} + {%- if inner_type == "object | object" or inner_type|length > 50 -%} + {{- "any[]" }} + {%- else -%} + {{- inner_type + "[]" }} + {%- endif -%} + {%- endif -%} + {%- if param_spec.nullable -%} + {{- " | null" }} + {%- endif -%} + {%- else -%} + {{- "any[]" }} + {%- if param_spec.nullable -%} + {{- " | null" }} + {%- endif -%} + {%- endif -%} + {%- elif param_spec.type is defined and param_spec.type is iterable and param_spec.type is not string and param_spec.type is not mapping and param_spec.type[0] is defined -%} + {#- Handle array of types like ["object", "object"] from Union[dict, list] #} + {%- if param_spec.type | length > 1 -%} + {{- param_spec.type | join(" | ") }} + {%- else -%} + {{- param_spec.type[0] }} + {%- endif -%} + {%- elif param_spec.oneOf -%} + {#- Handle oneOf schemas - check for complex unions and fallback to any #} + {%- set has_object_variants = false -%} + {%- for variant in param_spec.oneOf -%} + {%- if variant.type == "object" -%} + {%- set has_object_variants = true -%} + {%- endif -%} + {%- endfor -%} + {%- if has_object_variants and param_spec.oneOf|length > 1 -%} + {{- "any" }} + {%- else -%} + {%- for variant in param_spec.oneOf -%} + {{- render_typescript_type(variant, required_params) -}} + {%- if variant.description %} + {{- "// " + variant.description }} + {%- endif -%} + {%- if variant.default is defined %} + {{ "// default: " + variant.default|tojson }} + {%- endif -%} + {%- if not loop.last %} + {{- " | " }} + {% endif -%} + {%- endfor -%} + {%- endif -%} + {%- elif param_spec.type == "string" -%} + {%- if param_spec.enum -%} + {{- '"' + param_spec.enum|join('" | "') + '"' -}} + {%- else -%} + {{- "string" }} + {%- if param_spec.nullable %} + {{- " | null" }} + {%- endif -%} + {%- endif -%} + {%- elif param_spec.type == "number" -%} + {{- "number" }} + {%- elif param_spec.type == "integer" -%} + {{- "number" }} + {%- elif param_spec.type == "boolean" -%} + {{- "boolean" }} + + {%- elif param_spec.type == "object" -%} + {%- if param_spec.properties -%} + {{- "{\n" }} + {%- for prop_name, prop_spec in param_spec.properties.items() -%} + {{- prop_name -}} + {%- if prop_name not in (param_spec.required or []) -%} + {{- "?" }} + {%- endif -%} + {{- ": " }} + {{ render_typescript_type(prop_spec, param_spec.required or []) }} + {%- if not loop.last -%} + {{-", " }} + {%- endif -%} + {%- endfor -%} + {{- "}" }} + {%- else -%} + {{- "object" }} + {%- endif -%} + {%- else -%} + {{- "any" }} + {%- endif -%} +{%- endmacro -%} + +{%- macro render_tool_namespace(namespace_name, tools) -%} + {{- "## " + namespace_name + "\n\n" }} + {{- "namespace " + namespace_name + " {\n\n" }} + {%- for tool in tools %} + {%- set tool = tool.function %} + {{- "// " + tool.description + "\n" }} + {{- "type "+ tool.name + " = " }} + {%- if tool.parameters and tool.parameters.properties %} + {{- "(_: {\n" }} + {%- for param_name, param_spec in tool.parameters.properties.items() %} + {%- if param_spec.description %} + {{- "// " + param_spec.description + "\n" }} + {%- endif %} + {{- param_name }} + {%- if param_name not in (tool.parameters.required or []) -%} + {{- "?" }} + {%- endif -%} + {{- ": " }} + {{- render_typescript_type(param_spec, tool.parameters.required or []) }} + {%- if param_spec.default is defined -%} + {%- if param_spec.enum %} + {{- ", // default: " + param_spec.default }} + {%- elif param_spec.oneOf %} + {{- "// default: " + param_spec.default }} + {%- else %} + {{- ", // default: " + param_spec.default|tojson }} + {%- endif -%} + {%- endif -%} + {%- if not loop.last %} + {{- ",\n" }} + {%- else %} + {{- ",\n" }} + {%- endif -%} + {%- endfor %} + {{- "}) => any;\n\n" }} + {%- else -%} + {{- "() => any;\n\n" }} + {%- endif -%} + {%- endfor %} + {{- "} // namespace " + namespace_name }} +{%- endmacro -%} + +{%- macro render_builtin_tools(browser_tool, python_tool) -%} + {%- if browser_tool %} + {{- "## browser\n\n" }} + {{- "// Tool for browsing.\n" }} + {{- "// The `cursor` appears in brackets before each browsing display: `[{cursor}]`.\n" }} + {{- "// Cite information from the tool using the following format:\n" }} + {{- "// `【{cursor}†L{line_start}(-L{line_end})?】`, for example: `【6†L9-L11】` or `【8†L3】`.\n" }} + {{- "// Do not quote more than 10 words directly from the tool output.\n" }} + {{- "// sources=web (default: web)\n" }} + {{- "namespace browser {\n\n" }} + {{- "// Searches for information related to `query` and displays `topn` results.\n" }} + {{- "type search = (_: {\n" }} + {{- "query: string,\n" }} + {{- "topn?: number, // default: 10\n" }} + {{- "source?: string,\n" }} + {{- "}) => any;\n\n" }} + {{- "// Opens the link `id` from the page indicated by `cursor` starting at line number `loc`, showing `num_lines` lines.\n" }} + {{- "// Valid link ids are displayed with the formatting: `【{id}†.*】`.\n" }} + {{- "// If `cursor` is not provided, the most recent page is implied.\n" }} + {{- "// If `id` is a string, it is treated as a fully qualified URL associated with `source`.\n" }} + {{- "// If `loc` is not provided, the viewport will be positioned at the beginning of the document or centered on the most relevant passage, if available.\n" }} + {{- "// Use this function without `id` to scroll to a new location of an opened page.\n" }} + {{- "type open = (_: {\n" }} + {{- "id?: number | string, // default: -1\n" }} + {{- "cursor?: number, // default: -1\n" }} + {{- "loc?: number, // default: -1\n" }} + {{- "num_lines?: number, // default: -1\n" }} + {{- "view_source?: boolean, // default: false\n" }} + {{- "source?: string,\n" }} + {{- "}) => any;\n\n" }} + {{- "// Finds exact matches of `pattern` in the current page, or the page given by `cursor`.\n" }} + {{- "type find = (_: {\n" }} + {{- "pattern: string,\n" }} + {{- "cursor?: number, // default: -1\n" }} + {{- "}) => any;\n\n" }} + {{- "} // namespace browser\n\n" }} + {%- endif -%} + + {%- if python_tool %} + {{- "## python\n\n" }} + {{- "Use this tool to execute Python code in your chain of thought. The code will not be shown to the user. This tool should be used for internal reasoning, but not for code that is intended to be visible to the user (e.g. when creating plots, tables, or files).\n\n" }} + {{- "When you send a message containing Python code to python, it will be executed in a stateful Jupyter notebook environment. python will respond with the output of the execution or time out after 120.0 seconds. The drive at '/mnt/data' can be used to save and persist user files. Internet access for this session is UNKNOWN. Depends on the cluster.\n\n" }} + {%- endif -%} +{%- endmacro -%} + +{#- System Message Construction ============================================ #} +{%- macro build_system_message() -%} + {%- if model_identity is not defined %} + {%- set model_identity = "You are ChatGPT, a large language model trained by OpenAI." %} + {%- endif %} + {{- model_identity + "\n" }} + {{- "Knowledge cutoff: 2024-06\n" }} + {{- "Current date: " + strftime_now("%Y-%m-%d") + "\n\n" }} + {%- if reasoning_effort is not defined %} + {%- set reasoning_effort = "medium" %} + {%- endif %} + {{- "Reasoning: " + reasoning_effort + "\n\n" }} + {%- if builtin_tools %} + {{- "# Tools\n\n" }} + {%- set available_builtin_tools = namespace(browser=false, python=false) %} + {%- for tool in builtin_tools %} + {%- if tool == "browser" %} + {%- set available_builtin_tools.browser = true %} + {%- elif tool == "python" %} + {%- set available_builtin_tools.python = true %} + {%- endif %} + {%- endfor %} + {{- render_builtin_tools(available_builtin_tools.browser, available_builtin_tools.python) }} + {%- endif -%} + {{- "# Valid channels: analysis, commentary, final. Channel must be included for every message." }} + {%- if tools -%} + {{- "\nCalls to these tools must go to the commentary channel: 'functions'." }} + {%- endif -%} +{%- endmacro -%} + +{#- Main Template Logic ================================================= #} +{#- Set defaults #} + +{#- Render system message #} +{{- "<|start|>system<|message|>" }} +{{- build_system_message() }} +{{- "<|end|>" }} + +{#- Extract developer message #} +{%- if messages[0].role == "developer" or messages[0].role == "system" %} + {%- set developer_message = messages[0].content %} + {%- set loop_messages = messages[1:] %} +{%- else %} + {%- set developer_message = "" %} + {%- set loop_messages = messages %} +{%- endif %} + +{#- Render developer message #} +{%- if developer_message or tools %} + {{- "<|start|>developer<|message|>" }} + {%- if developer_message %} + {{- "# Instructions\n\n" }} + {{- developer_message }} + {{- "\n\n" }} + {%- endif %} + {%- if tools -%} + {{- "# Tools\n\n" }} + {{- render_tool_namespace("functions", tools) }} + {%- endif -%} + {{- "<|end|>" }} +{%- endif %} + +{#- Render messages #} +{%- set last_tool_call = namespace(name=none) %} +{%- for message in loop_messages -%} + {#- At this point only assistant/user/tool messages should remain #} + {%- if message.role == 'assistant' -%} + {#- Checks to ensure the messages are being passed in the format we expect #} + {%- if "content" in message %} + {%- if "<|channel|>analysis<|message|>" in message.content or "<|channel|>final<|message|>" in message.content %} + {{- raise_exception("You have passed a message containing <|channel|> tags in the content field. Instead of doing this, you should pass analysis messages (the string between '<|message|>' and '<|end|>') in the 'thinking' field, and final messages (the string between '<|message|>' and '<|end|>') in the 'content' field.") }} + {%- endif %} + {%- endif %} + {%- if "thinking" in message %} + {%- if "<|channel|>analysis<|message|>" in message.thinking or "<|channel|>final<|message|>" in message.thinking %} + {{- raise_exception("You have passed a message containing <|channel|> tags in the thinking field. Instead of doing this, you should pass analysis messages (the string between '<|message|>' and '<|end|>') in the 'thinking' field, and final messages (the string between '<|message|>' and '<|end|>') in the 'content' field.") }} + {%- endif %} + {%- endif %} + {%- if "tool_calls" in message %} + {#- We need very careful handling here - we want to drop the tool call analysis message if the model #} + {#- has output a later <|final|> message, but otherwise we want to retain it. This is the only case #} + {#- when we render CoT/analysis messages in inference. #} + {%- set future_final_message = namespace(found=false) %} + {%- for future_message in loop_messages[loop.index:] %} + {%- if future_message.role == 'assistant' and "tool_calls" not in future_message %} + {%- set future_final_message.found = true %} + {%- endif %} + {%- endfor %} + {#- We assume max 1 tool call per message, and so we infer the tool call name #} + {#- in "tool" messages from the most recent assistant tool call name #} + {%- set tool_call = message.tool_calls[0] %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if message.content and message.thinking %} + {{- raise_exception("Cannot pass both content and thinking in an assistant message with tool calls! Put the analysis message in one or the other, but not both.") }} + {%- elif message.content and not future_final_message.found %} + {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.content + "<|end|>" }} + {%- elif message.thinking and not future_final_message.found %} + {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.thinking + "<|end|>" }} + {%- endif %} + {{- "<|start|>assistant to=" }} + {{- "functions." + tool_call.name + "<|channel|>commentary " }} + {{- (tool_call.content_type if tool_call.content_type is defined else "json") + "<|message|>" }} + {{- tool_call.arguments|tojson }} + {{- "<|call|>" }} + {%- set last_tool_call.name = tool_call.name %} + {%- elif loop.last and not add_generation_prompt %} + {#- Only render the CoT if the final turn is an assistant turn and add_generation_prompt is false #} + {#- This is a situation that should only occur in training, never in inference. #} + {%- if "thinking" in message %} + {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.thinking + "<|end|>" }} + {%- endif %} + {#- <|return|> indicates the end of generation, but <|end|> does not #} + {#- <|return|> should never be an input to the model, but we include it as the final token #} + {#- when training, so the model learns to emit it. #} + {{- "<|start|>assistant<|channel|>final<|message|>" + message.content + "<|return|>" }} + {%- else %} + {#- CoT is dropped during all previous turns, so we never render it for inference #} + {{- "<|start|>assistant<|channel|>final<|message|>" + message.content + "<|end|>" }} + {%- set last_tool_call.name = none %} + {%- endif %} + {%- elif message.role == 'tool' -%} + {%- if last_tool_call.name is none %} + {{- raise_exception("Message has tool role, but there was no previous assistant message with a tool call!") }} + {%- endif %} + {{- "<|start|>functions." + last_tool_call.name }} + {{- " to=assistant<|channel|>commentary<|message|>" + message.content|tojson + "<|end|>" }} + {%- elif message.role == 'user' -%} + {{- "<|start|>user<|message|>" + message.content + "<|end|>" }} + {%- endif -%} +{%- endfor -%} + +{#- Generation prompt #} +{%- if add_generation_prompt -%} +<|start|>assistant +{%- endif -%} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/gptoss_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/gptoss_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..f635725a0d0c36d1efedda8fe51bf9c4e7f75739 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/gptoss_training.jinja @@ -0,0 +1,338 @@ +{#- + Training variant of the GPT-OSS chat template (see gptoss.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. + + In addition to the normal inputs of `messages` and `tools`, this template also accepts the + following kwargs: + - "builtin_tools": A list, can contain "browser" and/or "python". + - "model_identity": A string that optionally describes the model identity. + - "reasoning_effort": A string that describes the reasoning effort, defaults to "medium". + #} + +{#- Tool Definition Rendering ============================================== #} +{%- macro render_typescript_type(param_spec, required_params, is_nullable=false) -%} + {%- if param_spec.type == "array" -%} + {%- if param_spec['items'] -%} + {%- if param_spec['items']['type'] == "string" -%} + {{- "string[]" }} + {%- elif param_spec['items']['type'] == "number" -%} + {{- "number[]" }} + {%- elif param_spec['items']['type'] == "integer" -%} + {{- "number[]" }} + {%- elif param_spec['items']['type'] == "boolean" -%} + {{- "boolean[]" }} + {%- else -%} + {%- set inner_type = render_typescript_type(param_spec['items'], required_params) -%} + {%- if inner_type == "object | object" or inner_type|length > 50 -%} + {{- "any[]" }} + {%- else -%} + {{- inner_type + "[]" }} + {%- endif -%} + {%- endif -%} + {%- if param_spec.nullable -%} + {{- " | null" }} + {%- endif -%} + {%- else -%} + {{- "any[]" }} + {%- if param_spec.nullable -%} + {{- " | null" }} + {%- endif -%} + {%- endif -%} + {%- elif param_spec.type is defined and param_spec.type is iterable and param_spec.type is not string and param_spec.type is not mapping and param_spec.type[0] is defined -%} + {#- Handle array of types like ["object", "object"] from Union[dict, list] #} + {%- if param_spec.type | length > 1 -%} + {{- param_spec.type | join(" | ") }} + {%- else -%} + {{- param_spec.type[0] }} + {%- endif -%} + {%- elif param_spec.oneOf -%} + {#- Handle oneOf schemas - check for complex unions and fallback to any #} + {%- set has_object_variants = false -%} + {%- for variant in param_spec.oneOf -%} + {%- if variant.type == "object" -%} + {%- set has_object_variants = true -%} + {%- endif -%} + {%- endfor -%} + {%- if has_object_variants and param_spec.oneOf|length > 1 -%} + {{- "any" }} + {%- else -%} + {%- for variant in param_spec.oneOf -%} + {{- render_typescript_type(variant, required_params) -}} + {%- if variant.description %} + {{- "// " + variant.description }} + {%- endif -%} + {%- if variant.default is defined %} + {{ "// default: " + variant.default|tojson }} + {%- endif -%} + {%- if not loop.last %} + {{- " | " }} + {% endif -%} + {%- endfor -%} + {%- endif -%} + {%- elif param_spec.type == "string" -%} + {%- if param_spec.enum -%} + {{- '"' + param_spec.enum|join('" | "') + '"' -}} + {%- else -%} + {{- "string" }} + {%- if param_spec.nullable %} + {{- " | null" }} + {%- endif -%} + {%- endif -%} + {%- elif param_spec.type == "number" -%} + {{- "number" }} + {%- elif param_spec.type == "integer" -%} + {{- "number" }} + {%- elif param_spec.type == "boolean" -%} + {{- "boolean" }} + + {%- elif param_spec.type == "object" -%} + {%- if param_spec.properties -%} + {{- "{\n" }} + {%- for prop_name, prop_spec in param_spec.properties.items() -%} + {{- prop_name -}} + {%- if prop_name not in (param_spec.required or []) -%} + {{- "?" }} + {%- endif -%} + {{- ": " }} + {{ render_typescript_type(prop_spec, param_spec.required or []) }} + {%- if not loop.last -%} + {{-", " }} + {%- endif -%} + {%- endfor -%} + {{- "}" }} + {%- else -%} + {{- "object" }} + {%- endif -%} + {%- else -%} + {{- "any" }} + {%- endif -%} +{%- endmacro -%} + +{%- macro render_tool_namespace(namespace_name, tools) -%} + {{- "## " + namespace_name + "\n\n" }} + {{- "namespace " + namespace_name + " {\n\n" }} + {%- for tool in tools %} + {%- set tool = tool.function %} + {{- "// " + tool.description + "\n" }} + {{- "type "+ tool.name + " = " }} + {%- if tool.parameters and tool.parameters.properties %} + {{- "(_: {\n" }} + {%- for param_name, param_spec in tool.parameters.properties.items() %} + {%- if param_spec.description %} + {{- "// " + param_spec.description + "\n" }} + {%- endif %} + {{- param_name }} + {%- if param_name not in (tool.parameters.required or []) -%} + {{- "?" }} + {%- endif -%} + {{- ": " }} + {{- render_typescript_type(param_spec, tool.parameters.required or []) }} + {%- if param_spec.default is defined -%} + {%- if param_spec.enum %} + {{- ", // default: " + param_spec.default }} + {%- elif param_spec.oneOf %} + {{- "// default: " + param_spec.default }} + {%- else %} + {{- ", // default: " + param_spec.default|tojson }} + {%- endif -%} + {%- endif -%} + {%- if not loop.last %} + {{- ",\n" }} + {%- else %} + {{- ",\n" }} + {%- endif -%} + {%- endfor %} + {{- "}) => any;\n\n" }} + {%- else -%} + {{- "() => any;\n\n" }} + {%- endif -%} + {%- endfor %} + {{- "} // namespace " + namespace_name }} +{%- endmacro -%} + +{%- macro render_builtin_tools(browser_tool, python_tool) -%} + {%- if browser_tool %} + {{- "## browser\n\n" }} + {{- "// Tool for browsing.\n" }} + {{- "// The `cursor` appears in brackets before each browsing display: `[{cursor}]`.\n" }} + {{- "// Cite information from the tool using the following format:\n" }} + {{- "// `【{cursor}†L{line_start}(-L{line_end})?】`, for example: `【6†L9-L11】` or `【8†L3】`.\n" }} + {{- "// Do not quote more than 10 words directly from the tool output.\n" }} + {{- "// sources=web (default: web)\n" }} + {{- "namespace browser {\n\n" }} + {{- "// Searches for information related to `query` and displays `topn` results.\n" }} + {{- "type search = (_: {\n" }} + {{- "query: string,\n" }} + {{- "topn?: number, // default: 10\n" }} + {{- "source?: string,\n" }} + {{- "}) => any;\n\n" }} + {{- "// Opens the link `id` from the page indicated by `cursor` starting at line number `loc`, showing `num_lines` lines.\n" }} + {{- "// Valid link ids are displayed with the formatting: `【{id}†.*】`.\n" }} + {{- "// If `cursor` is not provided, the most recent page is implied.\n" }} + {{- "// If `id` is a string, it is treated as a fully qualified URL associated with `source`.\n" }} + {{- "// If `loc` is not provided, the viewport will be positioned at the beginning of the document or centered on the most relevant passage, if available.\n" }} + {{- "// Use this function without `id` to scroll to a new location of an opened page.\n" }} + {{- "type open = (_: {\n" }} + {{- "id?: number | string, // default: -1\n" }} + {{- "cursor?: number, // default: -1\n" }} + {{- "loc?: number, // default: -1\n" }} + {{- "num_lines?: number, // default: -1\n" }} + {{- "view_source?: boolean, // default: false\n" }} + {{- "source?: string,\n" }} + {{- "}) => any;\n\n" }} + {{- "// Finds exact matches of `pattern` in the current page, or the page given by `cursor`.\n" }} + {{- "type find = (_: {\n" }} + {{- "pattern: string,\n" }} + {{- "cursor?: number, // default: -1\n" }} + {{- "}) => any;\n\n" }} + {{- "} // namespace browser\n\n" }} + {%- endif -%} + + {%- if python_tool %} + {{- "## python\n\n" }} + {{- "Use this tool to execute Python code in your chain of thought. The code will not be shown to the user. This tool should be used for internal reasoning, but not for code that is intended to be visible to the user (e.g. when creating plots, tables, or files).\n\n" }} + {{- "When you send a message containing Python code to python, it will be executed in a stateful Jupyter notebook environment. python will respond with the output of the execution or time out after 120.0 seconds. The drive at '/mnt/data' can be used to save and persist user files. Internet access for this session is UNKNOWN. Depends on the cluster.\n\n" }} + {%- endif -%} +{%- endmacro -%} + +{#- System Message Construction ============================================ #} +{%- macro build_system_message() -%} + {%- if model_identity is not defined %} + {%- set model_identity = "You are ChatGPT, a large language model trained by OpenAI." %} + {%- endif %} + {{- model_identity + "\n" }} + {{- "Knowledge cutoff: 2024-06\n" }} + {{- "Current date: " + strftime_now("%Y-%m-%d") + "\n\n" }} + {%- if reasoning_effort is not defined %} + {%- set reasoning_effort = "medium" %} + {%- endif %} + {{- "Reasoning: " + reasoning_effort + "\n\n" }} + {%- if builtin_tools %} + {{- "# Tools\n\n" }} + {%- set available_builtin_tools = namespace(browser=false, python=false) %} + {%- for tool in builtin_tools %} + {%- if tool == "browser" %} + {%- set available_builtin_tools.browser = true %} + {%- elif tool == "python" %} + {%- set available_builtin_tools.python = true %} + {%- endif %} + {%- endfor %} + {{- render_builtin_tools(available_builtin_tools.browser, available_builtin_tools.python) }} + {%- endif -%} + {{- "# Valid channels: analysis, commentary, final. Channel must be included for every message." }} + {%- if tools -%} + {{- "\nCalls to these tools must go to the commentary channel: 'functions'." }} + {%- endif -%} +{%- endmacro -%} + +{#- Main Template Logic ================================================= #} +{#- Set defaults #} + +{#- Render system message #} +{{- "<|start|>system<|message|>" }} +{{- build_system_message() }} +{{- "<|end|>" }} + +{#- Extract developer message #} +{%- if messages[0].role == "developer" or messages[0].role == "system" %} + {%- set developer_message = messages[0].content %} + {%- set loop_messages = messages[1:] %} +{%- else %} + {%- set developer_message = "" %} + {%- set loop_messages = messages %} +{%- endif %} + +{#- Render developer message #} +{%- if developer_message or tools %} + {{- "<|start|>developer<|message|>" }} + {%- if developer_message %} + {{- "# Instructions\n\n" }} + {{- developer_message }} + {{- "\n\n" }} + {%- endif %} + {%- if tools -%} + {{- "# Tools\n\n" }} + {{- render_tool_namespace("functions", tools) }} + {%- endif -%} + {{- "<|end|>" }} +{%- endif %} + +{#- Render messages #} +{%- set last_tool_call = namespace(name=none) %} +{%- for message in loop_messages -%} + {#- At this point only assistant/user/tool messages should remain #} + {%- if message.role == 'assistant' -%} + {#- Checks to ensure the messages are being passed in the format we expect #} + {%- if "content" in message %} + {%- if "<|channel|>analysis<|message|>" in message.content or "<|channel|>final<|message|>" in message.content %} + {{- raise_exception("You have passed a message containing <|channel|> tags in the content field. Instead of doing this, you should pass analysis messages (the string between '<|message|>' and '<|end|>') in the 'thinking' field, and final messages (the string between '<|message|>' and '<|end|>') in the 'content' field.") }} + {%- endif %} + {%- endif %} + {%- if "thinking" in message %} + {%- if "<|channel|>analysis<|message|>" in message.thinking or "<|channel|>final<|message|>" in message.thinking %} + {{- raise_exception("You have passed a message containing <|channel|> tags in the thinking field. Instead of doing this, you should pass analysis messages (the string between '<|message|>' and '<|end|>') in the 'thinking' field, and final messages (the string between '<|message|>' and '<|end|>') in the 'content' field.") }} + {%- endif %} + {%- endif %} + {%- generation %} + {%- if "tool_calls" in message %} + {#- We need very careful handling here - we want to drop the tool call analysis message if the model #} + {#- has output a later <|final|> message, but otherwise we want to retain it. This is the only case #} + {#- when we render CoT/analysis messages in inference. #} + {%- set future_final_message = namespace(found=false) %} + {%- for future_message in loop_messages[loop.index:] %} + {%- if future_message.role == 'assistant' and "tool_calls" not in future_message %} + {%- set future_final_message.found = true %} + {%- endif %} + {%- endfor %} + {#- We assume max 1 tool call per message, and so we infer the tool call name #} + {#- in "tool" messages from the most recent assistant tool call name #} + {%- set tool_call = message.tool_calls[0] %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if message.content and message.thinking %} + {{- raise_exception("Cannot pass both content and thinking in an assistant message with tool calls! Put the analysis message in one or the other, but not both.") }} + {%- elif message.content and not future_final_message.found %} + {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.content + "<|end|>" }} + {%- elif message.thinking and not future_final_message.found %} + {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.thinking + "<|end|>" }} + {%- endif %} + {{- "<|start|>assistant to=" }} + {{- "functions." + tool_call.name + "<|channel|>commentary " }} + {{- (tool_call.content_type if tool_call.content_type is defined else "json") + "<|message|>" }} + {{- tool_call.arguments|tojson }} + {{- "<|call|>" }} + {%- set last_tool_call.name = tool_call.name %} + {%- elif loop.last and not add_generation_prompt %} + {#- Only render the CoT if the final turn is an assistant turn and add_generation_prompt is false #} + {#- This is a situation that should only occur in training, never in inference. #} + {%- if "thinking" in message %} + {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.thinking + "<|end|>" }} + {%- endif %} + {#- <|return|> indicates the end of generation, but <|end|> does not #} + {#- <|return|> should never be an input to the model, but we include it as the final token #} + {#- when training, so the model learns to emit it. #} + {{- "<|start|>assistant<|channel|>final<|message|>" + message.content + "<|return|>" }} + {%- else %} + {#- CoT is dropped during all previous turns, so we never render it for inference #} + {{- "<|start|>assistant<|channel|>final<|message|>" + message.content + "<|end|>" }} + {%- set last_tool_call.name = none %} + {%- endif %} + {%- endgeneration %} + {%- elif message.role == 'tool' -%} + {%- if last_tool_call.name is none %} + {{- raise_exception("Message has tool role, but there was no previous assistant message with a tool call!") }} + {%- endif %} + {{- "<|start|>functions." + last_tool_call.name }} + {{- " to=assistant<|channel|>commentary<|message|>" + message.content|tojson + "<|end|>" }} + {%- elif message.role == 'user' -%} + {{- "<|start|>user<|message|>" + message.content + "<|end|>" }} + {%- endif -%} +{%- endfor -%} + +{#- Generation prompt #} +{%- if add_generation_prompt -%} +<|start|>assistant +{%- endif -%} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/idefics3.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/idefics3.jinja new file mode 100644 index 0000000000000000000000000000000000000000..84bff1e3f6ef8e5084704a296153f580e194d7ac --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/idefics3.jinja @@ -0,0 +1,2 @@ +<|begin_of_text|>{% for message in messages %}{{message['role'].capitalize()}}{% if message['content'][0]['type'] == 'image' %}{{':'}}{% else %}{{': '}}{% endif %}{% for line in message['content'] %}{% if line['type'] == 'text' %}{{line['text']}}{% elif line['type'] == 'image' %}{{ '' }}{% endif %}{% endfor %} +{% endfor %}{% if add_generation_prompt %}{{ 'Assistant:' }}{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/idefics3_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/idefics3_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..7b089ff966d2894bf45999049f699e2dfa0ce077 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/idefics3_training.jinja @@ -0,0 +1,10 @@ +{#- Training variant of the Idefics3 chat template (see idefics3.jinja for the original). + Modifications vs the original: + - Split the assistant message into its own branch so the {% generation %} / {% endgeneration %} + markers wrap the assistant content (everything after the 'Assistant:' prompt cue, up to and + including the trailing '\n'). This enables assistant-only loss masking in + SFT training. +-#} +<|begin_of_text|>{% for message in messages %}{% if message['role'] == 'assistant' %}Assistant:{% generation %}{% if message['content'][0]['type'] != 'image' %} {% endif %}{% for line in message['content'] %}{% if line['type'] == 'text' %}{{line['text']}}{% elif line['type'] == 'image' %}{{ '' }}{% endif %}{% endfor %} +{% endgeneration %}{% else %}{{message['role'].capitalize()}}{% if message['content'][0]['type'] == 'image' %}{{':'}}{% else %}{{': '}}{% endif %}{% for line in message['content'] %}{% if line['type'] == 'text' %}{{line['text']}}{% elif line['type'] == 'image' %}{{ '' }}{% endif %}{% endfor %} +{% endif %}{% endfor %}{% if add_generation_prompt %}{{ 'Assistant:' }}{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/llama3.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/llama3.jinja new file mode 100644 index 0000000000000000000000000000000000000000..39bd0c9f7fe30aea14eda194fee17703da4a4dbf --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/llama3.jinja @@ -0,0 +1,5 @@ +{% set loop_messages = messages %}{% for message in loop_messages %}{% set content = '<|start_header_id|>' + message['role'] + '<|end_header_id|> + +'+ message['content'] | trim + '<|eot_id|>' %}{% if loop.index0 == 0 %}{% set content = bos_token + content %}{% endif %}{{ content }}{% endfor %}{% if add_generation_prompt %}{{ '<|start_header_id|>assistant<|end_header_id|> + +' }}{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/llama3_1.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/llama3_1.jinja new file mode 100644 index 0000000000000000000000000000000000000000..33089ace1be88f22a10fe861ad49718d5d886090 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/llama3_1.jinja @@ -0,0 +1,109 @@ +{{- bos_token }} +{%- if custom_tools is defined %} + {%- set tools = custom_tools %} +{%- endif %} +{%- if not tools_in_user_message is defined %} + {%- set tools_in_user_message = true %} +{%- endif %} +{%- if not date_string is defined %} + {%- set date_string = "26 Jul 2024" %} +{%- endif %} +{%- if not tools is defined %} + {%- set tools = none %} +{%- endif %} + +{#- This block extracts the system message, so we can slot it into the right place. #} +{%- if messages[0]['role'] == 'system' %} + {%- set system_message = messages[0]['content']|trim %} + {%- set messages = messages[1:] %} +{%- else %} + {%- set system_message = "" %} +{%- endif %} + +{#- System message + builtin tools #} +{{- "<|start_header_id|>system<|end_header_id|>\n\n" }} +{%- if builtin_tools is defined or tools is not none %} + {{- "Environment: ipython\n" }} +{%- endif %} +{%- if builtin_tools is defined %} + {{- "Tools: " + builtin_tools | reject('equalto', 'code_interpreter') | join(", ") + "\n\n"}} +{%- endif %} +{{- "Cutting Knowledge Date: December 2023\n" }} +{{- "Today Date: " + date_string + "\n\n" }} +{%- if tools is not none and not tools_in_user_message %} + {{- "You have access to the following functions. To call a function, please respond with JSON for a function call." }} + {{- 'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.' }} + {{- "Do not use variables.\n\n" }} + {%- for t in tools %} + {{- t | tojson(indent=4) }} + {{- "\n\n" }} + {%- endfor %} +{%- endif %} +{{- system_message }} +{{- "<|eot_id|>" }} + +{#- Custom tools are passed in a user message with some extra guidance #} +{%- if tools_in_user_message and not tools is none %} + {#- Extract the first user message so we can plug it in here #} + {%- if messages | length != 0 %} + {%- set first_user_message = messages[0]['content']|trim %} + {%- set messages = messages[1:] %} + {%- else %} + {{- raise_exception("Cannot put tools in the first user message when there's no first user message!") }} +{%- endif %} + {{- '<|start_header_id|>user<|end_header_id|>\n\n' -}} + {{- "Given the following functions, please respond with a JSON for a function call " }} + {{- "with its proper arguments that best answers the given prompt.\n\n" }} + {{- 'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.' }} + {{- "Do not use variables.\n\n" }} + {%- for t in tools %} + {{- t | tojson(indent=4) }} + {{- "\n\n" }} + {%- endfor %} + {{- first_user_message + "<|eot_id|>"}} +{%- endif %} + +{%- for message in messages %} + {%- if not (message.role == 'ipython' or message.role == 'tool' or 'tool_calls' in message) %} + {{- '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n'+ message['content'] | trim + '<|eot_id|>' }} + {%- elif 'tool_calls' in message %} + {%- if not message.tool_calls|length == 1 %} + {{- raise_exception("This model only supports single tool-calls at once!") }} + {%- endif %} + {%- set tool_call = message.tool_calls[0].function %} + {%- if builtin_tools is defined and tool_call.name in builtin_tools %} + {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' -}} + {{- "<|python_tag|>" + tool_call.name + ".call(" }} + {%- for arg_name, arg_val in tool_call.arguments | items %} + {{- arg_name + '="' + arg_val + '"' }} + {%- if not loop.last %} + {{- ", " }} + {%- endif %} + {%- endfor %} + {{- ")" }} + {%- else %} + {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' -}} + {{- '{"name": "' + tool_call.name + '", ' }} + {{- '"parameters": ' }} + {{- tool_call.arguments | tojson }} + {{- "}" }} + {%- endif %} + {%- if builtin_tools is defined %} + {#- This means we're in ipython mode #} + {{- "<|eom_id|>" }} + {%- else %} + {{- "<|eot_id|>" }} + {%- endif %} + {%- elif message.role == "tool" or message.role == "ipython" %} + {{- "<|start_header_id|>ipython<|end_header_id|>\n\n" }} + {%- if message.content is mapping or message.content is iterable %} + {{- message.content | tojson }} + {%- else %} + {{- message.content }} + {%- endif %} + {{- "<|eot_id|>" }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' }} +{%- endif %} diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/llama3_2.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/llama3_2.jinja new file mode 100644 index 0000000000000000000000000000000000000000..1bad6a0f648dccdbec523ca79ba90fbcfc806af0 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/llama3_2.jinja @@ -0,0 +1,93 @@ +{{- bos_token }} +{%- if custom_tools is defined %} + {%- set tools = custom_tools %} +{%- endif %} +{%- if not tools_in_user_message is defined %} + {%- set tools_in_user_message = true %} +{%- endif %} +{%- if not date_string is defined %} + {%- if strftime_now is defined %} + {%- set date_string = strftime_now("%d %b %Y") %} + {%- else %} + {%- set date_string = "26 Jul 2024" %} + {%- endif %} +{%- endif %} +{%- if not tools is defined %} + {%- set tools = none %} +{%- endif %} + +{#- This block extracts the system message, so we can slot it into the right place. #} +{%- if messages[0]['role'] == 'system' %} + {%- set system_message = messages[0]['content']|trim %} + {%- set messages = messages[1:] %} +{%- else %} + {%- set system_message = "" %} +{%- endif %} + +{#- System message #} +{{- "<|start_header_id|>system<|end_header_id|>\n\n" }} +{%- if tools is not none %} + {{- "Environment: ipython\n" }} +{%- endif %} +{{- "Cutting Knowledge Date: December 2023\n" }} +{{- "Today Date: " + date_string + "\n\n" }} +{%- if tools is not none and not tools_in_user_message %} + {{- "You have access to the following functions. To call a function, please respond with JSON for a function call." }} + {{- 'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.' }} + {{- "Do not use variables.\n\n" }} + {%- for t in tools %} + {{- t | tojson(indent=4) }} + {{- "\n\n" }} + {%- endfor %} +{%- endif %} +{{- system_message }} +{{- "<|eot_id|>" }} + +{#- Custom tools are passed in a user message with some extra guidance #} +{%- if tools_in_user_message and not tools is none %} + {#- Extract the first user message so we can plug it in here #} + {%- if messages | length != 0 %} + {%- set first_user_message = messages[0]['content']|trim %} + {%- set messages = messages[1:] %} + {%- else %} + {{- raise_exception("Cannot put tools in the first user message when there's no first user message!") }} +{%- endif %} + {{- '<|start_header_id|>user<|end_header_id|>\n\n' -}} + {{- "Given the following functions, please respond with a JSON for a function call " }} + {{- "with its proper arguments that best answers the given prompt.\n\n" }} + {{- 'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.' }} + {{- "Do not use variables.\n\n" }} + {%- for t in tools %} + {{- t | tojson(indent=4) }} + {{- "\n\n" }} + {%- endfor %} + {{- first_user_message + "<|eot_id|>"}} +{%- endif %} + +{%- for message in messages %} + {%- if not (message.role == 'ipython' or message.role == 'tool' or 'tool_calls' in message) %} + {{- '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n'+ message['content'] | trim + '<|eot_id|>' }} + {%- elif 'tool_calls' in message %} + {%- if not message.tool_calls|length == 1 %} + {{- raise_exception("This model only supports single tool-calls at once!") }} + {%- endif %} + {%- set tool_call = message.tool_calls[0].function %} + {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' -}} + {{- '{"name": "' + tool_call.name + '", ' }} + {{- '"parameters": ' }} + {{- tool_call.arguments | tojson }} + {{- "}" }} + {{- "<|eot_id|>" }} + {%- elif message.role == "tool" or message.role == "ipython" %} + {{- "<|start_header_id|>ipython<|end_header_id|>\n\n" }} + {%- if message.content is mapping or message.content is iterable %} + {{- message.content | tojson }} + {%- else %} + {{- message.content }} + {%- endif %} + {{- "<|eot_id|>" }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' }} +{%- endif %} diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/llama3_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/llama3_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..85dafd3d877c69b48fcebae678a5ba367909afd1 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/llama3_training.jinja @@ -0,0 +1,19 @@ +{#- Training variant of the Llama 3 chat template (see llama3.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{%- for message in messages %} + {%- if loop.index0 == 0 %}{{- bos_token }}{%- endif %} + {%- if message['role'] == 'assistant' %} + {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' }} + {%- generation %} + {{- message['content'] | trim + '<|eot_id|>' }} + {%- endgeneration %} + {%- else %} + {{- '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n' + message['content'] | trim + '<|eot_id|>' }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' }} +{%- endif %} diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/llava_next.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/llava_next.jinja new file mode 100644 index 0000000000000000000000000000000000000000..c6cc6df43113384d5cafa46c06bd1b79ec4464c7 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/llava_next.jinja @@ -0,0 +1,6 @@ +{% for message in messages %}{% if message['role'] == 'system' %}{{ '<> +' + message['content'][0]['text'] + ' +<> + +' }}{% elif message['role'] == 'user' %}{{ '[INST] ' }}{# Render all images first #}{% for content in message['content'] | selectattr('type', 'equalto', 'image') %}{{ ' +' }}{% endfor %}{# Render all text next #}{% for content in message['content'] | selectattr('type', 'equalto', 'text') %}{{ content['text'] }}{% endfor %}{{' [/INST]' }}{% elif message['role'] == 'assistant' %}{{ ' ' + message['content'][0]['text'] + ' '}}{% else %}{{ raise_exception('Only user and assistant roles are supported!') }}{% endif %}{% endfor %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/llava_next_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/llava_next_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..9eaf357439a713fff44832b8892a244cf063a7b6 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/llava_next_training.jinja @@ -0,0 +1,11 @@ +{#- Training variant of the Llava-Next chat template (see llava_next.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around the assistant message output to support + assistant-only loss masking in SFT training. +-#} +{% for message in messages %}{% if message['role'] == 'system' %}{{ '<> +' + message['content'][0]['text'] + ' +<> + +' }}{% elif message['role'] == 'user' %}{{ '[INST] ' }}{# Render all images first #}{% for content in message['content'] | selectattr('type', 'equalto', 'image') %}{{ ' +' }}{% endfor %}{# Render all text next #}{% for content in message['content'] | selectattr('type', 'equalto', 'text') %}{{ content['text'] }}{% endfor %}{{' [/INST]' }}{% elif message['role'] == 'assistant' %}{% generation %}{{ ' ' + message['content'][0]['text'] + ' '}}{% endgeneration %}{% else %}{{ raise_exception('Only user and assistant roles are supported!') }}{% endif %}{% endfor %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/nemotron_3_nano.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/nemotron_3_nano.jinja new file mode 100644 index 0000000000000000000000000000000000000000..67ca3ce54a7118ed74d6fd793b7cc9fd6b2a9f03 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/nemotron_3_nano.jinja @@ -0,0 +1,204 @@ +{% macro render_extra_keys(json_dict, handled_keys) %} + {%- if json_dict is mapping %} + {%- for json_key in json_dict if json_key not in handled_keys %} + {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %} + {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '' }} + {%- else %} + {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '' }} + {%- endif %} + {%- endfor %} + {%- endif %} +{% endmacro %} +{%- set enable_thinking = enable_thinking if enable_thinking is defined else True %} +{%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %} + +{%- set ns = namespace(last_user_idx = -1) %} +{%- set loop_messages = messages %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} + +{%- if messages[0]["role"] == "system" %} + {%- set system_message = messages[0]["content"] %} + {%- set loop_messages = messages[1:] %} +{%- else %} + {%- set system_message = "" %} + {%- set loop_messages = messages %} +{%- endif %} +{%- if not tools is defined %} + {%- set tools = [] %} +{%- endif %} +{# Recompute last_user_idx relative to loop_messages after handling system #} +{%- set ns = namespace(last_user_idx = -1) %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} +{%- if system_message is defined %} + {{- "<|im_start|>system\n" + system_message }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- "<|im_start|>system\n" }} + {%- endif %} +{%- endif %} +{%- if tools is iterable and tools | length > 0 %} + {%- if system_message is defined and system_message | length > 0 %} + {{- "\n\n" }} + {%- endif %} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {{- "" }} + {%- for tool in tools %} + {%- if tool.function is defined %} + {%- set tool = tool.function %} + {%- endif %} + {{- "\n\n" ~ tool.name ~ "" }} + {%- if tool.description is defined %} + {{- '\n' ~ (tool.description | trim) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %} + {%- for param_name, param_fields in tool.parameters.properties|items %} + {{- '\n' }} + {{- '\n' ~ param_name ~ '' }} + {%- if param_fields.type is defined %} + {{- '\n' ~ (param_fields.type | string) ~ '' }} + {%- endif %} + {%- if param_fields.description is defined %} + {{- '\n' ~ (param_fields.description | trim) ~ '' }} + {%- endif %} + {%- if param_fields.enum is defined %} + {{- '\n' ~ (param_fields.enum | tojson | safe) ~ '' }} + {%- endif %} + {%- set handled_keys = ['name', 'type', 'description', 'enum'] %} + {{- render_extra_keys(param_fields, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {% set handled_keys = ['type', 'properties', 'required'] %} + {{- render_extra_keys(tool.parameters, handled_keys) }} + {%- if tool.parameters is defined and tool.parameters.required is defined %} + {{- '\n' ~ (tool.parameters.required | tojson | safe) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %} + {{- render_extra_keys(tool, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {{- "\n" }} + + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} +{%- endif %} + + +{%- if system_message is defined %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- '<|im_end|>\n' }} + {%- endif %} +{%- endif %} + +{%- for message in loop_messages %} + {%- if message.role == "assistant" %} + {# Add reasoning content in to content field for unified processing below. #} + {%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %} + {%- set content = "\n" ~ message.reasoning_content ~ "\n\n" ~ (message.content | default('', true)) %} + {%- else %} + {%- set content = message.content | default('', true) %} + {%- if content is string -%} + {# Allow downstream logic to to take care of broken thought, only handle coherent reasoning here. #} + {%- if '' not in content and '' not in content -%} + {%- set content = "" ~ content -%} + {%- endif -%} + {%- else -%} + {%- set content = content -%} + {%- endif -%} + {%- endif %} + {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %} + {# Assistant message has tool calls. #} + {{- '<|im_start|>assistant\n' }} + {%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {%- if content is string and content | trim | length > 0 %} + {%- if include_content %} + {{- (content | trim) ~ '\n' -}} + {%- else %} + {%- set c = (content | string) %} + {%- if '' in c %} + {# Keep only content after the last closing think. Also generation prompt causes this. #} + {%- set c = c.split('')[-1] %} + {%- elif '' in c %} + {# If was opened but never closed, drop the trailing think segment #} + {%- set c = c.split('')[0] %} + {%- endif %} + {%- set c = "" ~ c | trim %} + {%- if c | length > 0 %} + {{- c ~ '\n' -}} + {%- endif %} + {%- endif %} + {%- else %} + {{- "" -}} + {%- endif %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n\n' -}} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' -}} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value ~ '\n\n' -}} + {%- endfor %} + {%- endif %} + {{- '\n\n' -}} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- else %} + {# Assistant message doesn't have tool calls. #} + {%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {{- '<|im_start|>assistant\n' ~ (content | default('', true) | string | trim) ~ '<|im_end|>\n' }} + {%- else %} + {%- set c = (content | default('', true) | string) %} + {%- if '' in c and '' in c %} + {%- set c = "" ~ c.split('')[-1] %} + {%- endif %} + {%- set c = c | trim %} + {%- if c | length > 0 %} + {{- '<|im_start|>assistant\n' ~ c ~ '<|im_end|>\n' }} + {%- else %} + {{- '<|im_start|>assistant\n<|im_end|>\n' }} + {%- endif %} + {%- endif %} + {%- endif %} + {%- elif message.role == "user" or message.role == "system" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- set content = message.content | string %} + {{- content }} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user\n' }} + {%- endif %} + {{- '\n' }} + {{- message.content }} + {{- '\n\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }} + {%- endif %} +{%- endfor %} + +{%- if add_generation_prompt %} + {%- if enable_thinking %} + {{- '<|im_start|>assistant\n\n' }} + {%- else %} + {{- '<|im_start|>assistant\n' }} + {%- endif %} +{%- endif %} diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/nemotron_3_nano_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/nemotron_3_nano_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..c539b379f51fe7c76586858d70f25ff6220a3729 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/nemotron_3_nano_training.jinja @@ -0,0 +1,220 @@ +{#- Training variant of the Nemotron Nano chat template (see nemotron_3_nano.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{% macro render_extra_keys(json_dict, handled_keys) %} + {%- if json_dict is mapping %} + {%- for json_key in json_dict if json_key not in handled_keys %} + {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %} + {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '' }} + {%- else %} + {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '' }} + {%- endif %} + {%- endfor %} + {%- endif %} +{% endmacro %} +{%- set enable_thinking = enable_thinking if enable_thinking is defined else True %} +{%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %} + +{%- set ns = namespace(last_user_idx = -1) %} +{%- set loop_messages = messages %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} + +{%- if messages[0]["role"] == "system" %} + {%- set system_message = messages[0]["content"] %} + {%- set loop_messages = messages[1:] %} +{%- else %} + {%- set system_message = "" %} + {%- set loop_messages = messages %} +{%- endif %} +{%- if not tools is defined %} + {%- set tools = [] %} +{%- endif %} +{# Recompute last_user_idx relative to loop_messages after handling system #} +{%- set ns = namespace(last_user_idx = -1) %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} +{%- if system_message is defined %} + {{- "<|im_start|>system\n" + system_message }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- "<|im_start|>system\n" }} + {%- endif %} +{%- endif %} +{%- if tools is iterable and tools | length > 0 %} + {%- if system_message is defined and system_message | length > 0 %} + {{- "\n\n" }} + {%- endif %} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {{- "" }} + {%- for tool in tools %} + {%- if tool.function is defined %} + {%- set tool = tool.function %} + {%- endif %} + {{- "\n\n" ~ tool.name ~ "" }} + {%- if tool.description is defined %} + {{- '\n' ~ (tool.description | trim) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %} + {%- for param_name, param_fields in tool.parameters.properties|items %} + {{- '\n' }} + {{- '\n' ~ param_name ~ '' }} + {%- if param_fields.type is defined %} + {{- '\n' ~ (param_fields.type | string) ~ '' }} + {%- endif %} + {%- if param_fields.description is defined %} + {{- '\n' ~ (param_fields.description | trim) ~ '' }} + {%- endif %} + {%- if param_fields.enum is defined %} + {{- '\n' ~ (param_fields.enum | tojson | safe) ~ '' }} + {%- endif %} + {%- set handled_keys = ['name', 'type', 'description', 'enum'] %} + {{- render_extra_keys(param_fields, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {% set handled_keys = ['type', 'properties', 'required'] %} + {{- render_extra_keys(tool.parameters, handled_keys) }} + {%- if tool.parameters is defined and tool.parameters.required is defined %} + {{- '\n' ~ (tool.parameters.required | tojson | safe) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %} + {{- render_extra_keys(tool, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {{- "\n" }} + + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} +{%- endif %} + + +{%- if system_message is defined %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- '<|im_end|>\n' }} + {%- endif %} +{%- endif %} + +{%- for message in loop_messages %} + {%- if message.role == "assistant" %} + {# Add reasoning content in to content field for unified processing below. #} + {%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %} + {%- set content = "\n" ~ message.reasoning_content ~ "\n\n" ~ (message.content | default('', true)) %} + {%- else %} + {%- set content = message.content | default('', true) %} + {%- if content is string -%} + {# Allow downstream logic to to take care of broken thought, only handle coherent reasoning here. #} + {%- if '' not in content and '' not in content -%} + {%- set content = "" ~ content -%} + {%- endif -%} + {%- else -%} + {%- set content = content -%} + {%- endif -%} + {%- endif %} + {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %} + {# Assistant message has tool calls. #} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {%- if content is string and content | trim | length > 0 %} + {%- if include_content %} + {{- (content | trim) ~ '\n' -}} + {%- else %} + {%- set c = (content | string) %} + {%- if '' in c %} + {# Keep only content after the last closing think. Also generation prompt causes this. #} + {%- set c = c.split('')[-1] %} + {%- elif '' in c %} + {# If was opened but never closed, drop the trailing think segment #} + {%- set c = c.split('')[0] %} + {%- endif %} + {%- set c = "" ~ c | trim %} + {%- if c | length > 0 %} + {{- c ~ '\n' -}} + {%- endif %} + {%- endif %} + {%- else %} + {{- "" -}} + {%- endif %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n\n' -}} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' -}} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value ~ '\n\n' -}} + {%- endfor %} + {%- endif %} + {{- '\n\n' -}} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- else %} + {# Assistant message doesn't have tool calls. #} + {%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {{- (content | default('', true) | string | trim) ~ '<|im_end|>\n' }} + {%- endgeneration %} + {%- else %} + {%- set c = (content | default('', true) | string) %} + {%- if '' in c and '' in c %} + {%- set c = "" ~ c.split('')[-1] %} + {%- endif %} + {%- set c = c | trim %} + {%- if c | length > 0 %} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {{- c ~ '<|im_end|>\n' }} + {%- endgeneration %} + {%- else %} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- endif %} + {%- endif %} + {%- endif %} + {%- elif message.role == "user" or message.role == "system" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- set content = message.content | string %} + {{- content }} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user\n' }} + {%- endif %} + {{- '\n' }} + {{- message.content }} + {{- '\n\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }} + {%- endif %} +{%- endfor %} + +{%- if add_generation_prompt %} + {%- if enable_thinking %} + {{- '<|im_start|>assistant\n\n' }} + {%- else %} + {{- '<|im_start|>assistant\n' }} + {%- endif %} +{%- endif %} diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/nemotron_3_super.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/nemotron_3_super.jinja new file mode 100644 index 0000000000000000000000000000000000000000..71935c3a25edcdde07a0b7c4bec26f68bbce73a4 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/nemotron_3_super.jinja @@ -0,0 +1,209 @@ +{% macro render_extra_keys(json_dict, handled_keys) %} + {%- if json_dict is mapping %} + {%- for json_key in json_dict if json_key not in handled_keys %} + {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %} + {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '' }} + {%- else %} + {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '' }} + {%- endif %} + {%- endfor %} + {%- endif %} +{% endmacro %} +{%- set enable_thinking = enable_thinking if enable_thinking is defined else True %} +{%- set low_effort = low_effort if low_effort is defined else False %} +{%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %} + +{%- set ns = namespace(last_user_idx = -1) %} +{%- set loop_messages = messages %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} + +{%- if messages[0]["role"] == "system" %} + {%- set system_message = messages[0]["content"] %} + {%- set loop_messages = messages[1:] %} +{%- else %} + {%- set system_message = "" %} + {%- set loop_messages = messages %} +{%- endif %} +{%- if not tools is defined %} + {%- set tools = [] %} +{%- endif %} +{# Recompute last_user_idx relative to loop_messages after handling system #} +{%- set ns = namespace(last_user_idx = -1) %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} +{%- if system_message is defined %} + {{- "<|im_start|>system\n" + system_message }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- "<|im_start|>system\n" }} + {%- endif %} +{%- endif %} +{%- if tools is iterable and tools | length > 0 %} + {%- if system_message is defined and system_message | length > 0 %} + {{- "\n\n" }} + {%- endif %} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {{- "" }} + {%- for tool in tools %} + {%- if tool.function is defined %} + {%- set tool = tool.function %} + {%- endif %} + {{- "\n\n" ~ tool.name ~ "" }} + {%- if tool.description is defined %} + {{- '\n' ~ (tool.description | trim) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %} + {%- for param_name, param_fields in tool.parameters.properties|items %} + {{- '\n' }} + {{- '\n' ~ param_name ~ '' }} + {%- if param_fields.type is defined %} + {{- '\n' ~ (param_fields.type | string) ~ '' }} + {%- endif %} + {%- if param_fields.description is defined %} + {{- '\n' ~ (param_fields.description | trim) ~ '' }} + {%- endif %} + {%- if param_fields.enum is defined %} + {{- '\n' ~ (param_fields.enum | tojson | safe) ~ '' }} + {%- endif %} + {%- set handled_keys = ['name', 'type', 'description', 'enum'] %} + {{- render_extra_keys(param_fields, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {% set handled_keys = ['type', 'properties', 'required'] %} + {{- render_extra_keys(tool.parameters, handled_keys) }} + {%- if tool.parameters is defined and tool.parameters.required is defined %} + {{- '\n' ~ (tool.parameters.required | tojson | safe) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %} + {{- render_extra_keys(tool, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {{- "\n" }} + + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} +{%- endif %} + + +{%- if system_message is defined %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- '<|im_end|>\n' }} + {%- endif %} +{%- endif %} + +{%- for message in loop_messages %} + {%- if message.role == "assistant" %} + {# Add reasoning content in to content field for unified processing below. #} + {%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %} + {%- set content = "\n" ~ message.reasoning_content ~ "\n\n" ~ (message.content | default('', true)) %} + {%- else %} + {%- set content = message.content | default('', true) %} + {%- if content is string -%} + {# Allow downstream logic to to take care of broken thought, only handle coherent reasoning here. #} + {%- if '' not in content and '' not in content -%} + {%- set content = "" ~ content -%} + {%- endif -%} + {%- else -%} + {%- set content = content -%} + {%- endif -%} + {%- endif %} + {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %} + {# Assistant message has tool calls. #} + {{- '<|im_start|>assistant\n' }} + {%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {%- if content is string and content | trim | length > 0 %} + {%- if include_content %} + {{- (content | trim) ~ '\n' -}} + {%- else %} + {%- set c = (content | string) %} + {%- if '' in c %} + {# Keep only content after the last closing think. Also generation prompt causes this. #} + {%- set c = c.split('')[-1] %} + {%- elif '' in c %} + {# If was opened but never closed, drop the trailing think segment #} + {%- set c = c.split('')[0] %} + {%- endif %} + {%- set c = "" ~ c | trim %} + {%- if c | length > 0 %} + {{- c ~ '\n' -}} + {%- endif %} + {%- endif %} + {%- else %} + {{- "" -}} + {%- endif %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n\n' -}} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' -}} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value ~ '\n\n' -}} + {%- endfor %} + {%- endif %} + {{- '\n\n' -}} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- else %} + {# Assistant message doesn't have tool calls. #} + {%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {{- '<|im_start|>assistant\n' ~ (content | default('', true) | string | trim) ~ '<|im_end|>\n' }} + {%- else %} + {%- set c = (content | default('', true) | string) %} + {%- if '' in c and '' in c %} + {%- set c = "" ~ c.split('')[-1] %} + {%- endif %} + {%- set c = c | trim %} + {%- if c | length > 0 %} + {{- '<|im_start|>assistant\n' ~ c ~ '<|im_end|>\n' }} + {%- else %} + {{- '<|im_start|>assistant\n<|im_end|>\n' }} + {%- endif %} + {%- endif %} + {%- endif %} + {%- elif message.role == "user" or message.role == "system" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- set content = message.content | string %} + {%- if message.role == "user" and loop.index0 == ns.last_user_idx and low_effort %} + {{- content + '\n\n{reasoning effort: low}' }} + {%- else %} + {{- content }} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user\n' }} + {%- endif %} + {{- '\n' }} + {{- message.content }} + {{- '\n\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }} + {%- endif %} +{%- endfor %} + +{%- if add_generation_prompt %} + {%- if enable_thinking %} + {{- '<|im_start|>assistant\n\n' }} + {%- else %} + {{- '<|im_start|>assistant\n' }} + {%- endif %} +{%- endif %} diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/nemotron_3_super_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/nemotron_3_super_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..bcd170998dc60b864b7f9d35b31c7664cf35a546 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/nemotron_3_super_training.jinja @@ -0,0 +1,226 @@ +{#- Training variant of the Nemotron Super chat template (see nemotron_3_super.jinja for the original). + The original is already prefix-preserving, so the only modification is adding + {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. All other rendering (including the + `truncate_history_thinking` and `low_effort` logic) is identical to the original. +-#} +{% macro render_extra_keys(json_dict, handled_keys) %} + {%- if json_dict is mapping %} + {%- for json_key in json_dict if json_key not in handled_keys %} + {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %} + {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '' }} + {%- else %} + {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '' }} + {%- endif %} + {%- endfor %} + {%- endif %} +{% endmacro %} +{%- set enable_thinking = enable_thinking if enable_thinking is defined else True %} +{%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %} +{%- set low_effort = low_effort if low_effort is defined else False %} + +{%- set ns = namespace(last_user_idx = -1) %} +{%- set loop_messages = messages %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} + +{%- if messages[0]["role"] == "system" %} + {%- set system_message = messages[0]["content"] %} + {%- set loop_messages = messages[1:] %} +{%- else %} + {%- set system_message = "" %} + {%- set loop_messages = messages %} +{%- endif %} +{%- if not tools is defined %} + {%- set tools = [] %} +{%- endif %} +{# Recompute last_user_idx relative to loop_messages after handling system #} +{%- set ns = namespace(last_user_idx = -1) %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} +{%- if system_message is defined %} + {{- "<|im_start|>system\n" + system_message }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- "<|im_start|>system\n" }} + {%- endif %} +{%- endif %} +{%- if tools is iterable and tools | length > 0 %} + {%- if system_message is defined and system_message | length > 0 %} + {{- "\n\n" }} + {%- endif %} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {{- "" }} + {%- for tool in tools %} + {%- if tool.function is defined %} + {%- set tool = tool.function %} + {%- endif %} + {{- "\n\n" ~ tool.name ~ "" }} + {%- if tool.description is defined %} + {{- '\n' ~ (tool.description | trim) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %} + {%- for param_name, param_fields in tool.parameters.properties|items %} + {{- '\n' }} + {{- '\n' ~ param_name ~ '' }} + {%- if param_fields.type is defined %} + {{- '\n' ~ (param_fields.type | string) ~ '' }} + {%- endif %} + {%- if param_fields.description is defined %} + {{- '\n' ~ (param_fields.description | trim) ~ '' }} + {%- endif %} + {%- if param_fields.enum is defined %} + {{- '\n' ~ (param_fields.enum | tojson | safe) ~ '' }} + {%- endif %} + {%- set handled_keys = ['name', 'type', 'description', 'enum'] %} + {{- render_extra_keys(param_fields, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {% set handled_keys = ['type', 'properties', 'required'] %} + {{- render_extra_keys(tool.parameters, handled_keys) }} + {%- if tool.parameters is defined and tool.parameters.required is defined %} + {{- '\n' ~ (tool.parameters.required | tojson | safe) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %} + {{- render_extra_keys(tool, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {{- "\n" }} + + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} +{%- endif %} + + +{%- if system_message is defined %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- '<|im_end|>\n' }} + {%- endif %} +{%- endif %} + +{%- for message in loop_messages %} + {%- if message.role == "assistant" %} + {# Add reasoning content in to content field for unified processing below. #} + {%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %} + {%- set content = "\n" ~ message.reasoning_content ~ "\n\n" ~ (message.content | default('', true)) %} + {%- else %} + {%- set content = message.content | default('', true) %} + {%- if content is string -%} + {# Allow downstream logic to to take care of broken thought, only handle coherent reasoning here. #} + {%- if '' not in content and '' not in content -%} + {%- set content = "" ~ content -%} + {%- endif -%} + {%- else -%} + {%- set content = content -%} + {%- endif -%} + {%- endif %} + {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %} + {# Assistant message has tool calls. #} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {%- if content is string and content | trim | length > 0 %} + {%- if include_content %} + {{- (content | trim) ~ '\n' -}} + {%- else %} + {%- set c = (content | string) %} + {%- if '' in c %} + {# Keep only content after the last closing think. Also generation prompt causes this. #} + {%- set c = c.split('')[-1] %} + {%- elif '' in c %} + {# If was opened but never closed, drop the trailing think segment #} + {%- set c = c.split('')[0] %} + {%- endif %} + {%- set c = "" ~ c | trim %} + {%- if c | length > 0 %} + {{- c ~ '\n' -}} + {%- endif %} + {%- endif %} + {%- else %} + {{- "" -}} + {%- endif %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n\n' -}} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' -}} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value ~ '\n\n' -}} + {%- endfor %} + {%- endif %} + {{- '\n\n' -}} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- else %} + {# Assistant message doesn't have tool calls. #} + {%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {{- (content | default('', true) | string | trim) ~ '<|im_end|>\n' }} + {%- endgeneration %} + {%- else %} + {%- set c = (content | default('', true) | string) %} + {%- if '' in c and '' in c %} + {%- set c = "" ~ c.split('')[-1] %} + {%- endif %} + {%- set c = c | trim %} + {%- if c | length > 0 %} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {{- c ~ '<|im_end|>\n' }} + {%- endgeneration %} + {%- else %} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- endif %} + {%- endif %} + {%- endif %} + {%- elif message.role == "user" or message.role == "system" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- set content = message.content | string %} + {%- if message.role == "user" and loop.index0 == ns.last_user_idx and low_effort %} + {{- content + '\n\n{reasoning effort: low}' }} + {%- else %} + {{- content }} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user\n' }} + {%- endif %} + {{- '\n' }} + {{- message.content }} + {{- '\n\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }} + {%- endif %} +{%- endfor %} + +{%- if add_generation_prompt %} + {%- if enable_thinking %} + {{- '<|im_start|>assistant\n\n' }} + {%- else %} + {{- '<|im_start|>assistant\n' }} + {%- endif %} +{%- endif %} diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/nemotron_3_ultra.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/nemotron_3_ultra.jinja new file mode 100644 index 0000000000000000000000000000000000000000..7afbeb759a6786de17cde07485f9c2db387fd94d --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/nemotron_3_ultra.jinja @@ -0,0 +1,195 @@ +{% macro render_extra_keys(json_dict, handled_keys) %} + {%- if json_dict is mapping %} + {%- for json_key in json_dict if json_key not in handled_keys %} + {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %} + {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '' }} + {%- else %} + {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '' }} + {%- endif %} + {%- endfor %} + {%- endif %} +{% endmacro %} +{%- set enable_thinking = enable_thinking if enable_thinking is defined else True %} +{%- set medium_effort = medium_effort if medium_effort is defined else False %} +{%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %} +{%- set ns = namespace(last_user_idx = -1) %} +{%- set loop_messages = messages %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} +{%- if messages[0]["role"] == "system" %} + {%- set system_message = messages[0]["content"] %} + {%- set loop_messages = messages[1:] %} +{%- else %} + {%- set system_message = "" %} + {%- set loop_messages = messages %} +{%- endif %} +{%- if not tools is defined %} + {%- set tools = [] %} +{%- endif %} +{%- set ns = namespace(last_user_idx = -1) %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} +{%- if system_message is defined %} + {{- "<|im_start|>system\n" + system_message }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- "<|im_start|>system\n" }} + {%- endif %} +{%- endif %} +{%- if tools is iterable and tools | length > 0 %} + {%- if system_message is defined and system_message | length > 0 %} + {{- "\n\n" }} + {%- endif %} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {{- "" }} + {%- for tool in tools %} + {%- if tool.function is defined %} + {%- set tool = tool.function %} + {%- endif %} + {{- "\n\n" ~ tool.name ~ "" }} + {%- if tool.description is defined %} + {{- '\n' ~ (tool.description | trim) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %} + {%- for param_name, param_fields in tool.parameters.properties|items %} + {{- '\n' }} + {{- '\n' ~ param_name ~ '' }} + {%- if param_fields.type is defined %} + {{- '\n' ~ (param_fields.type | string) ~ '' }} + {%- endif %} + {%- if param_fields.description is defined %} + {{- '\n' ~ (param_fields.description | trim) ~ '' }} + {%- endif %} + {%- if param_fields.enum is defined %} + {{- '\n' ~ (param_fields.enum | tojson | safe) ~ '' }} + {%- endif %} + {%- set handled_keys = ['name', 'type', 'description', 'enum'] %} + {{- render_extra_keys(param_fields, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {% set handled_keys = ['type', 'properties', 'required'] %} + {{- render_extra_keys(tool.parameters, handled_keys) }} + {%- if tool.parameters is defined and tool.parameters.required is defined %} + {{- '\n' ~ (tool.parameters.required | tojson | safe) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %} + {{- render_extra_keys(tool, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} +{%- endif %} +{%- if system_message is defined %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- for message in loop_messages %} + {%- if message.role == "assistant" %} + {%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %} + {%- set content = "\n" ~ message.reasoning_content ~ "" ~ (message.content | default('', true)) %} + {%- else %} + {%- set content = message.content | default('', true) %} + {%- if content is string -%} + {%- if '' not in content and '' not in content -%} + {%- set content = "" ~ content -%} + {%- endif -%} + {%- else -%} + {%- set content = content -%} + {%- endif -%} + {%- endif %} + {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %} + {{- '<|im_start|>assistant\n' }} + {%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {%- if content is string and content | trim | length > 0 %} + {%- if include_content %} + {{- (content | trim) ~ '\n' -}} + {%- else %} + {%- set c = (content | string) %} + {%- if '' in c %} + {%- set c = c.split('')[-1] %} + {%- elif '' in c %} + {%- set c = c.split('')[0] %} + {%- endif %} + {%- set c = "" ~ c %} + {%- if c | length > 0 %} + {{- c ~ '\n' -}} + {%- endif %} + {%- endif %} + {%- else %} + {{- "" -}} + {%- endif %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n\n' -}} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' -}} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value ~ '\n\n' -}} + {%- endfor %} + {%- endif %} + {{- '\n\n' -}} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- else %} + {%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {{- '<|im_start|>assistant\n' ~ (content | default('', true) | string | trim) ~ '<|im_end|>\n' }} + {%- else %} + {%- set c = (content | default('', true) | string) %} + {%- if '' in c and '' in c %} + {%- set c = "" ~ c.split('')[-1] %} + {%- endif %} + {%- set c = c | trim %} + {%- if c | length > 0 %} + {{- '<|im_start|>assistant\n' ~ c ~ '<|im_end|>\n' }} + {%- else %} + {{- '<|im_start|>assistant\n<|im_end|>\n' }} + {%- endif %} + {%- endif %} + {%- endif %} + {%- elif message.role == "user" or message.role == "system" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- set content = message.content | string %} + {%- if message.role == "user" and loop.index0 == ns.last_user_idx and medium_effort %} + {{- content + '\n\n{reasoning effort: efficient}' }} + {%- else %} + {{- content }} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user\n' }} + {%- endif %} + {{- '\n' }} + {{- message.content }} + {{- '\n\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {%- if enable_thinking %} + {{- '<|im_start|>assistant\n\n' }} + {%- else %} + {{- '<|im_start|>assistant\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/nemotron_3_ultra_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/nemotron_3_ultra_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..12a52d22e4c38c67a6a98b5b396e134ad3de94f8 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/nemotron_3_ultra_training.jinja @@ -0,0 +1,212 @@ +{#- Training variant of the Nemotron Ultra chat template (see nemotron_3_ultra.jinja for the original). + The original is already prefix-preserving, so the only modification is adding + {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. All other rendering (including the + `truncate_history_thinking` and `medium_effort` logic) is identical to the original. +-#} +{% macro render_extra_keys(json_dict, handled_keys) %} + {%- if json_dict is mapping %} + {%- for json_key in json_dict if json_key not in handled_keys %} + {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %} + {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '' }} + {%- else %} + {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '' }} + {%- endif %} + {%- endfor %} + {%- endif %} +{% endmacro %} +{%- set enable_thinking = enable_thinking if enable_thinking is defined else True %} +{%- set medium_effort = medium_effort if medium_effort is defined else False %} +{%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %} +{%- set ns = namespace(last_user_idx = -1) %} +{%- set loop_messages = messages %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} +{%- if messages[0]["role"] == "system" %} + {%- set system_message = messages[0]["content"] %} + {%- set loop_messages = messages[1:] %} +{%- else %} + {%- set system_message = "" %} + {%- set loop_messages = messages %} +{%- endif %} +{%- if not tools is defined %} + {%- set tools = [] %} +{%- endif %} +{%- set ns = namespace(last_user_idx = -1) %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} +{%- if system_message is defined %} + {{- "<|im_start|>system\n" + system_message }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- "<|im_start|>system\n" }} + {%- endif %} +{%- endif %} +{%- if tools is iterable and tools | length > 0 %} + {%- if system_message is defined and system_message | length > 0 %} + {{- "\n\n" }} + {%- endif %} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {{- "" }} + {%- for tool in tools %} + {%- if tool.function is defined %} + {%- set tool = tool.function %} + {%- endif %} + {{- "\n\n" ~ tool.name ~ "" }} + {%- if tool.description is defined %} + {{- '\n' ~ (tool.description | trim) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %} + {%- for param_name, param_fields in tool.parameters.properties|items %} + {{- '\n' }} + {{- '\n' ~ param_name ~ '' }} + {%- if param_fields.type is defined %} + {{- '\n' ~ (param_fields.type | string) ~ '' }} + {%- endif %} + {%- if param_fields.description is defined %} + {{- '\n' ~ (param_fields.description | trim) ~ '' }} + {%- endif %} + {%- if param_fields.enum is defined %} + {{- '\n' ~ (param_fields.enum | tojson | safe) ~ '' }} + {%- endif %} + {%- set handled_keys = ['name', 'type', 'description', 'enum'] %} + {{- render_extra_keys(param_fields, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {% set handled_keys = ['type', 'properties', 'required'] %} + {{- render_extra_keys(tool.parameters, handled_keys) }} + {%- if tool.parameters is defined and tool.parameters.required is defined %} + {{- '\n' ~ (tool.parameters.required | tojson | safe) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %} + {{- render_extra_keys(tool, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} +{%- endif %} +{%- if system_message is defined %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- for message in loop_messages %} + {%- if message.role == "assistant" %} + {%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %} + {%- set content = "\n" ~ message.reasoning_content ~ "" ~ (message.content | default('', true)) %} + {%- else %} + {%- set content = message.content | default('', true) %} + {%- if content is string -%} + {%- if '' not in content and '' not in content -%} + {%- set content = "" ~ content -%} + {%- endif -%} + {%- else -%} + {%- set content = content -%} + {%- endif -%} + {%- endif %} + {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {%- if content is string and content | trim | length > 0 %} + {%- if include_content %} + {{- (content | trim) ~ '\n' -}} + {%- else %} + {%- set c = (content | string) %} + {%- if '' in c %} + {%- set c = c.split('')[-1] %} + {%- elif '' in c %} + {%- set c = c.split('')[0] %} + {%- endif %} + {%- set c = "" ~ c %} + {%- if c | length > 0 %} + {{- c ~ '\n' -}} + {%- endif %} + {%- endif %} + {%- else %} + {{- "" -}} + {%- endif %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n\n' -}} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' -}} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value ~ '\n\n' -}} + {%- endfor %} + {%- endif %} + {{- '\n\n' -}} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- else %} + {%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {{- (content | default('', true) | string | trim) ~ '<|im_end|>\n' }} + {%- endgeneration %} + {%- else %} + {%- set c = (content | default('', true) | string) %} + {%- if '' in c and '' in c %} + {%- set c = "" ~ c.split('')[-1] %} + {%- endif %} + {%- set c = c | trim %} + {%- if c | length > 0 %} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {{- c ~ '<|im_end|>\n' }} + {%- endgeneration %} + {%- else %} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- endif %} + {%- endif %} + {%- endif %} + {%- elif message.role == "user" or message.role == "system" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- set content = message.content | string %} + {%- if message.role == "user" and loop.index0 == ns.last_user_idx and medium_effort %} + {{- content + '\n\n{reasoning effort: efficient}' }} + {%- else %} + {{- content }} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user\n' }} + {%- endif %} + {{- '\n' }} + {{- message.content }} + {{- '\n\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {%- if enable_thinking %} + {{- '<|im_start|>assistant\n\n' }} + {%- else %} + {{- '<|im_start|>assistant\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/phi3.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/phi3.jinja new file mode 100644 index 0000000000000000000000000000000000000000..ddb5006baa8ee6aa317c5d84827e6993469c2073 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/phi3.jinja @@ -0,0 +1,8 @@ +{% for message in messages %}{% if message['role'] == 'system' %}{{'<|system|> +' + message['content'] + '<|end|> +'}}{% elif message['role'] == 'user' %}{{'<|user|> +' + message['content'] + '<|end|> +'}}{% elif message['role'] == 'assistant' %}{{'<|assistant|> +' + message['content'] + '<|end|> +'}}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|assistant|> +' }}{% else %}{{ eos_token }}{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/phi3_5.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/phi3_5.jinja new file mode 100644 index 0000000000000000000000000000000000000000..d1533d1526b2e42fccd99477a7274dc20b7a189b --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/phi3_5.jinja @@ -0,0 +1,8 @@ +{% for message in messages %}{% if message['role'] == 'system' and message['content'] %}{{'<|system|> +' + message['content'] + '<|end|> +'}}{% elif message['role'] == 'user' %}{{'<|user|> +' + message['content'] + '<|end|> +'}}{% elif message['role'] == 'assistant' %}{{'<|assistant|> +' + message['content'] + '<|end|> +'}}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|assistant|> +' }}{% else %}{{ eos_token }}{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/phi3_5_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/phi3_5_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..61d15d77936bc8ebbf965f4478185e9b4233caad --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/phi3_5_training.jinja @@ -0,0 +1,26 @@ +{#- Training variant of the Phi-3.5 chat template (see phi3_5.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{%- for message in messages %} + {%- if message['role'] == 'system' and message['content'] %} + {{- '<|system|>\n' + message['content'] + '<|end|>\n' }} + {%- elif message['role'] == 'user' %} + {{- '<|user|>\n' + message['content'] + '<|end|>\n'}} + {%- elif message['role'] == 'assistant' %} + {{- '<|assistant|>\n' }} + {%- generation %} + {{- message['content'] + '<|end|>\n' }} + {%- endgeneration %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|assistant|>\n'}} +{%- elif messages[-1]['role'] == 'assistant' %} + {%- generation %} + {{- eos_token }} + {%- endgeneration %} +{%- else %} + {{- eos_token }} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/phi3_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/phi3_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..1536d152f7de385ed29917e463bb0aba66977eb3 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/phi3_training.jinja @@ -0,0 +1,26 @@ +{#- Training variant of the Phi-3 chat template (see phi3.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{%- for message in messages %} + {%- if message['role'] == 'system' %} + {{- '<|system|>\n' + message['content'] + '<|end|>\n' }} + {%- elif message['role'] == 'user' %} + {{- '<|user|>\n' + message['content'] + '<|end|>\n' }} + {%- elif message['role'] == 'assistant' %} + {{- '<|assistant|>\n' }} + {%- generation %} + {{- message['content'] + '<|end|>\n' }} + {%- endgeneration %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|assistant|>\n' }} +{%- elif messages[-1]['role'] == 'assistant' %} + {%- generation %} + {{- eos_token }} + {%- endgeneration %} +{%- else %} + {{- eos_token }} +{%- endif %} diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen2_5.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen2_5.jinja new file mode 100644 index 0000000000000000000000000000000000000000..bdf7919a96cfe43d50914a007b9c0877bd0ec27e --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen2_5.jinja @@ -0,0 +1,54 @@ +{%- if tools %} + {{- '<|im_start|>system\n' }} + {%- if messages[0]['role'] == 'system' %} + {{- messages[0]['content'] }} + {%- else %} + {{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }} + {%- endif %} + {{- "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n<|im_end|>\n" }} +{%- else %} + {%- if messages[0]['role'] == 'system' %} + {{- '<|im_start|>system\n' + messages[0]['content'] + '<|im_end|>\n' }} + {%- else %} + {{- '<|im_start|>system\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- for message in messages %} + {%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) %} + {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {{- '<|im_start|>' + message.role }} + {%- if message.content %} + {{- '\n' + message.content }} + {%- endif %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n\n{"name": "' }} + {{- tool_call.name }} + {{- '", "arguments": ' }} + {{- tool_call.arguments | tojson }} + {{- '}\n' }} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- message.content }} + {{- '\n' }} + {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} +{%- endif %} diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen2_5_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen2_5_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..fd7258ece606cb8b6b59a3fb28904282f6004ac4 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen2_5_training.jinja @@ -0,0 +1,65 @@ +{#- Training variant of the Qwen2.5 chat template (see qwen2_5.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{%- if tools %} + {{- '<|im_start|>system\n' }} + {%- if messages[0]['role'] == 'system' %} + {{- messages[0]['content'] }} + {%- else %} + {{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }} + {%- endif %} + {{- "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n<|im_end|>\n" }} +{%- else %} + {%- if messages[0]['role'] == 'system' %} + {{- '<|im_start|>system\n' + messages[0]['content'] + '<|im_end|>\n' }} + {%- else %} + {{- '<|im_start|>system\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- for message in messages %} + {%- if (message.role == "user") or (message.role == "system" and not loop.first) %} + {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {{- '<|im_start|>assistant' }} + {%- generation %} + {%- if not message.tool_calls %} + {{- '\n' + message.content + '<|im_end|>\n' }} + {%- else %} + {%- if message.content %} + {{- '\n' + message.content }} + {%- endif %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n\n{"name": "' }} + {{- tool_call.name }} + {{- '", "arguments": ' }} + {{- tool_call.arguments | tojson }} + {{- '}\n' }} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endgeneration %} + {%- elif message.role == "tool" %} + {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- message.content }} + {{- '\n' }} + {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} +{%- endif %} diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen2_5_vl.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen2_5_vl.jinja new file mode 100644 index 0000000000000000000000000000000000000000..6c226632394ae7474b0d4b13e15793eac2e21ee9 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen2_5_vl.jinja @@ -0,0 +1,7 @@ +{% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system +You are a helpful assistant.<|im_end|> +{% endif %}<|im_start|>{{ message['role'] }} +{% if message['content'] is string %}{{ message['content'] }}<|im_end|> +{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}Picture {{ image_count.value }}: {% endif %}<|vision_start|><|image_pad|><|vision_end|>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}Video {{ video_count.value }}: {% endif %}<|vision_start|><|video_pad|><|vision_end|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|> +{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant +{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen2_5_vl_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen2_5_vl_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..46e34469a34f03fa8c12b7535307cc189997d14b --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen2_5_vl_training.jinja @@ -0,0 +1,63 @@ +{#- Training variant of the Qwen 2.5 VL chat template (see qwen2_5_vl.jinja for the original). + Also used for Qwen 2 VL, which ships a byte-identical chat template. + Modifications vs the original: + - Split the assistant message into its own branch so the {% generation %} / {% endgeneration %} + markers wrap the assistant content (everything after the '<|im_start|>assistant\n' prompt + cue, up to and including the trailing '<|im_end|>\n'). This enables assistant-only loss + masking in SFT training. +-#} +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- for message in messages %} + {%- if loop.first and message['role'] != 'system' %} + {{- '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }} + {%- endif %} + {%- if message['role'] == 'assistant' %} + {{- '<|im_start|>assistant\n' }} + {%- generation -%} + {%- if message['content'] is string %} + {{- message['content'] }} + {{- '<|im_end|>\n' }} + {%- else %} + {%- for content in message['content'] %} + {%- if content['type'] == 'image' or 'image' in content or 'image_url' in content %} + {%- set image_count.value = image_count.value + 1 %} + {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%} + <|vision_start|><|image_pad|><|vision_end|> + {%- elif content['type'] == 'video' or 'video' in content %} + {%- set video_count.value = video_count.value + 1 %} + {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%} + <|vision_start|><|video_pad|><|vision_end|> + {%- elif 'text' in content %} + {{- content['text'] }} + {%- endif %} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endgeneration -%} + {%- else %} + {{- '<|im_start|>' + message['role'] + '\n' }} + {%- if message['content'] is string %} + {{- message['content'] }} + {{- '<|im_end|>\n' }} + {%- else %} + {%- for content in message['content'] %} + {%- if content['type'] == 'image' or 'image' in content or 'image_url' in content %} + {%- set image_count.value = image_count.value + 1 %} + {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%} + <|vision_start|><|image_pad|><|vision_end|> + {%- elif content['type'] == 'video' or 'video' in content %} + {%- set video_count.value = video_count.value + 1 %} + {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%} + <|vision_start|><|video_pad|><|vision_end|> + {%- elif 'text' in content %} + {{- content['text'] }} + {%- endif %} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3.jinja new file mode 100644 index 0000000000000000000000000000000000000000..01be9b307daa2d425f7c168c9fb145a286e0afb4 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3.jinja @@ -0,0 +1,89 @@ +{%- if tools %} + {{- '<|im_start|>system\n' }} + {%- if messages[0].role == 'system' %} + {{- messages[0].content + '\n\n' }} + {%- endif %} + {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n<|im_end|>\n" }} +{%- else %} + {%- if messages[0].role == 'system' %} + {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('') and message.content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} +{%- endfor %} +{%- for message in messages %} + {%- if message.content is string %} + {%- set content = message.content %} + {%- else %} + {%- set content = '' %} + {%- endif %} + {%- if (message.role == "user") or (message.role == "system" and not loop.first) %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {%- if loop.index0 > ns.last_query_index %} + {%- if loop.last or (not loop.last and reasoning_content) %} + {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content.strip('\n') + '\n\n\n' + content.lstrip('\n') }} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- endif %} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- endif %} + {%- if message.tool_calls %} + {%- for tool_call in message.tool_calls %} + {%- if (loop.first and content) or (not loop.first) %} + {{- '\n' }} + {%- endif %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n{"name": "' }} + {{- tool_call.name }} + {{- '", "arguments": ' }} + {%- if tool_call.arguments is string %} + {{- tool_call.arguments }} + {%- else %} + {{- tool_call.arguments | tojson }} + {%- endif %} + {{- '}\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n\n\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_5_nothink.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_5_nothink.jinja new file mode 100644 index 0000000000000000000000000000000000000000..0ef09f214eaa6d9bca297988afc1454b5827b2c7 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_5_nothink.jinja @@ -0,0 +1,154 @@ +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- macro render_content(content, do_vision_count, is_system_content=false) %} + {%- if content is string %} + {{- content }} + {%- elif content is iterable and content is not mapping %} + {%- for item in content %} + {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain images.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set image_count.value = image_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Picture ' ~ image_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|image_pad|><|vision_end|>' }} + {%- elif 'video' in item or item.type == 'video' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain videos.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set video_count.value = video_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Video ' ~ video_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|video_pad|><|vision_end|>' }} + {%- elif 'text' in item %} + {{- item.text }} + {%- else %} + {{- raise_exception('Unexpected item type in content.') }} + {%- endif %} + {%- endfor %} + {%- elif content is none or content is undefined %} + {{- '' }} + {%- else %} + {{- raise_exception('Unexpected content type.') }} + {%- endif %} +{%- endmacro %} +{%- if not messages %} + {{- raise_exception('No messages provided.') }} +{%- endif %} +{%- if tools and tools is iterable and tools is not mapping %} + {{- '<|im_start|>system\n' }} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {%- if content %} + {{- '\n\n' + content }} + {%- endif %} + {%- endif %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" %} + {%- set content = render_content(message.content, false)|trim %} + {%- if not(content.startswith('') and content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if ns.multi_step_tool %} + {{- raise_exception('No user query found in messages.') }} +{%- endif %} +{%- for message in messages %} + {%- set content = render_content(message.content, true)|trim %} + {%- if message.role == "system" %} + {%- if not loop.first %} + {{- raise_exception('System message must be at the beginning.') }} + {%- endif %} + {%- elif message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {%- set reasoning_content = reasoning_content|trim %} + {%- if loop.index0 > ns.last_query_index %} + {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content + '\n\n\n' + content }} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- endif %} + {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if loop.first %} + {%- if content|trim %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n\n' }} + {%- endif %} + {%- else %} + {{- '\n\n\n' }} + {%- endif %} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' }} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value }} + {{- '\n\n' }} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- raise_exception('Unexpected message role.') }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is true %} + {{- '\n' }} + {%- else %} + {{- '\n\n\n\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_5_nothink_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_5_nothink_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..a5bde154d92c83eb794470601ac82a1b22b5b938 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_5_nothink_training.jinja @@ -0,0 +1,162 @@ +{#- Training variant of the Qwen3.5 chat template, NoThink flavor (see qwen3_5_nothink.jinja for the original). + Modifications vs the original: + - {%- if '' in content %} → {%- if '' in content and '' in content %} + Always check for both tags to avoid edge cases where the model generates only one tag. + - Removed the loop.index0 > ns.last_query_index conditional; always include thinking block. + This makes the template prefix-preserving for the [user, assistant] → [user, assistant, tool] transition. + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- macro render_content(content, do_vision_count, is_system_content=false) %} + {%- if content is string %} + {{- content }} + {%- elif content is iterable and content is not mapping %} + {%- for item in content %} + {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain images.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set image_count.value = image_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Picture ' ~ image_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|image_pad|><|vision_end|>' }} + {%- elif 'video' in item or item.type == 'video' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain videos.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set video_count.value = video_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Video ' ~ video_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|video_pad|><|vision_end|>' }} + {%- elif 'text' in item %} + {{- item.text }} + {%- else %} + {{- raise_exception('Unexpected item type in content.') }} + {%- endif %} + {%- endfor %} + {%- elif content is none or content is undefined %} + {{- '' }} + {%- else %} + {{- raise_exception('Unexpected content type.') }} + {%- endif %} +{%- endmacro %} +{%- if not messages %} + {{- raise_exception('No messages provided.') }} +{%- endif %} +{%- if tools and tools is iterable and tools is not mapping %} + {{- '<|im_start|>system\n' }} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {%- if content %} + {{- '\n\n' + content }} + {%- endif %} + {%- endif %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" %} + {%- set content = render_content(message.content, false)|trim %} + {%- if not(content.startswith('') and content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if ns.multi_step_tool %} + {{- raise_exception('No user query found in messages.') }} +{%- endif %} +{%- for message in messages %} + {%- set content = render_content(message.content, true)|trim %} + {%- if message.role == "system" %} + {%- if not loop.first %} + {{- raise_exception('System message must be at the beginning.') }} + {%- endif %} + {%- elif message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content and '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {%- set reasoning_content = reasoning_content|trim %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- generation %} + {{- '\n' + reasoning_content + '\n\n\n' + content }} + {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if loop.first %} + {%- if content|trim %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n\n' }} + {%- endif %} + {%- else %} + {{- '\n\n\n' }} + {%- endif %} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' }} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value }} + {{- '\n\n' }} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- raise_exception('Unexpected message role.') }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is true %} + {{- '\n' }} + {%- else %} + {{- '\n\n\n\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_5_think.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_5_think.jinja new file mode 100644 index 0000000000000000000000000000000000000000..a585dec894e63da457d9440ec6aa7caa16d20860 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_5_think.jinja @@ -0,0 +1,154 @@ +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- macro render_content(content, do_vision_count, is_system_content=false) %} + {%- if content is string %} + {{- content }} + {%- elif content is iterable and content is not mapping %} + {%- for item in content %} + {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain images.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set image_count.value = image_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Picture ' ~ image_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|image_pad|><|vision_end|>' }} + {%- elif 'video' in item or item.type == 'video' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain videos.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set video_count.value = video_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Video ' ~ video_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|video_pad|><|vision_end|>' }} + {%- elif 'text' in item %} + {{- item.text }} + {%- else %} + {{- raise_exception('Unexpected item type in content.') }} + {%- endif %} + {%- endfor %} + {%- elif content is none or content is undefined %} + {{- '' }} + {%- else %} + {{- raise_exception('Unexpected content type.') }} + {%- endif %} +{%- endmacro %} +{%- if not messages %} + {{- raise_exception('No messages provided.') }} +{%- endif %} +{%- if tools and tools is iterable and tools is not mapping %} + {{- '<|im_start|>system\n' }} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {%- if content %} + {{- '\n\n' + content }} + {%- endif %} + {%- endif %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" %} + {%- set content = render_content(message.content, false)|trim %} + {%- if not(content.startswith('') and content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if ns.multi_step_tool %} + {{- raise_exception('No user query found in messages.') }} +{%- endif %} +{%- for message in messages %} + {%- set content = render_content(message.content, true)|trim %} + {%- if message.role == "system" %} + {%- if not loop.first %} + {{- raise_exception('System message must be at the beginning.') }} + {%- endif %} + {%- elif message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {%- set reasoning_content = reasoning_content|trim %} + {%- if loop.index0 > ns.last_query_index %} + {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content + '\n\n\n' + content }} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- endif %} + {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if loop.first %} + {%- if content|trim %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n\n' }} + {%- endif %} + {%- else %} + {{- '\n\n\n' }} + {%- endif %} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' }} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value }} + {{- '\n\n' }} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- raise_exception('Unexpected message role.') }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_5_think_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_5_think_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..fb4b811d6ae3c583b7e7144ace7789f8c07ca10b --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_5_think_training.jinja @@ -0,0 +1,162 @@ +{#- Training variant of the Qwen3.5 chat template, Think flavor (see qwen3_5_think.jinja for the original). + Modifications vs the original: + - {%- if '' in content %} → {%- if '' in content and '' in content %} + Always check for both tags to avoid edge cases where the model generates only one tag. + - Removed the loop.index0 > ns.last_query_index conditional; always include thinking block. + This makes the template prefix-preserving for the [user, assistant] → [user, assistant, tool] transition. + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- macro render_content(content, do_vision_count, is_system_content=false) %} + {%- if content is string %} + {{- content }} + {%- elif content is iterable and content is not mapping %} + {%- for item in content %} + {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain images.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set image_count.value = image_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Picture ' ~ image_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|image_pad|><|vision_end|>' }} + {%- elif 'video' in item or item.type == 'video' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain videos.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set video_count.value = video_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Video ' ~ video_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|video_pad|><|vision_end|>' }} + {%- elif 'text' in item %} + {{- item.text }} + {%- else %} + {{- raise_exception('Unexpected item type in content.') }} + {%- endif %} + {%- endfor %} + {%- elif content is none or content is undefined %} + {{- '' }} + {%- else %} + {{- raise_exception('Unexpected content type.') }} + {%- endif %} +{%- endmacro %} +{%- if not messages %} + {{- raise_exception('No messages provided.') }} +{%- endif %} +{%- if tools and tools is iterable and tools is not mapping %} + {{- '<|im_start|>system\n' }} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {%- if content %} + {{- '\n\n' + content }} + {%- endif %} + {%- endif %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" %} + {%- set content = render_content(message.content, false)|trim %} + {%- if not(content.startswith('') and content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if ns.multi_step_tool %} + {{- raise_exception('No user query found in messages.') }} +{%- endif %} +{%- for message in messages %} + {%- set content = render_content(message.content, true)|trim %} + {%- if message.role == "system" %} + {%- if not loop.first %} + {{- raise_exception('System message must be at the beginning.') }} + {%- endif %} + {%- elif message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content and '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {%- set reasoning_content = reasoning_content|trim %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- generation %} + {{- '\n' + reasoning_content + '\n\n\n' + content }} + {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if loop.first %} + {%- if content|trim %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n\n' }} + {%- endif %} + {%- else %} + {{- '\n\n\n' }} + {%- endif %} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' }} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value }} + {{- '\n\n' }} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- raise_exception('Unexpected message role.') }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_6.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_6.jinja new file mode 100644 index 0000000000000000000000000000000000000000..a8755d827c0a7b614c246c4060dfd58ab352a8ff --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_6.jinja @@ -0,0 +1,154 @@ +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- macro render_content(content, do_vision_count, is_system_content=false) %} + {%- if content is string %} + {{- content }} + {%- elif content is iterable and content is not mapping %} + {%- for item in content %} + {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain images.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set image_count.value = image_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Picture ' ~ image_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|image_pad|><|vision_end|>' }} + {%- elif 'video' in item or item.type == 'video' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain videos.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set video_count.value = video_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Video ' ~ video_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|video_pad|><|vision_end|>' }} + {%- elif 'text' in item %} + {{- item.text }} + {%- else %} + {{- raise_exception('Unexpected item type in content.') }} + {%- endif %} + {%- endfor %} + {%- elif content is none or content is undefined %} + {{- '' }} + {%- else %} + {{- raise_exception('Unexpected content type.') }} + {%- endif %} +{%- endmacro %} +{%- if not messages %} + {{- raise_exception('No messages provided.') }} +{%- endif %} +{%- if tools and tools is iterable and tools is not mapping %} + {{- '<|im_start|>system\n' }} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {%- if content %} + {{- '\n\n' + content }} + {%- endif %} + {%- endif %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" %} + {%- set content = render_content(message.content, false)|trim %} + {%- if not(content.startswith('') and content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if ns.multi_step_tool %} + {{- raise_exception('No user query found in messages.') }} +{%- endif %} +{%- for message in messages %} + {%- set content = render_content(message.content, true)|trim %} + {%- if message.role == "system" %} + {%- if not loop.first %} + {{- raise_exception('System message must be at the beginning.') }} + {%- endif %} + {%- elif message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {%- set reasoning_content = reasoning_content|trim %} + {%- if (preserve_thinking is defined and preserve_thinking is true) or (loop.index0 > ns.last_query_index) %} + {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content + '\n\n\n' + content }} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- endif %} + {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if loop.first %} + {%- if content|trim %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n\n' }} + {%- endif %} + {%- else %} + {{- '\n\n\n' }} + {%- endif %} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' }} + {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %} + {{- args_value }} + {{- '\n\n' }} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- raise_exception('Unexpected message role.') }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_6_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_6_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..e4e705768d7d62e8149f7c28da77c93b57f6d041 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_6_training.jinja @@ -0,0 +1,162 @@ +{#- Training variant of the Qwen3.6 chat template (see qwen3_6.jinja for the original). + Modifications vs the original: + - {%- if '' in content %} → {%- if '' in content and '' in content %} + Always check for both tags to avoid edge cases where the model generates only one tag. + - Removed the loop.index0 > ns.last_query_index conditional; always include thinking block. + This makes the template prefix-preserving for the [user, assistant] → [user, assistant, tool] transition. + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- macro render_content(content, do_vision_count, is_system_content=false) %} + {%- if content is string %} + {{- content }} + {%- elif content is iterable and content is not mapping %} + {%- for item in content %} + {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain images.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set image_count.value = image_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Picture ' ~ image_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|image_pad|><|vision_end|>' }} + {%- elif 'video' in item or item.type == 'video' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain videos.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set video_count.value = video_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Video ' ~ video_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|video_pad|><|vision_end|>' }} + {%- elif 'text' in item %} + {{- item.text }} + {%- else %} + {{- raise_exception('Unexpected item type in content.') }} + {%- endif %} + {%- endfor %} + {%- elif content is none or content is undefined %} + {{- '' }} + {%- else %} + {{- raise_exception('Unexpected content type.') }} + {%- endif %} +{%- endmacro %} +{%- if not messages %} + {{- raise_exception('No messages provided.') }} +{%- endif %} +{%- if tools and tools is iterable and tools is not mapping %} + {{- '<|im_start|>system\n' }} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {%- if content %} + {{- '\n\n' + content }} + {%- endif %} + {%- endif %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" %} + {%- set content = render_content(message.content, false)|trim %} + {%- if not(content.startswith('') and content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if ns.multi_step_tool %} + {{- raise_exception('No user query found in messages.') }} +{%- endif %} +{%- for message in messages %} + {%- set content = render_content(message.content, true)|trim %} + {%- if message.role == "system" %} + {%- if not loop.first %} + {{- raise_exception('System message must be at the beginning.') }} + {%- endif %} + {%- elif message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content and '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {%- set reasoning_content = reasoning_content|trim %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- generation %} + {{- '\n' + reasoning_content + '\n\n\n' + content }} + {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if loop.first %} + {%- if content|trim %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n\n' }} + {%- endif %} + {%- else %} + {{- '\n\n\n' }} + {%- endif %} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' }} + {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %} + {{- args_value }} + {{- '\n\n' }} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- raise_exception('Unexpected message role.') }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_instruct_2507.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_instruct_2507.jinja new file mode 100644 index 0000000000000000000000000000000000000000..70adff8a08fb31e0636f618564838d4bf3c05286 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_instruct_2507.jinja @@ -0,0 +1,61 @@ +{%- if tools %} + {{- '<|im_start|>system\n' }} + {%- if messages[0].role == 'system' %} + {{- messages[0].content + '\n\n' }} + {%- endif %} + {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n<|im_end|>\n" }} +{%- else %} + {%- if messages[0].role == 'system' %} + {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- for message in messages %} + {%- if message.content is string %} + {%- set content = message.content %} + {%- else %} + {%- set content = '' %} + {%- endif %} + {%- if (message.role == "user") or (message.role == "system" and not loop.first) %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- if message.tool_calls %} + {%- for tool_call in message.tool_calls %} + {%- if (loop.first and content) or (not loop.first) %} + {{- '\n' }} + {%- endif %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n{"name": "' }} + {{- tool_call.name }} + {{- '", "arguments": ' }} + {%- if tool_call.arguments is string %} + {{- tool_call.arguments }} + {%- else %} + {{- tool_call.arguments | tojson }} + {%- endif %} + {{- '}\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_instruct_2507_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_instruct_2507_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..2e30797390d4983e6e2fcbce9827f56d5ee364ae --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_instruct_2507_training.jinja @@ -0,0 +1,71 @@ +{#- Training variant of the Qwen3-Instruct-2507 chat template (see qwen3_instruct_2507.jinja for the original). + This is for models like Qwen3-4B-Instruct-2507 that ship without the reasoning_content / + multi_step_tool / enable_thinking logic present in later Qwen3 revisions. + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{%- if tools %} + {{- '<|im_start|>system\n' }} + {%- if messages[0].role == 'system' %} + {{- messages[0].content + '\n\n' }} + {%- endif %} + {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n<|im_end|>\n" }} +{%- else %} + {%- if messages[0].role == 'system' %} + {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- for message in messages %} + {%- if message.content is string %} + {%- set content = message.content %} + {%- else %} + {%- set content = '' %} + {%- endif %} + {%- if (message.role == "user") or (message.role == "system" and not loop.first) %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- generation %} + {{- content }} + {%- if message.tool_calls %} + {%- for tool_call in message.tool_calls %} + {%- if (loop.first and content) or (not loop.first) %} + {{- '\n' }} + {%- endif %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n{"name": "' }} + {{- tool_call.name }} + {{- '", "arguments": ' }} + {%- if tool_call.arguments is string %} + {{- tool_call.arguments }} + {%- else %} + {{- tool_call.arguments | tojson }} + {%- endif %} + {{- '}\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- elif message.role == "tool" %} + {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..decc48dc6b6fecb761d045d4a318b92c1c489d0b --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_training.jinja @@ -0,0 +1,93 @@ +{#- Training variant of the Qwen3 chat template (see qwen3.jinja for the original). + Modifications vs the original: + - {%- if '' in content %} → {%- if '' in content and '' in content %} + Always check for both tags to avoid edge cases where the model generates only one tag. + - Removed the loop.index0 > ns.last_query_index conditional; always include thinking block. + This makes the template prefix-preserving for the [user, assistant] → [user, assistant, tool] transition. + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{%- if tools %} + {{- '<|im_start|>system\n' }} + {%- if messages[0].role == 'system' %} + {{- messages[0].content + '\n\n' }} + {%- endif %} + {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n<|im_end|>\n" }} +{%- else %} + {%- if messages[0].role == 'system' %} + {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('') and message.content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} +{%- endfor %} +{%- for message in messages %} + {%- if message.content is string %} + {%- set content = message.content %} + {%- else %} + {%- set content = '' %} + {%- endif %} + {%- if (message.role == "user") or (message.role == "system" and not loop.first) %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content and '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- generation %} + {{- '\n' + reasoning_content.strip('\n') + '\n\n\n' + content.lstrip('\n') }} + {%- if message.tool_calls %} + {%- for tool_call in message.tool_calls %} + {%- if (loop.first and content) or (not loop.first) %} + {{- '\n' }} + {%- endif %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n{"name": "' }} + {{- tool_call.name }} + {{- '", "arguments": ' }} + {%- if tool_call.arguments is string %} + {{- tool_call.arguments }} + {%- else %} + {{- tool_call.arguments | tojson }} + {%- endif %} + {{- '}\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- elif message.role == "tool" %} + {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n\n\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_vl.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_vl.jinja new file mode 100644 index 0000000000000000000000000000000000000000..124386803f142761528f710e77ae483f5f8c4fc4 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_vl.jinja @@ -0,0 +1,120 @@ +{%- if tools %} + {{- '<|im_start|>system\n' }} + {%- if messages[0].role == 'system' %} + {%- if messages[0].content is string %} + {{- messages[0].content }} + {%- else %} + {%- for content in messages[0].content %} + {%- if 'text' in content %} + {{- content.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {{- '\n\n' }} + {%- endif %} + {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n<|im_end|>\n" }} +{%- else %} + {%- if messages[0].role == 'system' %} + {{- '<|im_start|>system\n' }} + {%- if messages[0].content is string %} + {{- messages[0].content }} + {%- else %} + {%- for content in messages[0].content %} + {%- if 'text' in content %} + {{- content.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- for message in messages %} + {%- if message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- if message.content is string %} + {{- message.content }} + {%- else %} + {%- for content in message.content %} + {%- if content.type == 'image' or 'image' in content or 'image_url' in content %} + {%- set image_count.value = image_count.value + 1 %} + {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%} + <|vision_start|><|image_pad|><|vision_end|> + {%- elif content.type == 'video' or 'video' in content %} + {%- set video_count.value = video_count.value + 1 %} + {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%} + <|vision_start|><|video_pad|><|vision_end|> + {%- elif 'text' in content %} + {{- content.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "assistant" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- if message.content is string %} + {{- message.content }} + {%- else %} + {%- for content_item in message.content %} + {%- if 'text' in content_item %} + {{- content_item.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {%- if message.tool_calls %} + {%- for tool_call in message.tool_calls %} + {%- if (loop.first and message.content) or (not loop.first) %} + {{- '\n' }} + {%- endif %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n{"name": "' }} + {{- tool_call.name }} + {{- '", "arguments": ' }} + {%- if tool_call.arguments is string %} + {{- tool_call.arguments }} + {%- else %} + {{- tool_call.arguments | tojson }} + {%- endif %} + {{- '}\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {%- if message.content is string %} + {{- message.content }} + {%- else %} + {%- for content in message.content %} + {%- if content.type == 'image' or 'image' in content or 'image_url' in content %} + {%- set image_count.value = image_count.value + 1 %} + {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%} + <|vision_start|><|image_pad|><|vision_end|> + {%- elif content.type == 'video' or 'video' in content %} + {%- set video_count.value = video_count.value + 1 %} + {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%} + <|vision_start|><|video_pad|><|vision_end|> + {%- elif 'text' in content %} + {{- content.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} +{%- endif %} diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_vl_training.jinja b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_vl_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..137a64a1722352220eee524909ef631a37066541 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/chat_templates/qwen3_vl_training.jinja @@ -0,0 +1,127 @@ +{#- Training variant of the Qwen 3 VL chat template (see qwen3_vl.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message content to + support assistant-only loss masking in SFT training. +-#} +{%- if tools %} + {{- '<|im_start|>system\n' }} + {%- if messages[0].role == 'system' %} + {%- if messages[0].content is string %} + {{- messages[0].content }} + {%- else %} + {%- for content in messages[0].content %} + {%- if 'text' in content %} + {{- content.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {{- '\n\n' }} + {%- endif %} + {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n<|im_end|>\n" }} +{%- else %} + {%- if messages[0].role == 'system' %} + {{- '<|im_start|>system\n' }} + {%- if messages[0].content is string %} + {{- messages[0].content }} + {%- else %} + {%- for content in messages[0].content %} + {%- if 'text' in content %} + {{- content.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- for message in messages %} + {%- if message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- if message.content is string %} + {{- message.content }} + {%- else %} + {%- for content in message.content %} + {%- if content.type == 'image' or 'image' in content or 'image_url' in content %} + {%- set image_count.value = image_count.value + 1 %} + {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%} + <|vision_start|><|image_pad|><|vision_end|> + {%- elif content.type == 'video' or 'video' in content %} + {%- set video_count.value = video_count.value + 1 %} + {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%} + <|vision_start|><|video_pad|><|vision_end|> + {%- elif 'text' in content %} + {{- content.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "assistant" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- generation -%} + {%- if message.content is string %} + {{- message.content }} + {%- else %} + {%- for content_item in message.content %} + {%- if 'text' in content_item %} + {{- content_item.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {%- if message.tool_calls %} + {%- for tool_call in message.tool_calls %} + {%- if (loop.first and message.content) or (not loop.first) %} + {{- '\n' }} + {%- endif %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n{"name": "' }} + {{- tool_call.name }} + {{- '", "arguments": ' }} + {%- if tool_call.arguments is string %} + {{- tool_call.arguments }} + {%- else %} + {{- tool_call.arguments | tojson }} + {%- endif %} + {{- '}\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- endgeneration -%} + {%- elif message.role == "tool" %} + {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {%- if message.content is string %} + {{- message.content }} + {%- else %} + {%- for content in message.content %} + {%- if content.type == 'image' or 'image' in content or 'image_url' in content %} + {%- set image_count.value = image_count.value + 1 %} + {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%} + <|vision_start|><|image_pad|><|vision_end|> + {%- elif content.type == 'video' or 'video' in content %} + {%- set video_count.value = video_count.value + 1 %} + {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%} + <|vision_start|><|video_pad|><|vision_end|> + {%- elif 'text' in content %} + {{- content.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} +{%- endif %} diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6a1721cba48803210a91d0280eb9ccd35214d74f --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/__init__.py @@ -0,0 +1,18 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .main import main + + +__all__ = ["main"] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/accelerate_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/accelerate_config.py new file mode 100644 index 0000000000000000000000000000000000000000..d775fca787f7618a2785d1294beec2c152962e90 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/accelerate_config.py @@ -0,0 +1,47 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import importlib.resources as resources +from pathlib import Path + + +def resolve_accelerate_config_argument(launch_args: list[str]) -> list[str]: + """ + Resolve `--accelerate_config` from CLI arguments into `accelerate --config_file`. + + The function supports either a filesystem path or a predefined config name shipped in `trl/accelerate_configs` + (without the `.yaml` suffix). + """ + if "--accelerate_config" not in launch_args: + return launch_args + + config_index = launch_args.index("--accelerate_config") + if config_index + 1 >= len(launch_args): + raise ValueError("Expected a value after `--accelerate_config`.") + + config_name = launch_args[config_index + 1] + if Path(config_name).is_file(): + accelerate_config_path = config_name + else: + candidate = resources.files("trl.accelerate_configs").joinpath(f"{config_name}.yaml") + if not candidate.exists(): + raise ValueError( + f"Accelerate config {config_name} is neither a file nor a valid config in the `trl` package. " + "Please provide a valid config name or a path to a config file." + ) + accelerate_config_path = candidate + + # Remove '--accelerate_config '. + launch_args = launch_args[:config_index] + launch_args[config_index + 2 :] + return ["--config_file", str(accelerate_config_path)] + launch_args diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/accelerate_launcher.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/accelerate_launcher.py new file mode 100644 index 0000000000000000000000000000000000000000..eceebe1ffe8d49d6cfa4a3bdc5d3037b5dfd9da3 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/accelerate_launcher.py @@ -0,0 +1,47 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import importlib.resources as resources +from collections.abc import Callable +from typing import Any + +from accelerate.commands.launch import launch_command, launch_command_parser + + +def launch_training_script( + script_name: str, + launch_args: list[str], + training_script_args: list[str], + *, + launch_command_fn: Callable[[Any], None] = launch_command, + launch_parser_fn: Callable[[], Any] = launch_command_parser, +) -> None: + """ + Launch a TRL training script through `accelerate launch`. + + Parameters: + script_name (`str`): + Script filename in `trl/scripts`, e.g. `"dpo.py"`. + launch_args (`list[str]`): + Arguments consumed by `accelerate launch`. + training_script_args (`list[str]`): + Arguments forwarded to the training script. + launch_command_fn (`Callable[[Any], None]`, *optional*): + Function used to execute accelerate launch. + launch_parser_fn (`Callable[[], Any]`, *optional*): + Factory creating the accelerate launch parser. + """ + training_script = resources.files("trl.scripts").joinpath(script_name) + accelerate_args = launch_parser_fn().parse_args(launch_args + [str(training_script)] + training_script_args) + launch_command_fn(accelerate_args) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/commands/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/commands/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4bafa3ba61879096285ddeca6b48d7fe3292ffeb --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/commands/__init__.py @@ -0,0 +1,37 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .base import Command +from .env import EnvCommand +from .skills import SkillsCommand +from .training import TrainingCommand +from .vllm_serve import VllmServeCommand + + +def get_commands() -> list[Command]: + """Return all registered top-level TRL CLI commands.""" + return [ + TrainingCommand("dpo"), + EnvCommand(), + TrainingCommand("grpo"), + TrainingCommand("kto"), + TrainingCommand("reward"), + TrainingCommand("rloo"), + TrainingCommand("sft"), + SkillsCommand(), + VllmServeCommand(), + ] + + +__all__ = ["Command", "get_commands"] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/commands/base.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/commands/base.py new file mode 100644 index 0000000000000000000000000000000000000000..0000b558f26418077c3946519f54dcd1195029cc --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/commands/base.py @@ -0,0 +1,62 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from abc import ABC, abstractmethod +from argparse import Namespace +from dataclasses import dataclass + + +@dataclass(slots=True) +class CommandContext: + """Context shared by CLI commands during execution.""" + + argv: list[str] + + def argv_after(self, token: str) -> list[str]: + """ + Return CLI tokens after the first occurrence of `token`. + + Parameters: + token (`str`): + Subcommand name as it appears in `argv`. + """ + try: + index = self.argv.index(token) + except ValueError: + return [] + return self.argv[index + 1 :] + + +class Command(ABC): + """ + Base command definition for the TRL CLI. + + Parameters: + name (`str`): + Subcommand name exposed by the CLI. + help_text (`str`): + Short description displayed in help output. + """ + + def __init__(self, name: str, help_text: str): + self.name = name + self.help_text = help_text + + @abstractmethod + def register(self, subparsers) -> None: + """Register this command parser in the subparser collection.""" + + @abstractmethod + def run(self, args: Namespace, context: CommandContext) -> int: + """Execute the command.""" diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/commands/env.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/commands/env.py new file mode 100644 index 0000000000000000000000000000000000000000..28498ba15cb0ca1998b2f4b937c6393b7fbd1536 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/commands/env.py @@ -0,0 +1,33 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from argparse import Namespace + +from .base import Command, CommandContext + + +class EnvCommand(Command): + """CLI command that prints TRL environment information.""" + + def __init__(self): + super().__init__(name="env", help_text="Print the environment information") + + def register(self, subparsers) -> None: + subparsers.add_parser(self.name, help=self.help_text) + + def run(self, args: Namespace, context: CommandContext) -> int: + from ...scripts.env import print_env + + print_env() + return 0 diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/commands/skills.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/commands/skills.py new file mode 100644 index 0000000000000000000000000000000000000000..737bf4747276a348042e25f3826e6ad6e3bfa96c --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/commands/skills.py @@ -0,0 +1,42 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from argparse import Namespace + +from ...skills.cli import add_skills_subcommands +from .base import Command, CommandContext + + +class SkillsCommand(Command): + """CLI command that manages TRL agent skills.""" + + def __init__(self): + super().__init__(name="skills", help_text="Manage TRL agent skills") + self._skills_parser = None + + def register(self, subparsers) -> None: + self._skills_parser = subparsers.add_parser(self.name, help=self.help_text) + skills_subparsers = self._skills_parser.add_subparsers(dest="skills_command", help="Skills commands") + add_skills_subcommands(skills_subparsers) + + def run(self, args: Namespace, context: CommandContext) -> int: + if getattr(args, "skills_command", None): + if hasattr(args, "func"): + return args.func(args) + print("Error: Unknown skills command") + return 1 + + if self._skills_parser is not None: + self._skills_parser.print_help() + return 0 diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/commands/training.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/commands/training.py new file mode 100644 index 0000000000000000000000000000000000000000..64f52c73b7ec998d42d420d53890184bd5a40428 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/commands/training.py @@ -0,0 +1,72 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import importlib +from argparse import Namespace + +from .base import Command, CommandContext + + +def _subtract_subsequence(lst: list[str], subseq: list[str]) -> list[str]: + """Return lst with the ordered subsequence subseq removed.""" + sub_iter = iter(subseq) + current = next(sub_iter, None) + result = [] + for item in lst: + if current is not None and item == current: + current = next(sub_iter, None) + else: + result.append(item) + return result + + +class TrainingCommand(Command): + """ + Generic CLI command that launches a training script with accelerate. + + The script `trl/scripts/.py` must expose a `make_parser()` function. + + Parameters: + name (`str`): + CLI subcommand name (e.g. `"dpo"`). + """ + + def __init__(self, name: str): + super().__init__(name=name, help_text=f"Run the {name} training script") + + def register(self, subparsers) -> None: + subparsers.add_parser(self.name, help=self.help_text, add_help=False) + + def run(self, args: Namespace, context: CommandContext) -> int: + from ..accelerate_config import resolve_accelerate_config_argument + from ..accelerate_launcher import launch_training_script + + module = importlib.import_module(f"...scripts.{self.name}", package=__package__) + all_args = context.argv_after(self.name) + parser = module.make_parser(prog=f"trl {self.name}") + + # Handles -h (exits). Returns config_remaining and cli_remaining separately. + # cli_remaining is an ordered subsequence of all_args; config_remaining is not. + *_, config_remaining, cli_remaining = parser.parse_args_and_config( + all_args, return_remaining_strings=True, separate_remaining_strings=True + ) + launch_args = resolve_accelerate_config_argument(config_remaining + cli_remaining) + training_script_args = _subtract_subsequence(all_args, cli_remaining) + + launch_training_script( + script_name=f"{self.name}.py", + launch_args=launch_args, + training_script_args=training_script_args, + ) + return 0 diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/commands/vllm_serve.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/commands/vllm_serve.py new file mode 100644 index 0000000000000000000000000000000000000000..cc1cea21a5c1fcb8f52d8c2ce46a820e8702be03 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/commands/vllm_serve.py @@ -0,0 +1,36 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from argparse import Namespace + +from .base import Command, CommandContext + + +class VllmServeCommand(Command): + """CLI command for serving TRL models with vLLM.""" + + def __init__(self): + super().__init__(name="vllm-serve", help_text="Serve a model with vLLM") + + def register(self, subparsers) -> None: + subparsers.add_parser(self.name, help=self.help_text, add_help=False) + + def run(self, args: Namespace, context: CommandContext) -> int: + from ...scripts.vllm_serve import main as vllm_serve_main + from ...scripts.vllm_serve import make_parser as make_vllm_serve_parser + + parser = make_vllm_serve_parser(prog="trl vllm-serve") + (script_args,) = parser.parse_args_and_config(args=context.argv_after(self.name)) + vllm_serve_main(script_args) + return 0 diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/main.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/main.py new file mode 100644 index 0000000000000000000000000000000000000000..cea99a16d9a6ce250dbc242389cd4ea21f7f75f2 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/cli/main.py @@ -0,0 +1,51 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys +from argparse import ArgumentParser + +from .commands import get_commands +from .commands.base import Command, CommandContext + + +def _build_parser(commands: list[Command]) -> ArgumentParser: + parser = ArgumentParser(prog="trl", allow_abbrev=False) + subparsers = parser.add_subparsers(help="available commands", dest="command") + + for command in commands: + command.register(subparsers) + + return parser + + +def main(argv: list[str] | None = None) -> int: + """Run the TRL CLI.""" + commands = get_commands() + commands_by_name = {command.name: command for command in commands} + parser = _build_parser(commands) + argv = list(sys.argv[1:] if argv is None else argv) + + args, _ = parser.parse_known_args(argv) + command_name = getattr(args, "command", None) + if command_name is None: + parser.print_help() + return 0 + + command = commands_by_name[command_name] + context = CommandContext(argv=argv) + return command.run(args, context) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/data_utils.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/data_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fc2bcd8ea3b8e72a076358a092b5e2fb827dae33 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/data_utils.py @@ -0,0 +1,981 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +from collections import defaultdict, deque +from collections.abc import Callable, Sequence +from itertools import takewhile +from typing import Any, Literal, TypeVar + +import numpy as np +import pyarrow as pa +import pyarrow.compute as pc +import pyarrow.types +from datasets import Dataset, DatasetDict, IterableDataset, IterableDatasetDict +from transformers import PreTrainedTokenizerBase, ProcessorMixin + + +DatasetType = TypeVar("DatasetType", Dataset, DatasetDict) +IterableDatasetType = TypeVar("IterableDatasetType", IterableDataset, IterableDatasetDict) + + +def prepare_multimodal_messages(messages: list[dict[str, Any]], images: list | None = None) -> list[dict[str, Any]]: + # docstyle-ignore # because is not parsable in the code block + """ + Convert messages into a structured multimodal format and inject the provided images into the message contents. + + Args: + messages (`list[dict[str, Any]]`): + Messages with `"role"`, `"content"` (or `"tool_calls"`). Content may be a raw string before transformation. + List of messages with a `"role"` key (`"system"`, `"user"`, `"assistant"`, or `"tool"`) and a `"content"` key containing + either a string or a list of structured blocks if already prepared. Optionally, the `"content"` might + be `None` or not provided in favour of `"tool_calls"` in the `"assistant"` turns if applicable. + images (`list`, *optional*): + List of image objects to insert in the messages. + + Returns: + `list[dict[str, Any]]`: A new list of messages where every `"content"` value is a list of structured + content blocks, and all `"image"` placeholders are populated with the corresponding image objects. If the + assistant turns contains `"tool_calls"`, then the `"content"` might be empty. + + Notes: + - When the input `messages` isn't already in the structured format, (i.e., all `"content"` values are strings), + the function transforms them into the structured format by wrapping text in `{"type": "text", "text": ...}` + and inserting `{"type": "image"}` placeholders for the images *before* the first user message. + If the number of placeholders does not match the number of provided images, an error is raised. + - Existing image blocks that already include an `"image"` payload are preserved as-is. Only unfilled image + placeholders are counted and populated from `images`. + + Example: + ```python + # Input + [ + {"role": "user", "content": "What's in this image?"}, + {"role": "assistant", "content": "It looks like a cat."}, + ] + + # Output, one image provided + [ + {"role": "user", "content": [{"type": "image", "image": }, {"type": "text", "text": "What's in this image?"}]}, + {"role": "assistant", "content": [{"type": "text", "text": "It looks like a cat."}]}, + ] + ``` + """ + images = images or [] + + # First, convert all messages to the structured format if needed, and insert image placeholders if needed. + # Build new message dicts only when transforming string content to avoid modifying the originals. + new_messages = [] + images_included = False + for message in messages: + if message["role"] == "user": + if isinstance(message["content"], str) and not images_included: + image_entries = [{"type": "image"} for _ in range(len(images))] + message = {**message, "content": [*image_entries, {"type": "text", "text": message["content"]}]} + images_included = True + elif isinstance(message["content"], str): + message = {**message, "content": [{"type": "text", "text": message["content"]}]} + elif message["role"] in {"assistant", "system", "tool"}: + if isinstance(message.get("content"), str): + message = {**message, "content": [{"type": "text", "text": message["content"]}]} + else: + raise ValueError( + f"Invalid role in message: {message['role']}. Expected 'system', 'user', 'assistant', or 'tool'." + ) + new_messages.append(message) + + # Then, check that the number of image placeholders matches the number of images provided + num_placeholders = sum( + sum(1 for part in message["content"] if part["type"] == "image" and "image" not in part) + for message in new_messages + if message.get("content") and message["role"] != "tool" + ) + if num_placeholders != len(images): + raise ValueError( + f"Number of images provided ({len(images)}) does not match number of image placeholders ({num_placeholders})." + ) + + # Then, fill in the actual images in the placeholders + if images: + img_idx = 0 + for i, message in enumerate(new_messages): + if not message.get("content") or message["role"] == "tool": + continue + new_content = [] + for part in message["content"]: + if part["type"] == "image" and "image" not in part: + new_content.append({**part, "image": images[img_idx]}) + img_idx += 1 + else: + new_content.append(part) + new_messages[i] = {**message, "content": new_content} + + return new_messages + + +def prepare_multimodal_messages_vllm(messages: list[dict[str, Any]]) -> list[dict[str, Any]]: + # docstyle-ignore # because is not parsable in the code block + """ + Convert structured multimodal messages into a format compatible with vLLM. Replaces `"type": "image"` blocks with + `"type": "image_pil"` blocks, and `"image": Image` with `"image_pil": Image`. + + Args: + messages (`list[dict[str, Any]]`): + Messages with `"role"` and `"content"`. Content is expected to be a list of structured blocks. + + Returns: + `list[dict[str, Any]]`: + A deep-copied list of messages compatible with vLLM's expected input format. + + Example: + ```python + # Input + [{"role": "user", "content": [{"type": "image", "image": }, {"type": "text", "text": "What's in this image?"}]}] + + # Output + [{"role": "user", "content": [{"type": "image_pil", "image_pil": }, {"type": "text", "text": "What's in this image?"}]}] + ``` + """ + messages = copy.deepcopy(messages) # avoid modifying the original messages + for message in messages: + if isinstance(message["content"], list): + for part in message["content"]: + if part["type"] == "image": + part["type"] = "image_pil" # vLLM expects 'image_pil' key for images + part["image_pil"] = part.pop("image") + return messages + + +def is_conversational(example: dict[str, Any]) -> bool: + r""" + Check if the example is in a conversational format. + + Args: + example (`dict[str, Any]`): + A single data entry of a dataset. The example can have different keys depending on the dataset type. + + Returns: + `bool`: + `True` if the data is in a conversational format, `False` otherwise. + + Examples: + + ```python + >>> example = {"prompt": [{"role": "user", "content": "What color is the sky?"}]} + >>> is_conversational(example) + True + + >>> example = {"prompt": "The sky is"} + >>> is_conversational(example) + False + ``` + """ + supported_keys = ["prompt", "chosen", "rejected", "completion", "messages"] + example_keys = {key for key in example.keys() if key in supported_keys} + + # It must have one of the supported keys + if example_keys: + key = example_keys.pop() # take the first supported key + maybe_messages = example[key] + # It must be a list of messages + if isinstance(maybe_messages, list): + maybe_message = maybe_messages[0] + # Each message must a list of dictionaries with keys "role" and "content" + if isinstance(maybe_message, dict) and "role" in maybe_message: + return True + + return False + + +def apply_chat_template( + example: dict[str, list[dict[str, str]]], + processing_class: PreTrainedTokenizerBase | ProcessorMixin, + tools: list[dict | Callable] | None = None, + **template_kwargs, +) -> dict[str, str]: + r""" + Apply a chat template to a conversational example along with the schema for a list of functions in `tools`. + + For more details, see [`maybe_apply_chat_template`]. + """ + tools = tools or None # `or None`: Llama bug: it renders tool boilerplate for tools=[] + # Check that the example has the correct keys + supported_keys = ["prompt", "chosen", "rejected", "completion", "messages", "label"] + example_keys = {key for key in example.keys() if key in supported_keys} + if example_keys not in [ + {"messages"}, # language modeling + {"prompt"}, # prompt-only + {"prompt", "completion"}, # prompt-completion + {"prompt", "chosen", "rejected"}, # preference + {"chosen", "rejected"}, # preference with implicit prompt + {"prompt", "completion", "label"}, # unpaired preference + ]: + raise KeyError(f"Invalid keys in the example: {example_keys}") + + # Apply the chat template to the whole conversation + if "messages" in example: + messages = processing_class.apply_chat_template( + example["messages"], + tools=tools, + tokenize=False, + **example.get("chat_template_kwargs", {}), + **template_kwargs, + ) + + # Apply the chat template to the prompt, adding the generation prompt + if "prompt" in example: + last_role = example["prompt"][-1]["role"] + if last_role in ["user", "tool"]: + add_generation_prompt = True + continue_final_message = False + elif last_role == "assistant": + add_generation_prompt = False + continue_final_message = True + else: + raise ValueError(f"Invalid role in the last message: {last_role}") + prompt = processing_class.apply_chat_template( + example["prompt"], + tools=tools, + continue_final_message=continue_final_message, + tokenize=False, + add_generation_prompt=add_generation_prompt, + **example.get("chat_template_kwargs", {}), + **template_kwargs, + ) + + # Apply the chat template to the entire prompt + completion + if "prompt" in example: # explicit prompt and prompt-completion case + if "chosen" in example: + prompt_chosen = processing_class.apply_chat_template( + example["prompt"] + example["chosen"], + tools=tools, + tokenize=False, + **example.get("chat_template_kwargs", {}), + **template_kwargs, + ) + # DeepSeek-R1 inserts a token when using `add_generation_prompt`, which can cause discrepancies + # between the prompt alone and the combined prompt+completion. To ensure consistency, we extract the + # common prefix between the two. In most cases, this is a no-op. + prompt = "".join(x for x, _ in takewhile(lambda x: x[0] == x[1], zip(prompt, prompt_chosen, strict=False))) + + chosen = prompt_chosen[len(prompt) :] + if "rejected" in example and "prompt" in example: # explicit prompt + prompt_rejected = processing_class.apply_chat_template( + example["prompt"] + example["rejected"], + tools=tools, + tokenize=False, + **example.get("chat_template_kwargs", {}), + **template_kwargs, + ) + # Handle DeepSeek-R1 token, see the above comment for details + prompt = "".join( + x for x, _ in takewhile(lambda x: x[0] == x[1], zip(prompt, prompt_rejected, strict=False)) + ) + rejected = prompt_rejected[len(prompt) :] + if "completion" in example: + prompt_completion = processing_class.apply_chat_template( + example["prompt"] + example["completion"], + tools=tools, + tokenize=False, + **example.get("chat_template_kwargs", {}), + **template_kwargs, + ) + # Handle DeepSeek-R1 token, see the above comment for details + prompt = "".join( + x for x, _ in takewhile(lambda x: x[0] == x[1], zip(prompt, prompt_completion, strict=False)) + ) + completion = prompt_completion[len(prompt) :] + else: # implicit prompt case + if "chosen" in example: + chosen = processing_class.apply_chat_template( + example["chosen"], + tools=tools, + tokenize=False, + **example.get("chat_template_kwargs", {}), + **template_kwargs, + ) + if "rejected" in example: + rejected = processing_class.apply_chat_template( + example["rejected"], + tools=tools, + tokenize=False, + **example.get("chat_template_kwargs", {}), + **template_kwargs, + ) + + # Extract the completion by removing the prompt part from the prompt-completion string + output = {} + if "messages" in example: + output["text"] = messages + if "prompt" in example: + output["prompt"] = prompt + if "chosen" in example: + output["chosen"] = chosen + if "rejected" in example: + output["rejected"] = rejected + if "completion" in example: + output["completion"] = completion + if "label" in example: + output["label"] = example["label"] + + return output + + +def maybe_apply_chat_template( + example: dict[str, list[dict[str, str]]], + processing_class: PreTrainedTokenizerBase | ProcessorMixin, + tools: list[dict | Callable] | None = None, + **template_kwargs: Any, +) -> dict[str, str]: + r""" + If the example is in a conversational format, apply a chat template to it. + + Args: + example (`dict[str, list[dict[str, str]]`): + Dictionary representing a single data entry of a conversational dataset. Each data entry can have different + keys depending on the dataset type. The supported dataset types are: + + - Language modeling dataset: `"messages"`. + - Prompt-only dataset: `"prompt"`. + - Prompt-completion dataset: `"prompt"` and `"completion"`. + - Preference dataset: `"prompt"`, `"chosen"`, and `"rejected"`. + - Preference dataset with implicit prompt: `"chosen"` and `"rejected"`. + - Unpaired preference dataset: `"prompt"`, `"completion"`, and `"label"`. + + For keys `"messages"`, `"prompt"`, `"chosen"`, `"rejected"`, and `"completion"`, the values are lists of + messages, where each message is a dictionary with keys `"role"` and `"content"`. Additionally, the example + may contain a `"chat_template_kwargs"` key, which is a dictionary of additional keyword arguments to pass + to the chat template renderer. + processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`]): + Tokenizer to apply the chat template with. + tools (`list[dict | Callable]`, *optional*): + A list of tools (callable functions) that will be accessible to the model. If the template does not support + function calling, this argument will have no effect. + **template_kwargs (`Any`, *optional*): + Additional kwargs to pass to the template renderer. Will be accessible by the chat template. + + Returns: + `dict[str, str]`: + Formatted example with the chat template applied. + + Notes: + - This function does not alter the keys, except for Language modeling dataset, where `"messages"` is replaced + by `"text"`. + + - In case of prompt-only data, if the last role is `"user"`, the generation prompt is added to the prompt. + Else, if the last role is `"assistant"`, the final message is continued. + + Example: + + ```python + >>> from transformers import AutoTokenizer + + >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-128k-instruct") + >>> example = { + ... "prompt": [{"role": "user", "content": "What color is the sky?"}], + ... "completion": [{"role": "assistant", "content": "It is blue."}], + ... } + >>> apply_chat_template(example, tokenizer) + {'prompt': '<|user|>\nWhat color is the sky?<|end|>\n<|assistant|>\n', 'completion': 'It is blue.<|end|>\n'} + ``` + """ + if is_conversational(example): + return apply_chat_template(example, processing_class, tools, **template_kwargs) + else: + return example + + +def _unpair_row(batch: dict[str, list[Any]]) -> dict[str, list[Any]]: + batch_size = len(batch["chosen"]) + new_batch = { + "completion": batch["chosen"] + batch["rejected"], + "label": [True] * batch_size + [False] * batch_size, + } + if "prompt" in batch: + new_batch["prompt"] = batch["prompt"] + batch["prompt"] + for k in batch: + if k not in ("chosen", "rejected", "prompt"): + new_batch[k] = batch[k] + batch[k] + return new_batch + + +def unpair_preference_dataset( + dataset: DatasetType | IterableDatasetType, **map_kwargs +) -> DatasetType | IterableDatasetType: + # docstyle-ignore + """ + Unpair a preference dataset. + + The output contains `"prompt"`, `"completion"`, and `"label"` plus any extra columns, which are duplicated for + each chosen and rejected row. + + Args: + dataset ([`~datasets.Dataset`] or [`~datasets.DatasetDict`] or [`~datasets.IterableDataset`] or [`~datasets.IterableDatasetDict`]): + Preference dataset to unpair. The dataset must have columns `"chosen"`, `"rejected"` and optionally + `"prompt"`. + **map_kwargs (`dict`, *optional*): + Additional keyword arguments to pass to the dataset's map method when unpairing preferences. + + Returns: + [`~datasets.Dataset`] or [`~datasets.DatasetDict`] or [`~datasets.IterableDataset`] or [`~datasets.IterableDatasetDict`]: + The unpaired preference dataset. + + Example: + + ```python + >>> from datasets import Dataset + + >>> dataset_dict = { + ... "prompt": ["The sky is", "The sun is"], + ... "chosen": [" blue.", "in the sky."], + ... "rejected": [" green.", " in the sea."], + ... } + >>> dataset = Dataset.from_dict(dataset_dict) + >>> dataset = unpair_preference_dataset(dataset) + >>> dataset + Dataset({ + features: ['prompt', 'completion', 'label'], + num_rows: 4 + }) + + >>> dataset[0] + {'prompt': 'The sky is', 'completion': ' blue.', 'label': True} + ``` + """ + if isinstance(dataset, DatasetDict): + column_names = next(iter(dataset.values())).column_names + elif isinstance(dataset, Dataset): + column_names = dataset.column_names + else: # IterableDataset + column_names = dataset.column_names or list(next(iter(dataset)).keys()) + return dataset.map(_unpair_row, batched=True, remove_columns=column_names, **map_kwargs) + + +def maybe_unpair_preference_dataset( + dataset: DatasetType, num_proc: int | None = None, desc: str | None = None +) -> DatasetType: + r""" + Unpair a preference dataset if it is paired. + + Args: + dataset ([`~datasets.Dataset`] or [`~datasets.DatasetDict`]): + Preference dataset to unpair. The dataset must have columns `"chosen"`, `"rejected"` and optionally + `"prompt"`. + num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + desc (`str`, *optional*): + Meaningful description to be displayed alongside with the progress bar while mapping examples. + + Returns: + [`~datasets.Dataset`] or [`~datasets.DatasetDict`]: The unpaired preference dataset if it was paired, otherwise + the original dataset. + + Example: + + ```python + >>> from datasets import Dataset + + >>> dataset_dict = { + ... "prompt": ["The sky is", "The sun is"], + ... "chosen": [" blue.", "in the sky."], + ... "rejected": [" green.", " in the sea."], + ... } + >>> dataset = Dataset.from_dict(dataset_dict) + >>> dataset = unpair_preference_dataset(dataset) + >>> dataset + Dataset({ + features: ['prompt', 'completion', 'label'], + num_rows: 4 + }) + + >>> dataset[0] + {'prompt': 'The sky is', 'completion': ' blue.', 'label': True} + ``` + """ + if isinstance(dataset, DatasetDict): + column_names = dataset[list(dataset.keys())[0]].column_names + else: + column_names = dataset.column_names + if "chosen" in column_names and "rejected" in column_names: + return unpair_preference_dataset(dataset, num_proc=num_proc, desc=desc) + else: + return dataset + + +def extract_prompt(example: dict[str, Sequence]) -> dict[str, Sequence]: + r""" + Extracts the shared prompt from a preference data example, where the prompt is implicit within both the chosen and + rejected completions. + + The function identifies the longest common sequence (prefix) of conversation turns between the "chosen" and + "rejected" completions and extracts this as the prompt. It then removes this prompt from the respective "chosen" + and "rejected" completions. + + Args: + example (`dict[str, list]`): + A dictionary representing a single data entry in the preference dataset. It must contain the keys + `"chosen"` and `"rejected"`, where each value is either conversational or standard (`str`). + + Returns: + `dict[str, list]`: A dictionary containing: + - `"prompt"`: The longest common prefix between the "chosen" and "rejected" completions. + - `"chosen"`: The remainder of the "chosen" completion, with the prompt removed. + - `"rejected"`: The remainder of the "rejected" completion, with the prompt removed. + + Examples: + + ```python + >>> example = { + ... "chosen": [ + ... {"role": "user", "content": "What color is the sky?"}, + ... {"role": "assistant", "content": "It is blue."}, + ... ], + ... "rejected": [ + ... {"role": "user", "content": "What color is the sky?"}, + ... {"role": "assistant", "content": "It is green."}, + ... ], + ... } + >>> extract_prompt(example) + {'prompt': [{'role': 'user', 'content': 'What color is the sky?'}], + 'chosen': [{'role': 'assistant', 'content': 'It is blue.'}], + 'rejected': [{'role': 'assistant', 'content': 'It is green.'}]} + ``` + + Or, with the `map` method of [`~datasets.Dataset`]: + + ```python + >>> from trl import extract_prompt + >>> from datasets import Dataset + + >>> dataset_dict = { + ... "chosen": [ + ... [ + ... {"role": "user", "content": "What color is the sky?"}, + ... {"role": "assistant", "content": "It is blue."}, + ... ], + ... [ + ... {"role": "user", "content": "Where is the sun?"}, + ... {"role": "assistant", "content": "In the sky."}, + ... ], + ... ], + ... "rejected": [ + ... [ + ... {"role": "user", "content": "What color is the sky?"}, + ... {"role": "assistant", "content": "It is green."}, + ... ], + ... [ + ... {"role": "user", "content": "Where is the sun?"}, + ... {"role": "assistant", "content": "In the sea."}, + ... ], + ... ], + ... } + >>> dataset = Dataset.from_dict(dataset_dict) + >>> dataset = dataset.map(extract_prompt) + >>> dataset[0] + {'prompt': [{'role': 'user', 'content': 'What color is the sky?'}], + 'chosen': [{'role': 'assistant', 'content': 'It is blue.'}], + 'rejected': [{'role': 'assistant', 'content': 'It is green.'}]} + ``` + """ + for idx in range(min(len(example["chosen"]), len(example["rejected"]))): + if example["chosen"][idx] != example["rejected"][idx]: + if example["chosen"][idx - 1] == " ": # remove space before the prompt + idx -= 1 + break + return { + "prompt": example["chosen"][:idx], + "chosen": example["chosen"][idx:], + "rejected": example["rejected"][idx:], + } + + +def maybe_extract_prompt(example: dict[str, list]) -> dict[str, list]: + r""" + Extracts the shared prompt from a preference data example, where the prompt is implicit within both the chosen and + rejected completions. + + If the example already contains a `"prompt"` key, the function returns the example as is. For more details, see + [`extract_prompt`]. + ``` + """ + # Some dataset add a `"prompt"` column, even though the prompt is implicit and included in the "chosen" and + # "rejected" completions. E.g.: + # {"prompt": "What color is the sky?", + # "chosen": [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is blue."}], + # "rejected": [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is green."}]} + # That's why we check if the prompt is also conversational before deciding not to extract it. + if "chosen" not in example or "rejected" not in example: # not a preference example + return example + if "prompt" in example: + # Both conversational or both non-conversational + chosen_conv = is_conversational({"chosen": example["chosen"]}) + prompt_conv = is_conversational({"prompt": example["prompt"]}) + if (chosen_conv and prompt_conv) or (not chosen_conv and not prompt_conv): + return example + return extract_prompt({"chosen": example["chosen"], "rejected": example["rejected"]}) + + +def _get_dataset_format(dataset: DatasetType) -> dict[str, Any]: + if isinstance(dataset, (DatasetDict, IterableDatasetDict)): + dataset = dataset[next(iter(dataset))] + if isinstance(dataset, Dataset): + format = dataset.format + else: + format_type = dataset._formatting.format_type if dataset._formatting is not None else None + format = {"type": format_type} + format.update(format.pop("format_kwargs", {})) + return format + + +def _check_if_columns_can_be_packed(columns: list[pa.Array]): + first_column_offsets = None + for idx, column in enumerate(columns): + if not (pyarrow.types.is_list(column.type) or pyarrow.types.is_large_list(column.type)): + raise TypeError("Packing requires all columns to be lists of lists.") + + if idx == 0: + first_column_offsets = column.offsets + elif not first_column_offsets.equals(column.offsets): + raise ValueError("All columns must have values of the same length.") + + +class _SegmentTree: + """ + A segment tree data structure that, when initialized as `_SegmentTree(maxval)`, efficiently finds the next larger + value for a given input within the range [1, maxval]. + + See [Fewer Truncations Improve Language Modeling](https://huggingface.co/papers/2404.10830) for more details. + """ + + def __init__(self, maxval: int): + self.maxval = maxval + # For non-power-of-2 values, we need to round up to the next power of 2 for the tree size + self.tree_size = 1 << (maxval - 1).bit_length() + self.tree = [0] * (2 * self.tree_size) + + def add(self, val): + assert 0 < val <= self.maxval + i = self.tree_size + val - 1 + self.tree[i] = val + while i > 1: + i >>= 1 + left, right = self.tree[i << 1], self.tree[(i << 1) + 1] + # Compare the values using if-else otherwise repeated calls to `builtins.max` become the bottleneck + self.tree[i] = left if left >= right else right + + def remove(self, val): + assert 0 < val <= self.maxval + i = self.tree_size + val - 1 + self.tree[i] = 0 + while i > 1: + i >>= 1 + left, right = self.tree[i << 1], self.tree[(i << 1) + 1] + # Compare the values using if-else otherwise repeated calls to `builtins.max` become the bottleneck + self.tree[i] = left if left >= right else right + + def search(self, val): + assert 0 < val <= self.maxval + i = 1 + while i < self.tree_size: + if self.tree[i << 1] >= val: + i = i << 1 + else: + i = (i << 1) + 1 + return self.tree[i] + + +def _pack_bfd( + examples: pa.Table, seq_length: int, on_seq_length_overflow: Literal["truncate", "split"] = "truncate" +) -> pa.Table: + """Pack sequences in a pyarrow Table using Best Fit Decreasing strategy.""" + columns = [column.chunks[0] for column in examples.combine_chunks().columns] + _check_if_columns_can_be_packed(columns) + assert len(columns) > 0 + + lengths = pc.list_value_length(columns[0]) + + # Filter out empty sequences + non_empty_mask = pc.greater(lengths, 0) + columns = [pc.filter(column, non_empty_mask) for column in columns] + lengths = pc.filter(lengths, non_empty_mask) + + if on_seq_length_overflow == "truncate": + columns = [pc.list_slice(column, 0, seq_length) for column in columns] + elif on_seq_length_overflow == "split": + lengths = lengths.to_numpy() + # Split the sequences longer than `seq_length` into chunks (of length `seq_length` or less) while respecting sequence boundaries + num_fragments = np.ceil(lengths / seq_length).astype(int) + offsets = np.arange(np.sum(num_fragments) + 1, dtype=columns[0].offsets.type.to_pandas_dtype()) * seq_length + # "Left-shift" the offsets to account for the last fragment of each original sequence possibly being shorter than `seq_length` + diff = np.zeros_like(offsets) + diff[np.cumsum(num_fragments)] = -lengths % seq_length + diff = np.cumsum(diff) + offsets -= diff + columns = [ + type(column).from_arrays(offsets.astype(column.offsets.type.to_pandas_dtype()), column.values) + for column in columns + ] + else: + raise ValueError(f"Invalid `on_seq_length_overflow`: {on_seq_length_overflow}. Use 'truncate' or 'split'.") + + examples = pa.Table.from_arrays(columns, names=examples.column_names) + lengths = pc.list_value_length(columns[0]) + examples = examples.append_column("seq_lengths", lengths) # Allows us to later construct `position_ids` + ids = np.arange(len(examples)) + lengths = pc.make_struct(lengths, ids) + lengths = lengths.sort("descending", by=0) + + # Greedy BFD binning using a segment tree to quickly find best-fit remaining space. + segment_tree = _SegmentTree(seq_length) + segment_tree.add(seq_length) # the max, `seq_length` bin is always available + space_to_bin = defaultdict(deque) + + # Bin is represented as a dict (of example ids and sum of their lengths) to allow in-place updates + bins: list[dict] = [] + for length, idx in zip(lengths.field(0).to_numpy(), lengths.field(1).to_numpy(), strict=True): + space = segment_tree.search(length) + + if space < seq_length: + # Use existing bin with exactly this amount of space + bin = space_to_bin[space].popleft() + else: + # Create a new bin + bin = {"ids": [], "length": 0} + bins.append(bin) + + bin["ids"].append(idx) + bin["length"] += length + if space < seq_length and not space_to_bin[space]: + segment_tree.remove(space) + + space = space - length + space_to_bin[space].append(bin) + if space > 0: + segment_tree.add(space) + + examples = pc.take(examples, [id_ for bin in bins for id_ in bin["ids"]]) + offsets = np.cumsum([0] + [bin["length"] for bin in bins]) + + assert all( + column.num_chunks == 1 for column in examples.columns + ) # `pc.take` returns a ChunkedArray with a single chunk + + lengths = examples["seq_lengths"].chunks[0] + examples = examples.drop_columns("seq_lengths") + lengths = pa.ListArray.from_arrays(np.cumsum([0] + [len(bin["ids"]) for bin in bins], dtype=np.int32), lengths) + + columns = [] + for column in examples.columns: + column = column.chunks[0] + assert pa.types.is_list(column.type) or pa.types.is_large_list(column.type) + dtype = column.offsets.type.to_pandas_dtype() + column = type(column).from_arrays(offsets.astype(dtype), column.values) + columns.append(column) + return pa.Table.from_arrays(columns + [lengths], names=examples.column_names + ["seq_lengths"]) + + +def _pack_wrapped(examples: pa.Table, seq_length: int) -> pa.Table: + """Pack sequences in a pyarrow Table using a wrapped strategy.""" + columns = [column.chunks[0] for column in examples.combine_chunks().columns] + _check_if_columns_can_be_packed(columns) + offsets, values = columns[0].offsets, columns[0].values + values = values[offsets[0].as_py() : offsets[-1].as_py()] + num_elements = len(values) + offsets = np.arange(0, num_elements, seq_length, dtype=columns[0].offsets.type.to_pandas_dtype()) + offsets = np.concatenate((offsets, [num_elements])) + columns = [ + type(column).from_arrays(offsets.astype(column.offsets.type.to_pandas_dtype()), column.values) + for column in columns + ] + return pa.Table.from_arrays(columns, names=examples.column_names) + + +def pack_dataset( + dataset: DatasetType, + seq_length: int, + strategy: str = "bfd", + map_kwargs: dict[str, Any] | None = None, +) -> DatasetType: + r""" + Pack sequences in a dataset into chunks of size `seq_length`. + + Args: + dataset ([`~datasets.Dataset`] or [`~datasets.DatasetDict`]): + Dataset to pack + seq_length (`int`): + Target sequence length to pack to. + strategy (`str`, *optional*, defaults to `"bfd"`): + Packing strategy to use. Can be either: + + - `"bfd"` (Best Fit Decreasing): Preserves sequence boundaries and truncates sequences that exceed + `seq_length`, discarding overflow tokens. Ideal for SFT and conversational datasets where maintaining + conversation structure is important. + - `"bfd_split"`: Similar to `"bfd"` but splits overflow sequences for packing into other examples. Prevents + token loss for pre-training or long documents, but may break conversation structure in SFT datasets. + - `"wrapped"`: Faster but more aggressive. Ignores sequence boundaries and will cut sequences in the middle + to completely fill each packed sequence with data. + map_kwargs (`dict`, *optional*): + Additional keyword arguments to pass to the dataset's map method when packing examples. + + Returns: + [`~datasets.Dataset`] or [`~datasets.DatasetDict`]: The dataset with packed sequences. The number of examples + may decrease as sequences are combined. + + Example: + ```python + >>> from datasets import Dataset + >>> from trl import pack_dataset + + >>> examples = { + ... "input_ids": [[1, 2, 3, 4, 5], [6, 7], [8, 9, 10], [11]], + ... "attention_mask": [[1, 1, 1, 0, 0], [1, 0], [1, 1, 0], [1]], + ... } + >>> dataset = Dataset.from_dict(examples) + >>> # Default "bfd" strategy (SFT-friendly): truncates long sequences + >>> packed_dataset = pack_dataset(dataset, seq_length=4, strategy="bfd") + >>> packed_dataset[:] + {'input_ids': [[1, 2, 3, 4], [8, 9, 10, 11], [6, 7]], + 'attention_mask': [[1, 1, 1, 0], [1, 1, 0, 1], [1, 0]], + 'seq_lengths': [[4], [3, 1], [2]]} + + >>> # "bfd_split" strategy: preserves all tokens + >>> packed_dataset = pack_dataset(dataset, seq_length=4, strategy="bfd_split") + >>> packed_dataset[:] + {'input_ids': [[1, 2, 3, 4], [8, 9, 10, 5], [6, 7, 11]], + 'attention_mask': [[1, 1, 1, 0], [1, 1, 0, 0], [1, 0, 1]], + 'seq_lengths': [[4], [3, 1], [2, 1]]} + ``` + """ + if map_kwargs is None: + map_kwargs = {} + + valid_strategies = ("bfd", "bfd_split", "wrapped") + if strategy not in valid_strategies: + raise ValueError(f"Invalid packing strategy '{strategy}', must be one of {valid_strategies}.") + format = _get_dataset_format(dataset) + dataset = dataset.with_format("arrow") + if strategy == "bfd": + dataset = dataset.map( + _pack_bfd, + batched=True, + fn_kwargs={"seq_length": seq_length, "on_seq_length_overflow": "truncate"}, + **map_kwargs, + ) + elif strategy == "bfd_split": + dataset = dataset.map( + _pack_bfd, + batched=True, + fn_kwargs={"seq_length": seq_length, "on_seq_length_overflow": "split"}, + **map_kwargs, + ) + elif strategy == "wrapped": + dataset = dataset.map(_pack_wrapped, batched=True, fn_kwargs={"seq_length": seq_length}, **map_kwargs) + else: + raise ValueError(f"Invalid packing strategy: '{strategy}', must be one of {valid_strategies}.") + + if strategy in {"bfd", "bfd_split"} and "columns" in format: + format["columns"] = format["columns"] + ["seq_lengths"] + + dataset = dataset.with_format(**format) + return dataset + + +def is_conversational_from_value(example: dict[str, Any]) -> bool: + r""" + Check if the example is in a conversational format (from/value). Note that this format isn't recommended. Prefer + the ChatML format (role/content) + + Args: + example (`dict[str, Any]`): + A single data entry of a dataset. The example can have different keys depending on the dataset type. + + Returns: + `bool`: + `True` if the data is in a conversational Chatformat, `False` otherwise. + + Examples: + + ```python + >>> example = {"conversations": [{"from": "user", "value": "What color is the sky?"}]} + >>> is_conversational_from_value(example) + True + + >>> example = {"conversations": [{"role": "user", "content": "What color is the sky?"}]} + >>> is_conversational_from_value(example) + False + + >>> example = {"conversations": "The sky is"} + >>> is_conversational_from_value(example) + False + ``` + """ + maybe_messages = example.get("conversations") + # It must be a list of messages + if isinstance(maybe_messages, list): + maybe_message = maybe_messages[0] + # Each message must a list of dictionaries with keys "from" and "value" + if isinstance(maybe_message, dict) and "from" in maybe_message and "value" in maybe_message: + return True + + return False + + +def maybe_convert_to_chatml(example: dict[str, list]) -> dict[str, list]: + """ + Convert a conversational dataset with fields `from` and `value` to ChatML format. + + This function modifies conversational data to align with OpenAI's ChatML format: + - Replaces the key `"from"` with `"role"` in message dictionaries. + - Replaces the key `"value"` with `"content"` in message dictionaries. + - Renames `"conversations"` to `"messages"` for consistency with ChatML. + + Args: + example (`dict[str, list]`): + A single data entry containing a list of messages. + + Returns: + `dict[str, list]`: + Example reformatted to ChatML style. + + Example: + ```python + >>> from trl import maybe_convert_to_chatml + + >>> example = { + ... "conversations": [ + ... {"from": "user", "value": "What color is the sky?"}, + ... {"from": "assistant", "value": "It is blue."}, + ... ] + ... } + >>> maybe_convert_to_chatml(example) + {'messages': [{'role': 'user', 'content': 'What color is the sky?'}, + {'role': 'assistant', 'content': 'It is blue.'}]} + ``` + """ + # List of possible keys containing message lists + for key in ["prompt", "completion", "chosen", "rejected", "messages", "conversations"]: + if key in example and isinstance(example[key], list): + messages = example[key] + for message in messages: + if isinstance(message, dict): + if "from" in message: + message["role"] = message.pop("from") + if "value" in message: + message["content"] = message.pop("value") + + # Rename "conversations" to "messages" + if "conversations" in example: + example["messages"] = example.pop("conversations") + + return example diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/distributed.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..d5d03be37e1457488ba7b15d926cfb9400adc96c --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/distributed.py @@ -0,0 +1,91 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Distributed training backend abstraction.""" + +from contextlib import contextmanager + + +class DistributedBackend: + """Abstracts distributed backend specifics (DeepSpeed ZeRO, FSDP) behind a uniform API. + + Detects the active backend once at construction from ``accelerator.state``, then provides context managers that are + no-ops on backends where the operation is not needed. + + Args: + accelerator ([`~accelerate.Accelerator`]): + The accelerator instance managing the distributed state. + + Example: + + ```python + >>> dist = DistributedBackend(accelerator) + >>> with dist.gather_params(list(model.parameters())): + ... model.merge_adapter() + >>> with dist.summon_full_params(model, recurse=False): + ... outputs = model.generate(inputs) + ``` + """ + + def __init__(self, accelerator): + ds_plugin = accelerator.state.deepspeed_plugin + fsdp_plugin = getattr(accelerator.state, "fsdp_plugin", None) + self.zero_stage = ds_plugin.zero_stage if ds_plugin else 0 + self.fsdp_version = getattr(fsdp_plugin, "fsdp_version", None) if fsdp_plugin else None + + @property + def is_zero3(self) -> bool: + """Whether DeepSpeed ZeRO Stage 3 is active.""" + return self.zero_stage == 3 + + @property + def is_fsdp(self) -> bool: + """Whether FSDP (any version) is active.""" + return self.fsdp_version is not None + + @contextmanager + def gather_params(self, params): + """Gather sharded parameters under DeepSpeed ZeRO-3; no-op otherwise. + + Args: + params (iterable of `torch.nn.Parameter`): + Parameters to gather. + """ + if self.is_zero3: + import deepspeed + + with deepspeed.zero.GatheredParameters(params): + yield + else: + yield + + @contextmanager + def summon_full_params(self, module, **kwargs): + """Materialize full FSDP v1 parameters; no-op for FSDP v2 or non-FSDP backends. + + FSDP v2 parameters are always accessible and require no explicit materialization. + + Args: + module (`torch.nn.Module`): + The FSDP-wrapped module. + **kwargs: + Forwarded to ``FSDP.summon_full_params`` (e.g. ``recurse``, ``writeback``). + """ + if self.fsdp_version == 1: + from torch.distributed.fsdp import FullyShardedDataParallel as FSDP + + with FSDP.summon_full_params(module, **kwargs): + yield + else: + yield diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..041a38542a6fbaba81fbdb3d278e737109c95f83 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/__init__.py @@ -0,0 +1,36 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Experimental submodule for TRL. + +This submodule contains unstable or incubating features. Anything here may change (or be removed) in any release +without deprecation. Use at your own risk. + +To silence this notice set environment variable TRL_EXPERIMENTAL_SILENCE=1. +""" + +import os +import warnings + +from ..import_utils import TRLExperimentalWarning + + +if not os.environ.get("TRL_EXPERIMENTAL_SILENCE"): + warnings.warn( + "You are importing from 'trl.experimental'. APIs here are unstable and may change or be removed without " + "notice. Silence this warning by setting environment variable TRL_EXPERIMENTAL_SILENCE=1.", + TRLExperimentalWarning, + stacklevel=2, + ) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/a2po/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/a2po/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fa3d8b8fbbff1633f7cd5414dd7f2362e302a09a --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/a2po/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .a2po_config import A2POConfig +from .a2po_trainer import A2POTrainer diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/a2po/a2po_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/a2po/a2po_config.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4137da675fb85aa5280f683fb2360ead92180b --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/a2po/a2po_config.py @@ -0,0 +1,156 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field + +from trl.trainer.base_config import _BaseConfig + + +@dataclass +class A2POConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`A2POTrainer`]. + + This class includes only the parameters that are specific to A2PO training. For a full list of training arguments, + please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may + differ from those in [`~transformers.TrainingArguments`]. + + Parameters: + > Parameters that control the model and reference model + + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model` + argument of the [`A2POTrainer`] is provided as a string. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to + [`~transformers.AutoModelForCausalLM.from_pretrained`] and [`~transformers.AutoTokenizer.from_pretrained`]. + + > Parameters that control the data preprocessing + + remove_unused_columns (`bool`, *optional*, defaults to `False`): + Whether to only keep the column `"prompt"` in the dataset. If you use a custom reward function that + requires any column other than `"prompts"` and `"completions"`, you should keep this to `False`. + + > Parameters that control generation + + max_prompt_length (`int` or `None`, *optional*, defaults to `512`): + Maximum length of the prompt. If the prompt is longer than this, it is left-truncated. + max_completion_length (`int` or `None`, *optional*, defaults to `256`): + Maximum length of the generated completion. + temperature (`float`, *optional*, defaults to `1.0`): + Sampling temperature, used in both Stage 1 and Stage 2 generation. + top_p (`float`, *optional*, defaults to `1.0`): + Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to + `1.0` to consider all tokens. + top_k (`int` or `None`, *optional*): + Number of highest-probability vocabulary tokens to keep. If `None`, top-k filtering is disabled. + + > Parameters that control Stage 1 (offline optimal value estimation) + + num_value_samples (`int`, *optional*, defaults to `8`): + Number of samples drawn from the reference policy per prompt to estimate `V*`. + beta1 (`float`, *optional*, defaults to `0.5`): + KL temperature used to estimate `V*` in Stage 1. + filter_all_incorrect (`bool`, *optional*, defaults to `True`): + Whether to drop prompts for which all reference samples are incorrect. + + > Parameters that control Stage 2 (on-policy regression) + + beta2 (`float`, *optional*, defaults to `1e-3`): + KL temperature used in the Stage 2 regression target. + reward_weights (`list[float]`, *optional*): + Weights for each reward function. Must match the number of reward functions. If `None`, all rewards are + weighted equally with weight `1.0`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters that control the model and reference model + model_init_kwargs: dict | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of " + "the `A2POTrainer` is provided as a string." + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. " + "Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoTokenizer.from_pretrained`." + }, + ) + + # Parameters that control the data preprocessing + remove_unused_columns: bool = field( + default=False, + metadata={ + "help": "Whether to only keep the column 'prompt' in the dataset. If you use a custom reward function " + "that requires any column other than 'prompts' and 'completions', you should keep this to `False`." + }, + ) + + # Parameters that control generation + max_prompt_length: int | None = field( + default=512, + metadata={"help": "Maximum length of the prompt. If the prompt is longer than this, it is left-truncated."}, + ) + max_completion_length: int | None = field( + default=256, metadata={"help": "Maximum length of the generated completion."} + ) + temperature: float = field( + default=1.0, + metadata={"help": "Sampling temperature, used in both Stage 1 and Stage 2 generation."}, + ) + top_p: float = field( + default=1.0, + metadata={ + "help": "Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. " + "Set to `1.0` to consider all tokens." + }, + ) + top_k: int | None = field( + default=None, + metadata={ + "help": "Number of highest-probability vocabulary tokens to keep. If `None`, top-k filtering is disabled." + }, + ) + + # Parameters that control Stage 1 (offline optimal value estimation) + num_value_samples: int = field( + default=8, + metadata={"help": "Number of samples drawn from the reference policy per prompt to estimate `V*`."}, + ) + beta1: float = field( + default=0.5, + metadata={"help": "KL temperature used to estimate `V*` in Stage 1."}, + ) + filter_all_incorrect: bool = field( + default=True, + metadata={"help": "Whether to drop prompts for which all reference samples are incorrect."}, + ) + + # Parameters that control Stage 2 (on-policy regression) + beta2: float = field( + default=1e-3, + metadata={"help": "KL temperature used in the Stage 2 regression target."}, + ) + reward_weights: list[float] | None = field( + default=None, + metadata={ + "help": "Weights for each reward function. Must match the number of reward functions. If `None`, all " + "rewards are weighted equally with weight `1.0`." + }, + ) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/a2po/a2po_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/a2po/a2po_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..2fad6ed25ba8af0c1062fa0df3248ad164bd9dd4 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/a2po/a2po_trainer.py @@ -0,0 +1,375 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import math +import textwrap +from collections import defaultdict +from collections.abc import Callable + +import torch +from accelerate.logging import get_logger +from accelerate.utils import gather_object +from torch.utils.data import DataLoader +from transformers import ( + AutoModelForCausalLM, + AutoTokenizer, + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, +) + +from ...data_utils import maybe_apply_chat_template +from ...models import create_reference_model, unwrap_model_for_generation +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import selective_log_softmax +from .a2po_config import A2POConfig + + +logger = get_logger(__name__) + +# A reward function is a callable that returns a list of floats (the rewards). The callable receives prompts, +# completions, and additional columns from the dataset. To ensure forward compatibility, it should accept **kwargs. +RewardFunc = Callable[..., list[float]] + + +class A2POTrainer(_BaseTrainer): + # docstyle-ignore + """ + Trainer for the A*-PO (Optimal Advantage Regression) method, introduced in [Accelerating RL for LLM Reasoning with + Optimal Advantage Regression](https://huggingface.co/papers/2505.20686). + + A*-PO runs in two stages: + + 1. **Offline value estimation.** Before training, `num_value_samples` completions are sampled from the reference + policy for every training prompt and scored with `reward_funcs`. The optimal value is estimated as + `V*(x) = beta1 * log(mean_i exp(r(x, y_i) / beta1))` and cached per prompt. + 2. **On-policy regression.** During training, a single completion is generated per prompt from the current policy. + The loss is the squared error between the implicit reward `beta2 * log(pi(y|x) / pi_ref(y|x))` and the optimal + advantage estimate `r(x, y) - V*(x)`. + + Args: + model (`PreTrainedModel` or `str`): + Model to be trained, or a model identifier (string) passed to + [`~transformers.AutoModelForCausalLM.from_pretrained`]. + reward_funcs (`Callable` or `list[Callable]`): + Reward function(s). Each takes `prompts` and `completions` (plus dataset columns as keyword arguments) and + returns a list of float rewards. When multiple are provided, their weighted sum (see + [`A2POConfig.reward_weights`]) is the scalar reward `r`, which A*-PO assumes to be binary (in `{0, 1}`). + args ([`A2POConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + train_dataset ([`~datasets.Dataset`], *optional*): + Training dataset. Must contain a `"prompt"` column. + eval_dataset ([`~datasets.Dataset`], *optional*): + Evaluation dataset. + processing_class ([`~transformers.PreTrainedTokenizerBase`], *optional*): + Processing class used to process the data. If `None`, it is loaded from the model's name with + [`~transformers.AutoTokenizer.from_pretrained`]. + callbacks (`list[~transformers.TrainerCallback]`, *optional*): + List of callbacks to customize the training loop. + optimizers (`tuple[~torch.optim.Optimizer, ~torch.optim.lr_scheduler.LambdaLR]`, *optional*, defaults to `(None, None)`): + Tuple containing the optimizer and the learning rate scheduler. + """ + + _tag_names = ["trl", "a2po"] + _name = "A2PO" + _paper = { + "title": "Accelerating RL for LLM Reasoning with Optimal Advantage Regression", + "id": "2505.20686", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{brantley2025accelerating, + title = {{Accelerating RL for LLM Reasoning with Optimal Advantage Regression}}, + author = {Kiant\'e Brantley and Mingyu Chen and Zhaolin Gao and Jason D. Lee and Wen Sun and Wenhao Zhan and Xuezhou Zhang}, + year = 2025, + eprint = {arXiv:2505.20686}, + }"""), + } + + def __init__( + self, + model: PreTrainedModel | str, + reward_funcs: RewardFunc | list[RewardFunc], + args: A2POConfig | None = None, + train_dataset=None, + eval_dataset=None, + processing_class: PreTrainedTokenizerBase | None = None, + callbacks=None, + optimizers=(None, None), + ): + # Args + if args is None: + args = A2POConfig(f"{model if isinstance(model, str) else model.config._name_or_path}-A2PO") + + # Models + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs) + model_id = model.config._name_or_path + + # Some models (e.g. SmolVLM/Idefics3) don't support the `logits_to_keep` argument and error out if we pass it. + # Inspect the forward method so Stage 2 can pass the argument only when it is supported. + self.model_kwarg_keys = inspect.signature(model.forward).parameters.keys() + + # Reference model: a frozen copy of the initial policy. Stage 1 samples from it and Stage 2 regularizes to it. + self.ref_model = create_reference_model(model) + + # Processing class + if processing_class is None: + processing_class = AutoTokenizer.from_pretrained( + model_id, padding_side="left", trust_remote_code=args.trust_remote_code + ) + + # Reward functions + if not isinstance(reward_funcs, list): + reward_funcs = [reward_funcs] + self.reward_funcs = reward_funcs + if args.reward_weights is None: + self.reward_weights = torch.ones(len(reward_funcs), dtype=torch.float32) + else: + self.reward_weights = torch.tensor(args.reward_weights, dtype=torch.float32) + + # Generation: N samples per prompt in Stage 1, a single sample in Stage 2 + self.value_generation_config = GenerationConfig( + max_new_tokens=args.max_completion_length, + do_sample=True, + temperature=args.temperature, + top_p=args.top_p, + top_k=args.top_k, + num_return_sequences=args.num_value_samples, + pad_token_id=processing_class.pad_token_id, + ) + self.generation_config = GenerationConfig( + max_new_tokens=args.max_completion_length, + do_sample=True, + temperature=args.temperature, + top_p=args.top_p, + top_k=args.top_k, + num_return_sequences=1, + pad_token_id=processing_class.pad_token_id, + ) + + # Optimal values V*(x), keyed by prompt text. Populated lazily by Stage 1 at the start of training. + self._optimal_values: dict[str, float] | None = None + + # Metrics + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + + # The data collator returns the list of features untouched; generation happens in `_prepare_inputs`. + def data_collator(features): + return features + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + callbacks=callbacks, + optimizers=optimizers, + ) + + self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True) + + def _calculate_rewards(self, prompts, completions, **reward_kwargs): + device = self.accelerator.device + rewards_per_func = torch.zeros(len(prompts), len(self.reward_funcs), device=device) + for i, reward_func in enumerate(self.reward_funcs): + output = reward_func(prompts=prompts, completions=completions, **reward_kwargs) + rewards_per_func[:, i] = torch.tensor(output, dtype=torch.float32, device=device) + # A*-PO assumes the (weighted) total reward is binary in {0, 1}. + return (rewards_per_func * self.reward_weights.to(device)).sum(dim=1) + + def _get_sequence_logps(self, model, input_ids, attention_mask, logits_to_keep): + model_inputs = {"input_ids": input_ids, "attention_mask": attention_mask} + # Only pass `logits_to_keep` when the model supports it (some models and VLMs don't). + if "logits_to_keep" in self.model_kwarg_keys: + # We add 1 to `logits_to_keep` because the last logits of the sequence is later excluded + model_inputs["logits_to_keep"] = logits_to_keep + 1 + logits = model(**model_inputs).logits + logits = logits[:, :-1, :] # the last logit predicts beyond the sequence + # Only keep the last logits_to_keep. For models that support logits_to_keep, this is a no-op. + logits = logits[:, -logits_to_keep:, :] + completion_ids = input_ids[:, -logits_to_keep:] + per_token_logps = selective_log_softmax(logits, completion_ids) + completion_mask = attention_mask[:, -logits_to_keep:] + return (per_token_logps * completion_mask).sum(dim=1) + + # Stage 1: offline optimal value estimation + def _estimate_optimal_values(self): + beta1 = self.args.beta1 + n = self.args.num_value_samples + optimal_values = {} + all_incorrect = set() + + # Stage 2 looks up V* for every prompt it scores, including eval prompts, so estimate over both datasets. + datasets = [self.train_dataset] if self.eval_dataset is None else [self.train_dataset, self.eval_dataset] + for dataset in datasets: + dataloader = self.accelerator.prepare( + DataLoader(dataset, batch_size=self.args.per_device_train_batch_size, collate_fn=list) + ) + for batch in dataloader: + prompts = [example["prompt"] for example in batch] + prompts_text = [ + maybe_apply_chat_template(example, self.processing_class)["prompt"] for example in batch + ] + + # Sample N completions per prompt from the reference policy + inputs = self.processing_class( + prompts_text, + return_tensors="pt", + padding=True, + truncation=True, + max_length=self.args.max_prompt_length, + add_special_tokens=False, + ).to(self.accelerator.device) + with unwrap_model_for_generation(self.ref_model, self.accelerator) as ref_model: + completion_ids = ref_model.generate(**inputs, generation_config=self.value_generation_config) + + prompt_length = inputs["input_ids"].size(1) + completions_text = self.processing_class.batch_decode( + completion_ids[:, prompt_length:], skip_special_tokens=True + ) + + # Each prompt is repeated N times by `num_return_sequences`. Forward any extra dataset columns (e.g. + # "solution") to the reward functions, repeated to align with the N samples per prompt. + keys = [key for key in batch[0] if key not in ["prompt", "completion"]] + reward_kwargs = {key: [example[key] for example in batch for _ in range(n)] for key in keys} + repeated_prompts = [p for p in prompts for _ in range(n)] + rewards = self._calculate_rewards(repeated_prompts, completions_text, **reward_kwargs) + rewards = rewards.view(len(prompts), n) + + # V*(x) = beta1 * log(mean_i exp(r_i / beta1)), computed stably + v_star = beta1 * (torch.logsumexp(rewards / beta1, dim=1) - math.log(n)) + + for j, prompt_text in enumerate(prompts_text): + optimal_values[prompt_text] = v_star[j].item() + if rewards[j].sum() == 0: + all_incorrect.add(prompt_text) + + # Each rank estimates V* for its shard of prompts; share them so any rank can score any prompt. + # `gather_object` concatenates the per-rank lists, so pass flat lists and rebuild on every rank. + self._optimal_values = dict(gather_object(list(optimal_values.items()))) + all_incorrect = set(gather_object(list(all_incorrect))) + + # Drop training prompts whose reference samples all scored zero (no learning signal). Eval prompts are kept + # so evaluation can still look up their V*. + if self.args.filter_all_incorrect: + self.train_dataset = self.train_dataset.filter( + lambda example: maybe_apply_chat_template(example, self.processing_class)["prompt"] + not in all_incorrect + ) + logger.info(f"Stage 1 complete: estimated V* for {len(self._optimal_values)} prompts.") + + # Stage 2: on-policy regression + def _prepare_inputs(self, inputs): + # Estimate V* on first use, e.g. when `evaluate()` is called without a preceding `train()`. + if self._optimal_values is None: + self._estimate_optimal_values() + mode = "train" if self.model.training else "eval" + device = self.accelerator.device + prompts = [example["prompt"] for example in inputs] + prompts_text = [maybe_apply_chat_template(example, self.processing_class)["prompt"] for example in inputs] + + # One on-policy completion per prompt + prompt_inputs = self.processing_class( + prompts_text, + return_tensors="pt", + padding=True, + truncation=True, + max_length=self.args.max_prompt_length, + add_special_tokens=False, + ).to(device) + with unwrap_model_for_generation(self.model, self.accelerator) as unwrapped_model: + prompt_completion_ids = unwrapped_model.generate(**prompt_inputs, generation_config=self.generation_config) + prompt_length = prompt_inputs["input_ids"].size(1) + completion_ids = prompt_completion_ids[:, prompt_length:] + completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + + # Scalar (binary) reward and cached optimal value. Forward extra dataset columns to the reward functions. + keys = [key for key in inputs[0] if key not in ["prompt", "completion"]] + reward_kwargs = {key: [example[key] for example in inputs] for key in keys} + rewards = self._calculate_rewards(prompts, completions_text, **reward_kwargs) + v_star = torch.tensor([self._optimal_values[p] for p in prompts_text], dtype=torch.float32, device=device) + + # Attention mask: the tokenizer's prompt mask followed by the completion mask. The completion mask is 1 up to + # and including the first EOS and 0 afterwards, so the terminal EOS stays in the log-prob sum (a plain + # `!= pad_token_id` mask would drop it when `pad_token == eos_token`). + is_eos = completion_ids == self.processing_class.eos_token_id + eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device) + eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)] + sequence_indices = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1) + completion_mask = (sequence_indices <= eos_idx.unsqueeze(1)).int() + attention_mask = torch.cat([prompt_inputs["attention_mask"], completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) + + with torch.no_grad(): + ref_logps = self._get_sequence_logps(self.ref_model, prompt_completion_ids, attention_mask, logits_to_keep) + + self._metrics[mode]["reward"].append(rewards.mean().item()) + self._metrics[mode]["v_star"].append(v_star.mean().item()) + + return { + "input_ids": prompt_completion_ids, + "attention_mask": attention_mask, + "logits_to_keep": logits_to_keep, + "ref_logps": ref_logps, + "rewards": rewards, + "v_star": v_star, + } + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + mode = "train" if self.model.training else "eval" + + policy_logps = self._get_sequence_logps( + model, inputs["input_ids"], inputs["attention_mask"], inputs["logits_to_keep"] + ) + + # Implicit reward beta2 * log(pi / pi_ref), regressed onto the optimal advantage r - V* + implicit_reward = self.args.beta2 * (policy_logps - inputs["ref_logps"]) + target = inputs["rewards"] - inputs["v_star"] + loss = ((implicit_reward - target) ** 2).mean() + + self._metrics[mode]["implicit_reward"].append(implicit_reward.mean().item()) + self._metrics[mode]["advantage"].append(target.mean().item()) + return loss + + def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys: list[str] | None = None): + inputs = self._prepare_inputs(inputs) + with torch.no_grad(): + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + loss = loss.mean().detach() + return loss, None, None + + def train(self, *args, **kwargs): + if self._optimal_values is None: + logger.info("Running Stage 1: offline optimal value estimation...") + self._estimate_optimal_values() + return super().train(*args, **kwargs) + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} + + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs = {**logs, **metrics} + super().log(logs, start_time) + self._metrics[mode].clear() diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/async_grpo/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/async_grpo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3fc30c059a76572f449ca53f59aeff47bd789cf5 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/async_grpo/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .async_grpo_config import AsyncGRPOConfig +from .async_grpo_trainer import AsyncGRPOTrainer diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/async_grpo/async_grpo_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/async_grpo/async_grpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..cf09fbe1c803a5589bcf71de6889867dfbf22378 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/async_grpo/async_grpo_config.py @@ -0,0 +1,268 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class AsyncGRPOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`AsyncGRPOTrainer`]. + + This class includes only the parameters that are specific to asynchronous GRPO training. For a full list of + training arguments, please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values + in this class may differ from those in [`~transformers.TrainingArguments`]. + + Parameters: + > Parameters that control the model + + model_init_kwargs (`dict[str, Any]` or `str`, *optional*): + Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when instantiating the + model from a path. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to + [`~transformers.AutoModelForCausalLM.from_pretrained`] and [`~transformers.AutoTokenizer.from_pretrained`]. + router_aux_loss_coef (`float`, *optional*, defaults to `0.001`): + Coefficient of the load-balancing auxiliary loss. Only has an effect when training a Mixture-of-Experts + (MoE) model; for other models it does nothing. The auxiliary loss is added to the training loss with this + weight. Set to `0.0` to disable it. + + > Parameters that control generation + + num_generations (`int`, *optional*, defaults to `8`): + Number of generations per prompt to sample. + max_completion_length (`int`, *optional*, defaults to `2048`): + Maximum number of tokens to generate per completion. + temperature (`float`, *optional*, defaults to `1.0`): + Temperature for sampling. The higher the temperature, the more random the completions. + chat_template_kwargs (`dict[str, Any]`, *optional*): + Additional keyword arguments to pass to the `apply_chat_template` function when generating completions. + max_tool_calling_iterations (`int`, *optional*): + Maximum number of tool-calling turns when training an agent. If `None`, there is no limit and generation + stops when the model generates a response turn with no tool calls or when the total response length reaches + `max_completion_length`. + + > Parameters that control the vLLM server + + vllm_server_base_url (`str`, *optional*, defaults to `"http://localhost:8000"`): + Base URL of the vLLM server used for generation (e.g., `"http://localhost:8000"`). + vllm_server_timeout (`float`, *optional*, defaults to `240.0`): + Total timeout duration in seconds to wait for the vLLM server to be ready. + request_timeout (`int`, *optional*, defaults to `600`): + Timeout in seconds for individual HTTP requests to the vLLM server. + + > Parameters that control the training + + epsilon (`float`, *optional*, defaults to `0.2`): + Epsilon value for clipping. + epsilon_high (`float`, *optional*): + Upper-bound epsilon value for clipping. If not specified, it defaults to the same value as the lower-bound + specified in argument `epsilon`. Paper [DAPO](https://huggingface.co/papers/2503.14476) recommends `0.28`. + + > Parameters that control the async rollout pipeline + + max_inflight_tasks (`int`, *optional*, defaults to `-1`): + Maximum number of concurrent generation tasks sent to the vLLM server. Defaults to `-1` (auto), which + sets it to `max_staleness * per_device_train_batch_size * gradient_accumulation_steps * num_processes`. + If using tool-use environments, you may want to set this manually based on how many parallel environments + you can run. + max_staleness (`int`, *optional*, defaults to `4`): + Maximum number of weight update steps a rollout sample can lag behind the current model version before + being discarded. + queue_maxsize (`int`, *optional*, defaults to `1024`): + Maximum number of rollout samples to buffer in the rollout queue. + weight_sync_steps (`int`, *optional*, defaults to `1`): + Number of training steps between weight synchronizations to the vLLM server. + heartbeat_stale_after_s (`float`, *optional*, defaults to `300.0`): + Seconds since the rollout worker's last heartbeat after which the trainer treats it as + hung and aborts. + + > Parameters that control the logging + + log_completions (`bool`, *optional*, defaults to `False`): + Whether to log a sample of (prompt, completion) pairs every `logging_steps` steps. + num_completions_to_print (`int`, *optional*): + Number of completions to print with `rich`. If `None`, all completions are logged. + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `1` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `1e-6` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters that control the model + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `transformers.AutoModelForCausalLM.from_pretrained`, used when instantiating " + "the model from a path." + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. " + "Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoTokenizer.from_pretrained`." + }, + ) + router_aux_loss_coef: float = field( + default=0.001, + metadata={ + "help": "Coefficient of the load-balancing auxiliary loss. Only has an effect when training a " + "Mixture-of-Experts (MoE) model; for other models it does nothing. The auxiliary loss is added to the " + "training loss with this weight. Set to `0.0` to disable it." + }, + ) + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=1e-6, + metadata={"help": "The initial learning rate for AdamW."}, + ) + logging_steps: float = field( + default=1, + metadata={ + "help": "Log every X update steps. Should be an integer or a float in range `[0,1)`. If smaller than 1, " + "will be interpreted as ratio of total training steps." + }, + ) + + # Parameters that control generation + num_generations: int = field( + default=8, + metadata={"help": "Number of generations per prompt to sample."}, + ) + max_completion_length: int = field( + default=2048, + metadata={"help": "Maximum number of tokens to generate per completion."}, + ) + temperature: float = field( + default=1.0, + metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."}, + ) + chat_template_kwargs: dict | None = field( + default=None, + metadata={ + "help": "Additional keyword arguments to pass to the `apply_chat_template` function when generating " + "completions." + }, + ) + max_tool_calling_iterations: int | None = field( + default=None, + metadata={ + "help": "Maximum number of tool-calling turns when training an agent. If `None`, there is no limit and " + "generation stops when the model generates a response turn with no tool calls or when the total response " + "length reaches `max_completion_length`." + }, + ) + + # Parameters that control the vLLM server + vllm_server_base_url: str = field( + default="http://localhost:8000", + metadata={"help": "Base URL of the vLLM server used for generation (e.g., 'http://localhost:8000')."}, + ) + vllm_server_timeout: float = field( + default=240.0, + metadata={ + "help": "Total timeout duration in seconds to wait for the vLLM server to be ready. If the server is not " + "up after the timeout, a `TimeoutError` is raised." + }, + ) + request_timeout: int = field( + default=600, + metadata={"help": "Timeout in seconds for individual HTTP requests to the vLLM server."}, + ) + + # Parameters that control the training + epsilon: float = field( + default=0.2, + metadata={"help": "Epsilon value for clipping."}, + ) + epsilon_high: float | None = field( + default=None, + metadata={ + "help": "Upper-bound epsilon value for clipping. If not specified, it defaults to the same value as the " + "lower-bound specified in argument `epsilon`. Paper DAPO recommends `0.28`." + }, + ) + + # Parameters that control the async rollout pipeline + max_inflight_tasks: int = field( + default=-1, + metadata={ + "help": "Maximum number of concurrent generation tasks sent to the vLLM server. Defaults to -1 (auto), " + "which sets it to `max_staleness * per_device_train_batch_size * gradient_accumulation_steps * " + "num_processes`. Generating more samples than this is wasteful since they will be discarded as stale " + "before the trainer can consume them. If using tool-use environments, you may want to set this manually " + "based on how many parallel environments you can run." + }, + ) + max_staleness: int = field( + default=4, + metadata={ + "help": "Maximum number of weight update steps a rollout sample can lag behind the current model version " + "before being discarded." + }, + ) + queue_maxsize: int = field( + default=1024, + metadata={"help": "Maximum number of rollout samples to buffer in the rollout queue."}, + ) + weight_sync_steps: int = field( + default=1, + metadata={"help": "Number of training steps between weight synchronizations to the vLLM server."}, + ) + heartbeat_stale_after_s: float = field( + default=300.0, + metadata={ + "help": "Seconds since the rollout worker's last heartbeat after which the trainer treats it as hung " + "and aborts." + }, + ) + + # Parameters that control the logging + log_completions: bool = field( + default=False, + metadata={ + "help": "Whether to log a sample of (prompt, completion) pairs every `logging_steps` steps. If `rich` is " + "installed, it prints the sample. If `wandb` logging is enabled, it logs it to `wandb`." + }, + ) + num_completions_to_print: int | None = field( + default=None, + metadata={"help": "Number of completions to print with `rich`. If `None`, all completions are logged."}, + ) + + def __post_init__(self): + super().__post_init__() + + # Accelerator config: required for the async IterableDataset-backed dataloader to work correctly. + # split_batches=True and dispatch_batches=True ensure that the main process drives the dataloader + # and batches are broadcast to other processes rather than each process pulling independently. + if not hasattr(self, "accelerator_config") or self.accelerator_config is None: + self.accelerator_config = {"split_batches": True, "dispatch_batches": True} + elif isinstance(self.accelerator_config, dict): + self.accelerator_config["split_batches"] = True + self.accelerator_config["dispatch_batches"] = True + else: + self.accelerator_config.split_batches = True + self.accelerator_config.dispatch_batches = True diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/async_grpo/async_grpo_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/async_grpo/async_grpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..0ed68f815d45a2538d8b40bc570523a9f9f5e24d --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/async_grpo/async_grpo_trainer.py @@ -0,0 +1,825 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import math +import queue +import textwrap +import time +from collections import defaultdict +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any, Protocol + +import torch +from accelerate.logging import get_logger +from datasets import Dataset, IterableDataset +from torch.distributed._tensor import DTensor +from torch.utils.data import DataLoader +from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerBase, TrainerCallback +from transformers.data.data_collator import DataCollatorMixin + +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import nanmax, nanmin, pad, patch_chunked_lm_head +from .async_grpo_config import AsyncGRPOConfig +from .async_rollout_worker import AsyncRolloutWorker +from .weight_transfer import WeightTransferClient + + +logger = get_logger(__name__) + +# A reward function is a callable that returns a list of floats (the rewards). The callable receives prompts, +# completions, and additional arguments from the trainer (refer to the trainer's source for details). To ensure forward +# compatibility, it should accept **kwargs. +RewardFunc = Callable[..., list[float]] + + +class _SupportsReset(Protocol): + def reset(self, **kwargs) -> str | None: ... + + +EnvironmentFactory = Callable[[], _SupportsReset] + + +class RolloutWorkerProtocol(Protocol): + """Interface a rollout worker must implement to be passed as `rollout_worker` to [`AsyncGRPOTrainer`]. + + The default [`AsyncRolloutWorker`] spawns a CUDA-free child process and scores completions with the trainer's + `reward_funcs`. Implement this protocol to plug in a custom rollout/scoring backend instead — for example, one that + runs reward models on their own GPUs. + + Attributes: + rollout_buffer (`queue.Queue`): + Queue the trainer drains; the worker pushes scored `RolloutSample`s onto it. + """ + + rollout_buffer: queue.Queue + + def start(self) -> None: + """Begin producing rollouts. Called once on train begin, after the initial weight sync.""" + ... + + def stop(self) -> None: + """Stop the worker and release its resources. Called on train end.""" + ... + + def update_model_version(self, version: int) -> None: + """Tell the worker which policy version is now live, so it can tag or discard stale samples.""" + ... + + def check_health(self, stale_after_s: float) -> None: + """Raise if the worker has crashed or stopped producing within `stale_after_s` seconds.""" + ... + + +class StepIntervalCallback(TrainerCallback): + """ + A callback that calls a function every N optimization steps. + """ + + def __init__(self, fn, every_n_steps: int): + self.fn = fn + self.every_n_steps = every_n_steps + + def on_step_end(self, _args, state, _control, **_kwargs): + if state.global_step % self.every_n_steps == 0: + self.fn() + + +class _InitialWeightSyncCallback(TrainerCallback): + """Idempotent: NCCL group setup + cold weight sync to vLLM on train begin.""" + + def __init__(self, trainer: "AsyncGRPOTrainer"): + self._trainer = trainer + self._fired = False + + def on_train_begin(self, _args, _state, _control, **_kwargs): + if self._fired: + return + self._fired = True + if self._trainer.accelerator.is_main_process and self._trainer.weight_transfer is not None: + self._trainer.weight_transfer.init_weight_transfer() + self._trainer._sync_weight() + + +class _StartRolloutWorkerCallback(TrainerCallback): + """Idempotent: starts the rollout worker. Must be registered AFTER `_InitialWeightSyncCallback`.""" + + def __init__(self, trainer: "AsyncGRPOTrainer"): + self._trainer = trainer + self._fired = False + + def on_train_begin(self, _args, _state, _control, **_kwargs): + if self._fired: + return + self._fired = True + if self._trainer.accelerator.is_main_process and self._trainer.rollout_worker is not None: + self._trainer.rollout_worker.start() + + +class RolloutQueueDataset(torch.utils.data.IterableDataset): + def __init__( + self, + rollout_queue, + model_version_fn, + check_health_fn, + stale_after_s, + max_staleness=3, + poll_interval_s=5.0, + ): + self.queue = rollout_queue + self.model_version_fn = model_version_fn + self.check_health_fn = check_health_fn + self.stale_after_s = stale_after_s + self.max_staleness = max_staleness + self.poll_interval_s = poll_interval_s + + def __iter__(self): + while True: + t0 = time.time() + if self.queue.qsize() == 0: + logger.info("queue empty, waiting for rollout samples...") + try: + sample = self.queue.get(timeout=self.poll_interval_s) + except queue.Empty: + # Returning here would broadcast None through accelerate's dispatch loop. + self.check_health_fn(self.stale_after_s) + continue + queue_wait_time_s = time.time() - t0 + if queue_wait_time_s > 1.0: + logger.info(f"waited {queue_wait_time_s:.1f}s for sample (qsize={self.queue.qsize()})") + + staleness = self.model_version_fn() - sample.model_version + if staleness > self.max_staleness: + logger.info(f"dropping stale sample (staleness={staleness}, max={self.max_staleness})") + continue # drop stale, pull next + + yield { + "input_ids": sample.input_ids, + "completion_mask": sample.completion_mask, + "old_log_probs": sample.old_log_probs, + "advantage": sample.advantage, + "metrics": {**sample.metrics, "queue_wait_time_s": queue_wait_time_s}, + } + + +class _EmptyIterableDataset(torch.utils.data.IterableDataset): + """Placeholder for non-rank-0 processes. Never actually iterated.""" + + def __iter__(self): + return iter([]) + + +@dataclass +class DataCollatorForRollout(DataCollatorMixin): + """ + Padding-free collator for rollout samples. Splits the global batch into `num_processes` groups (one per rank) and + concatenates each group's samples into a single packed row, with `position_ids` resetting per sequence and + advantages expanded per-token. Rows are padded only to the longest group, so the batch stays rectangular for + `DataLoaderDispatcher` to scatter row `i` -> rank `i`; this inter-rank padding is stripped per-rank in + `compute_loss`. + + Args: + pad_token_id (`int`): + Token id used to pad `input_ids`. + num_processes (`int`, *optional*, defaults to `1`): + Number of ranks; the global batch is packed into this many rows. + """ + + pad_token_id: int + num_processes: int = 1 + return_tensors: str = "pt" + + def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + groups = [examples[i :: self.num_processes] for i in range(self.num_processes)] + + input_ids, attention_mask, completion_mask, old_log_probs, position_ids, advantages = [], [], [], [], [], [] + for group in groups: + seq_lengths = [len(example["input_ids"]) for example in group] + ids = [token for example in group for token in example["input_ids"]] + input_ids.append(torch.tensor(ids, dtype=torch.long)) + attention_mask.append(torch.ones(len(ids), dtype=torch.long)) + completion_mask.append( + torch.tensor([m for example in group for m in example["completion_mask"]], dtype=torch.long) + ) + old_log_probs.append( + torch.tensor([lp for example in group for lp in example["old_log_probs"]], dtype=torch.float32) + ) + position_ids.append(torch.cat([torch.arange(n) for n in seq_lengths])) + advantages.append( + torch.cat( + [torch.full((n,), example["advantage"]) for example, n in zip(group, seq_lengths, strict=False)] + ) + ) + + input_ids = pad(input_ids, padding_value=self.pad_token_id) + attention_mask = pad(attention_mask, padding_value=0) + completion_mask = pad(completion_mask, padding_value=0) + old_log_probs = pad(old_log_probs, padding_value=0.0) + position_ids = pad(position_ids, padding_value=0) + advantages = pad(advantages, padding_value=0.0) + + # Total valid completion tokens across all samples in the full batch. + # Repeated per rank so that DataLoaderDispatcher (dispatch_batches=True) slices correctly on dim=0 + global_n_tokens = sum(sum(example["completion_mask"]) for example in examples) + global_n_tokens = torch.full((self.num_processes,), float(global_n_tokens), dtype=torch.float32) + + # Per-sample metrics grouped per rank, as a dict of 2D tensors (one row per rank) so that Accelerate's + # recursive broadcast (dispatch_batches=True) can scatter them — it traverses nested dicts of tensors but + # chokes on plain Python floats. Rows are padded with NaN so padded slots are ignored by the nan-aware + # aggregation in `compute_loss`. + metrics_list = [example["metrics"] for example in examples] + metrics = ( + { + key: pad( + [ + torch.tensor([example["metrics"].get(key, 0.0) for example in group], dtype=torch.float32) + for group in groups + ], + padding_value=float("nan"), + ) + for key in metrics_list[0] + } + if metrics_list and metrics_list[0] + else {} + ) + + return { + "input_ids": input_ids, + "attention_mask": attention_mask, + "completion_mask": completion_mask, + "old_log_probs": old_log_probs, + "position_ids": position_ids, + "advantages": advantages, + "global_n_tokens": global_n_tokens, + "metrics": metrics, + } + + +class AsyncGRPOTrainer(_BaseTrainer): + """ + Trainer for the Group Relative Policy Optimization (GRPO) method. This algorithm was initially proposed in the + paper [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language + Models](https://huggingface.co/papers/2402.03300). This trainer is the asynchronous version of GRPO, where + generation is offloaded to an external vLLM server that runs asynchronously alongside training, decoupling rollout + from the gradient update loop. + + Example: + + ```python + >>> from trl.experimental.async_grpo import AsyncGRPOTrainer + >>> from trl.rewards import accuracy_reward + >>> from datasets import load_dataset + + >>> dataset = load_dataset("trl-lib/DeepMath-103K", split="train") + + >>> trainer = AsyncGRPOTrainer( + ... model="Qwen/Qwen2.5-0.5B-Instruct", + ... reward_funcs=accuracy_reward, + ... train_dataset=dataset, + ... ) + >>> trainer.train() + ``` + + Args: + model (`str`): + Model to be trained. Must be a string, being the *model id* of a pretrained model hosted inside a model + repo on huggingface.co, or a path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using [`~transformers.AutoModelForCausalLM.from_pretrained`]. The model name is also used to identify the + model on the vLLM server used for generation. + reward_funcs (`RewardFunc | list[RewardFunc]`): + Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward + functions with the prompts and completions and sum the rewards. Can be either: + + - A single reward function: The function is provided with the prompts and the generated completions, plus + any additional columns in the dataset. It should return a list of rewards. Reward functions can be either + synchronous or asynchronous and can also return `None` when the reward is not applicable to those + samples. This is useful for multi-task training where different reward functions apply to different types + of samples. When a reward function returns `None` for a sample, that reward function is excluded from the + reward calculation for that sample. For more details, see [Using a custom reward + function](#using-a-custom-reward-function). + - A list of reward functions, where each item is a reward function as described above. Rewards from all + functions are summed. + + Unlike [`GRPOTrainer`], rewards are computed in a spawned child process, so each reward function (along + with `tools` and `environment_factory`) must be picklable: use a module-level function, + `functools.partial`, or a callable class instance — lambdas and closures will fail at startup. The child + process also runs with `CUDA_VISIBLE_DEVICES=""`, so a GPU-backed reward model runs on CPU (slow), not the + trainer's GPU. + args ([`AsyncGRPOConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset are + ignored. The format of the samples can be either: + + - [Standard](dataset_formats#standard): Each sample contains plain text. + - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role + and content). + processing_class ([`~transformers.PreTrainedTokenizerBase`], *optional*): + Processing class used to process the data. The padding side must be set to `"left"`. If `None`, the + processing class is loaded from the model's name with [`~transformers.AutoTokenizer.from_pretrained`]. A + padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token, + `tokenizer.eos_token` will be used as the default. + callbacks (list of [`~transformers.TrainerCallback`], *optional*): + List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed + in [here](https://huggingface.co/docs/transformers/main_classes/callback). + + If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`] + method. + optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`): + A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your + model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`. + tools (list of `Callable`, *optional*): + A list of callable tool functions (sync or async) that the model can invoke during generation. Each tool + should be a standard Python function with properly type-hinted arguments and return values, and a + Google-style docstring describing its purpose, arguments, and return value. For more details, see: + https://huggingface.co/docs/transformers/en/chat_extras#passing-tools. The model uses the function's name, + type hints, and docstring to determine how to call it. Ensure that the model's chat template supports tool + use and that it has been fine-tuned for tool calling. + environment_factory (`EnvironmentFactory`, *optional*): + A callable that creates and returns an environment instance. The environment class should define methods + that can be invoked as tools during generation. Each method should comply with the same requirements as the + `tools` described above. If `environment_factory` is provided, an instance of the environment is created + for each generation in the batch, allowing for parallel and independent interactions. The environment must + also implement a callable `reset` method that can be used to reset state between generations. The `reset` + method should return either `None` or a string: when it returns a string, that string is appended to the + last user message before generation. This feature is experimental and may change or be removed at any time + without prior notice. + rollout_worker (`RolloutWorkerProtocol`, *optional*): + Custom rollout worker implementing [`RolloutWorkerProtocol`]. If `None`, a default [`AsyncRolloutWorker`] + is created, which spawns a CUDA-free child process and scores completions with the trainer's + `reward_funcs`. Pass a custom worker to plug in a different rollout/scoring backend instead — for example, + one that runs reward models on their own GPUs. + """ + + _tag_names = ["trl", "async-grpo"] + _name = "AsyncGRPO" + _paper = { + "title": "DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models", + "id": "2402.03300", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{shao2024deepseekmath, + title = {{DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models}}, + author = {Zhihong Shao and Peiyi Wang and Qihao Zhu and Runxin Xu and Junxiao Song and Mingchuan Zhang and Y. K. Li and Y. Wu and Daya Guo}, + year = 2024, + eprint = {arXiv:2402.03300}, + }"""), + } + + def __init__( + self, + model: str, + reward_funcs: RewardFunc | list[RewardFunc], + args: AsyncGRPOConfig | None = None, + train_dataset: Dataset | IterableDataset | None = None, + processing_class: PreTrainedTokenizerBase | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + tools: list[Callable] | None = None, + environment_factory: EnvironmentFactory | None = None, + rollout_worker: RolloutWorkerProtocol | None = None, + ): + self.args = args or AsyncGRPOConfig() + + # Training arguments + self.epsilon_low = self.args.epsilon + self.epsilon_high = self.args.epsilon_high if self.args.epsilon_high is not None else self.args.epsilon + self.temperature = self.args.temperature + + # Model + model_name = model + model_init_kwargs = self.args.model_init_kwargs or {} + model_init_kwargs.setdefault("trust_remote_code", self.args.trust_remote_code) + # FlashAttention is required: training runs in padding-free mode, where sequences are concatenated into a + # single row and `cu_seq_lens` are derived from `position_ids` resets. SDPA/eager can't handle this. + model = AutoModelForCausalLM.from_pretrained( + model_name, + device_map=None, + dtype=torch.float32, + attn_implementation="kernels-community/flash-attn3", + **model_init_kwargs, + ) + + if self.args.use_liger_kernel: + raise NotImplementedError("`use_liger_kernel` is not supported yet.") + + # MoE load-balancing auxiliary loss, applied to Mixture-of-Experts models (no effect otherwise) + text_config = model.config.get_text_config() + is_moe = getattr(text_config, "output_router_logits", None) is not None + self.aux_loss_enabled = is_moe and self.args.router_aux_loss_coef != 0.0 + self.router_aux_loss_coef = self.args.router_aux_loss_coef + + patch_chunked_lm_head( + model, chunk_size=8192, temperature=self.temperature, output_router_logits=self.aux_loss_enabled + ) + + # Processing class + if processing_class is None: + processing_class = AutoTokenizer.from_pretrained(model_name, trust_remote_code=self.args.trust_remote_code) + if processing_class.pad_token is None: + processing_class.pad_token = processing_class.eos_token + + # Reward functions + if not isinstance(reward_funcs, list): + reward_funcs = [reward_funcs] + + # Initialize the Trainer + super().__init__( + model=model, + args=self.args, + train_dataset=train_dataset, + processing_class=processing_class, + callbacks=callbacks, + optimizers=optimizers, + compute_loss_func="non-None value to disable scaling", + ) + # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the + # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set + # self.model_accepts_loss_kwargs to False to enable scaling. + self.model_accepts_loss_kwargs = False + + # Infer max_steps from dataset size when not explicitly set. This must happen after super().__init__() + # so that self.accelerator.num_processes is available for the correct calculation. + samples_per_step = ( + self.args.per_device_train_batch_size + * self.args.gradient_accumulation_steps + * self.accelerator.num_processes + ) + if self.args.max_steps <= 0 and train_dataset is not None and hasattr(train_dataset, "__len__"): + samples_per_epoch = len(train_dataset) * self.args.num_generations + self.args.max_steps = int(self.args.num_train_epochs * samples_per_epoch / samples_per_step) + + # Infer max_inflight_tasks when not explicitly set. Generating more samples than the trainer can consume + # before they become stale is wasteful. The useful upper bound is max_staleness * samples_per_step. + if self.args.max_inflight_tasks < 0: + self.args.max_inflight_tasks = self.args.max_staleness * samples_per_step + logger.info( + f"max_inflight_tasks set to {self.args.max_inflight_tasks} " + f"(max_staleness={self.args.max_staleness} × samples_per_step={samples_per_step})" + ) + + # Initialize the metrics + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + self._train_tokens_start_time = None + self.model_version = 0 + # Create worker and queue on rank 0 + if self.accelerator.is_main_process: + if self.train_dataset is None: + raise ValueError("train_dataset is required for AsyncGRPOTrainer") + + if rollout_worker is not None: + # Use the injected worker (e.g. a stub in tests). The queue is owned by the worker. + # Weight transfer is also expected to be wired by the test fixture (or left as None + # if the stub doesn't sync to a real vLLM). + self.rollout_worker = rollout_worker + self.weight_transfer = None + else: + # Collect weight metadata once — names/dtypes/shapes are fixed for the lifetime of training. + # DTensor.shape returns the global shape without triggering any all-gather. + weight_names, weight_dtype_names, weight_shapes = [], [], [] + for name, param in model.named_parameters(): + # DDP/FSDP1 wrapping, avoids vllm module not exist error + name = name.removeprefix("module.") + weight_names.append(name) + weight_dtype_names.append(str(param.dtype).split(".")[-1]) + weight_shapes.append(list(param.shape)) + self.weight_transfer = WeightTransferClient( + vllm_server_url=self.args.vllm_server_base_url, + server_timeout=self.args.vllm_server_timeout, + weight_update_info={ + "names": weight_names, + "dtype_names": weight_dtype_names, + "shapes": weight_shapes, + "packed": True, + }, + ) + self.rollout_worker = AsyncRolloutWorker( + model_name=model_name, + dataset=train_dataset, + reward_funcs=reward_funcs, + processing_class=processing_class, + tools=tools, + environment_factory=environment_factory, + num_generations=self.args.num_generations, + max_inflight_tasks=self.args.max_inflight_tasks, + queue_maxsize=self.args.queue_maxsize, + vllm_server_url=self.args.vllm_server_base_url, + max_tokens=self.args.max_completion_length, + temperature=self.args.temperature, + request_timeout=self.args.request_timeout, + chat_template_kwargs=self.args.chat_template_kwargs, + max_tool_calling_iterations=self.args.max_tool_calling_iterations, + log_completions=self.args.log_completions, + num_completions_to_print=self.args.num_completions_to_print, + ) + # TODO(@aminediro): decide if this is returned by the worker or common API that is passed to the worker later. + self.rollout_queue = self.rollout_worker.rollout_buffer + else: + self.rollout_queue = None + self.rollout_worker = None + self.weight_transfer = None + + # Add callbacks. Registration order matters: weight sync first, then worker start. + self.add_callback(_InitialWeightSyncCallback(self)) + self.add_callback(_StartRolloutWorkerCallback(self)) + self.add_callback(StepIntervalCallback(self._sync_weight, self.args.weight_sync_steps)) + + def get_train_dataloader(self) -> DataLoader: + if self.accelerator.is_main_process: + dataset = RolloutQueueDataset( + rollout_queue=self.rollout_queue, + model_version_fn=lambda: self.model_version, + check_health_fn=self.rollout_worker.check_health, + stale_after_s=self.args.heartbeat_stale_after_s, + max_staleness=self.args.max_staleness, + ) + else: + dataset = _EmptyIterableDataset() + + return self.accelerator.prepare( + DataLoader( + dataset, + batch_size=self.args.per_device_train_batch_size * self.accelerator.num_processes, + collate_fn=DataCollatorForRollout(self.processing_class.pad_token_id, self.accelerator.num_processes), + num_workers=0, + # NOTE(@aminediro): + # dispatch_batches = True for DataLoader whose underlying dataset is an IterableDataset + # dataloader prepared by the Accelerator is only iterated through on the main process a + ) + ) + + def _set_signature_columns_if_needed(self): + # If `self.args.remove_unused_columns` is True, non-signature columns are removed. + # By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids" + # and "attention_mask"). In AsyncGRPOTrainer, we need additional columns ("completion_mask", "old_log_probs", + # "advantages", "global_n_tokens") to compute the loss, hence the override. + if self._signature_columns is None: + self._signature_columns = [ + "input_ids", + "attention_mask", + "completion_mask", + "old_log_probs", + "position_ids", + "advantages", + "global_n_tokens", + "metrics", + ] + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + # Padding-free: the collator already packed this rank's samples into a single row (real tokens concatenated, + # `position_ids` resetting per sequence, advantages expanded per-token), then padded the row to the longest + # rank's length so DataLoaderDispatcher could scatter rectangular rows. Strip that trailing inter-rank padding + # here. + mask_bool = inputs["attention_mask"].bool() + input_ids = inputs["input_ids"][mask_bool].unsqueeze(0) + completion_mask = inputs["completion_mask"][mask_bool].unsqueeze(0) + old_log_probs = inputs["old_log_probs"][mask_bool].unsqueeze(0) + position_ids = inputs["position_ids"][mask_bool].unsqueeze(0) + advantages = inputs["advantages"][mask_bool].unsqueeze(0) + + forward_start = time.time() + outputs = model( + input_ids=input_ids, + position_ids=position_ids, + labels=input_ids, + completion_mask=completion_mask, + use_cache=False, + ) + log_probs, entropy = outputs["log_probs"], outputs["entropy"] + self._last_forward_time_s = time.time() - forward_start + + completion_mask = completion_mask[:, 1:] + old_log_probs = old_log_probs[:, 1:] + advantages = advantages[:, 1:] + log_ratio = log_probs - old_log_probs + coef_1 = torch.exp(log_ratio) + coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high) + per_token_loss1 = coef_1 * advantages + per_token_loss2 = coef_2 * advantages + per_token_loss = -torch.min(per_token_loss1, per_token_loss2) + + # DDP/FSDP averages gradients across ranks (world_size). + # To get correct per-token normalization we scale by 1/tokens_per_rank + # = world_size / global_n_tokens, so after DDP averaging the effective + loss = (per_token_loss * completion_mask).sum() + global_n_tokens = inputs["global_n_tokens"][0] + world_size = self.accelerator.num_processes + tokens_per_rank = (global_n_tokens / world_size).clamp(min=1.0) + loss = loss / tokens_per_rank.to(torch.float32) + # For DAPO, we would scale like this instead: + # loss = loss / max(per_token_loss.size(0), 1) + loss = loss / self.current_gradient_accumulation_steps + + # The policy loss above is scaled for gradient accumulation (HF auto-scaling is off here), so scale aux too + if self.aux_loss_enabled: + aux_loss = outputs["aux_loss"] + loss = loss + self.router_aux_loss_coef * aux_loss / self.current_gradient_accumulation_steps + + with torch.no_grad(): + valid_mask = completion_mask > 0 + local_count = valid_mask.sum().float() + + local_ratio_sum = ( + coef_1[valid_mask].sum() if valid_mask.any() else torch.zeros((), device=completion_mask.device) + ) + # Approx KL: http://joschu.net/blog/kl-approx.html + local_kl_sum = ( + ((coef_1[valid_mask] - 1) - log_ratio[valid_mask]).sum() + if valid_mask.any() + else torch.zeros((), device=completion_mask.device) + ) + + local_entropy_sum = ( + entropy[valid_mask].sum() if valid_mask.any() else torch.zeros((), device=completion_mask.device) + ) + + # Compute the clipped probability ratios. A token is counted as clipped only when clipping is binding in a + # policy-relevant direction: low clip when the advantage is negative, high clip when it is positive. + is_low_clipped = (coef_1 < 1 - self.epsilon_low) & (advantages < 0) + is_high_clipped = (coef_1 > 1 + self.epsilon_high) & (advantages > 0) + is_region_clipped = is_low_clipped | is_high_clipped + local_low_clip_sum = ( + is_low_clipped[valid_mask].float().sum() + if valid_mask.any() + else torch.zeros((), device=completion_mask.device) + ) + local_high_clip_sum = ( + is_high_clipped[valid_mask].float().sum() + if valid_mask.any() + else torch.zeros((), device=completion_mask.device) + ) + local_region_clip_sum = ( + is_region_clipped[valid_mask].float().sum() + if valid_mask.any() + else torch.zeros((), device=completion_mask.device) + ) + + # Per-rank clip fractions, gathered below to report the cross-rank saturation extrema. + local_low_clip_mean = local_low_clip_sum / local_count.clamp(min=1.0) + local_high_clip_mean = local_high_clip_sum / local_count.clamp(min=1.0) + + # Batch all-reduce: [ratio_sum, kl_sum, entropy_sum, low_clip_sum, high_clip_sum, region_clip_sum, count] + stats = torch.stack( + [ + local_ratio_sum, + local_kl_sum, + local_entropy_sum, + local_low_clip_sum, + local_high_clip_sum, + local_region_clip_sum, + local_count, + ] + ) + stats = self.accelerator.reduce(stats, reduction="sum") + ( + global_ratio_sum, + global_kl_sum, + global_entropy_sum, + global_low_clip_sum, + global_high_clip_sum, + global_region_clip_sum, + global_count, + ) = stats.unbind(0) + self._metrics["train"]["ratio"].append((global_ratio_sum / global_count).item()) + self._metrics["train"]["kl"].append((global_kl_sum / global_count).item()) + self._metrics["train"]["entropy"].append((global_entropy_sum / global_count).item()) + self._metrics["train"]["clip_ratio/low_mean"].append((global_low_clip_sum / global_count).item()) + self._metrics["train"]["clip_ratio/high_mean"].append((global_high_clip_sum / global_count).item()) + self._metrics["train"]["clip_ratio/region_mean"].append((global_region_clip_sum / global_count).item()) + + # Cross-rank saturation extrema, mirroring GRPOTrainer's clip_ratio/low_min and clip_ratio/high_max: + # the smallest per-rank low-clip and largest per-rank high-clip fractions across ranks. + gathered_low_clip = self.accelerator.gather(local_low_clip_mean) + gathered_high_clip = self.accelerator.gather(local_high_clip_mean) + self._metrics["train"]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item()) + self._metrics["train"]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item()) + + if self.aux_loss_enabled: + gathered_aux = self.accelerator.reduce(aux_loss.detach().to(torch.float32), reduction="sum") + self._metrics["train"]["aux_loss"].append((gathered_aux / world_size).item()) + + # Logging metrics from the rollout worker (reward, reward_std, etc.). + # inputs["metrics"] is a dict keyed by metric name; each value is this rank's row of per-sample values, + # NaN-padded (the nan-aware aggregation below ignores both padding and unscorable samples). + sample_metrics = inputs["metrics"] # dict[str, Tensor(shape=[1, n_samples_local])] + keys = list(sample_metrics.keys()) + device = completion_mask.device + n_samples = (position_ids == 0).sum().to(torch.float32) + if keys: + # nan-aware per key: unscorable samples carry NaN, so a plain .sum() would poison the whole metric. + local_sums = torch.stack([torch.nansum(sample_metrics[k].to(device)) for k in keys]) + local_counts = torch.stack( + [(~torch.isnan(sample_metrics[k].to(device))).sum().to(torch.float32) for k in keys] + ) + stats = torch.cat([local_sums, local_counts]) + stats = self.accelerator.reduce(stats, reduction="sum") + n = len(keys) + global_sums, global_counts = stats[:n], stats[n:] + for k, global_sum, global_count in zip(keys, global_sums, global_counts, strict=True): + metric = (global_sum / global_count).item() if global_count > 0 else float("nan") + self._metrics["train"][k].append(metric) + + length_stats = torch.stack([completion_mask.sum().float(), n_samples]) + length_stats = self.accelerator.reduce(length_stats, reduction="sum") + self._metrics["train"]["completions/mean_length"].append((length_stats[0] / length_stats[1]).item()) + + # Training throughput: completion tokens consumed by this training step per second. + now = time.time() + if self._train_tokens_start_time is not None: + train_elapsed = now - self._train_tokens_start_time + if train_elapsed > 0: + self._metrics["train"]["training_tok/s"].append(global_n_tokens.item() / train_elapsed) + self._train_tokens_start_time = now + + self._metrics["train"]["forward_time_s"].append(self._last_forward_time_s) + # NOTE: in dynamic mbs setup, we would need to agg across DP ranks. + self._metrics["train"]["train_seq_len"].append(float(position_ids.max() + 1)) + return loss + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + # Average the metrics + metrics = {} + for key, val in self._metrics[mode].items(): + # Filter out NaN values before averaging. A reward function that returns None for all samples + # in a batch produces NaN for that batch's metric. With logging_steps > 1, a naive sum()/len() + # would let a single NaN contaminate valid data from other batches. Only return None when no + # valid values remain (e.g. JSON loggers crash on float NaN). + valid = [v for v in val if not math.isnan(v)] + metrics[key] = sum(valid) / len(valid) if valid else None + + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + def _streaming_iter(self): + # Iterate parameters one at a time. For FSDP2 (DTensor), full_tensor() all-gathers just this parameter across + # FSDP ranks, then frees it once the generator advances — avoiding materializing the full model in memory. + device = self.accelerator.device + for name, param in self.model.named_parameters(): + name = name.removeprefix("module.") # DDP/FSDP1 wrapping + full = param.full_tensor() if isinstance(param, DTensor) else param.detach() + if full.device != device: + full = full.to(device) + yield name, full + + def _sync_weight(self): + t0 = time.time() + logger.info("Weight sync: pausing vLLM...") + if self.accelerator.is_main_process and self.weight_transfer: + self.weight_transfer.pause() + t_pause = time.time() + logger.info(f"Weight sync: pause took {t_pause - t0:.1f}s, waiting for all ranks...") + + self.accelerator.wait_for_everyone() + t_barrier = time.time() + + logger.info(f"Weight sync: transferring weights... (barrier took {t_barrier - t_pause:.1f}s)") + if self.accelerator.is_main_process and self.weight_transfer: + self.weight_transfer.send_weights(self._streaming_iter()) + else: + # Non-rank-0 processes must still participate in full_tensor() collectives for FSDP2. + for _ in self._streaming_iter(): + pass + t_transfer = time.time() + + self.accelerator.wait_for_everyone() + + logger.info(f"Weight sync: resuming vLLM... (transfer took {t_transfer - t_barrier:.1f}s)") + if self.accelerator.is_main_process: + if self.weight_transfer: + self.weight_transfer.resume() + self.model_version += 1 + if self.rollout_worker: + self.rollout_worker.update_model_version(self.model_version) + weight_sync_time_s = time.time() - t0 + self._metrics["train"]["weight_sync_time_s"].append(weight_sync_time_s) + logger.info(f"Weight sync: done. Total {weight_sync_time_s:.1f}s") + + def _inner_training_loop(self, *args, **kwargs): + try: + return super()._inner_training_loop(*args, **kwargs) + finally: + if self.accelerator.is_main_process: + if self.rollout_worker: + self.rollout_worker.stop() + if self.weight_transfer: + self.weight_transfer.destroy() diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/async_grpo/async_rollout_worker.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/async_grpo/async_rollout_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..43f1ec341f33c76ad64ba361461c8151c8ce8090 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/async_grpo/async_rollout_worker.py @@ -0,0 +1,829 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import asyncio +import inspect +import multiprocessing as mp +import os +import pickle +import queue +import threading +import time +import traceback +from collections.abc import Awaitable, Callable, Iterator +from dataclasses import dataclass +from multiprocessing.queues import Queue as MPQueue +from multiprocessing.sharedctypes import Synchronized as MPValue +from multiprocessing.synchronize import Event as MPEvent +from typing import Any, TypeAlias + +import aiohttp +import numpy as np +from accelerate.logging import get_logger +from datasets import Dataset +from transformers import PreTrainedTokenizerBase + +from ...chat_template_utils import ( + add_response_schema, + get_training_chat_template, + is_chat_template_prefix_preserving, + parse_response, +) +from ...import_utils import is_vllm_available +from ...trainer.utils import print_prompt_completions_sample + + +logger = get_logger(__name__) + +Messages: TypeAlias = list[dict[str, str]] + +_RETRYABLE_HTTP_ERRORS = (aiohttp.ClientError, asyncio.TimeoutError, TimeoutError, ConnectionResetError) + + +async def _retry_on_http_error(coro_factory: Callable[[], Awaitable], *, label: str, max_attempts: int = 1): + """Retry an aiohttp coroutine on transport errors with bounded exponential backoff.""" + for attempt in range(max_attempts): + try: + return await coro_factory() + except _RETRYABLE_HTTP_ERRORS as e: + if attempt >= max_attempts - 1: + raise + sleep = min(2 ** min(attempt, 4), 16) + logger.warning(f"{label} failed ({type(e).__name__}: {e}); retry {attempt + 1}/{max_attempts} in {sleep}s") + await asyncio.sleep(sleep) + + +@dataclass(slots=True) +class RolloutGroup: + prompt: Messages + prompt_ids: list[int] + reward_kwargs: dict[str, list[Any]] + completions: list[Messages] + completions_ids: list[list[int]] + completions_logprobs: list[list[float]] + tool_mask: list[list[int]] + tool_call_counts: list[int] + tool_failure_counts: list[int] + model_version: int + queued_at: float = 0.0 + + +@dataclass(slots=True) +class RolloutSample: + prompt: Messages + completion: Messages + input_ids: list[int] + completion_mask: list[int] + old_log_probs: list[float] + advantage: float + model_version: int + metrics: dict[str, float] + + +# Env vars the child must drop so accelerate's `PartialState()` initialises in +# single-process mode instead of trying to join the parent's process group. +_CHILD_ENV_TO_STRIP = ( + "RANK", + "WORLD_SIZE", + "LOCAL_RANK", + "LOCAL_WORLD_SIZE", + "MASTER_ADDR", + "MASTER_PORT", + "GROUP_RANK", + "ROLE_RANK", + "ROLE_WORLD_SIZE", + "TORCHELASTIC_RUN_ID", + "TORCHELASTIC_RESTART_COUNT", + "TORCHELASTIC_MAX_RESTARTS", + "TORCH_FR_DUMP_TEMP_FILE", + "NCCL_DEBUG_FILE", +) + + +def _scrub_child_env() -> None: + # The child has no business touching CUDA; any library that imports torch + # and lazily probes devices would race the parent's allocator. + os.environ["CUDA_VISIBLE_DEVICES"] = "" + for k in _CHILD_ENV_TO_STRIP: + os.environ.pop(k, None) + + +def _spawn_stop_watcher(rollout_loop: "_AsyncRolloutLoop", stop_event: MPEvent) -> None: + # Daemon thread that translates the parent's mp.Event into the child's + # asyncio.Event so _run_loops breaks out of its gather. + def _watch(): + stop_event.wait() + try: + rollout_loop._loop.call_soon_threadsafe(rollout_loop._stop_event.set) + except RuntimeError: + # Loop already closed (run() returned before stop fired). Nothing to do. + pass + + threading.Thread(target=_watch, daemon=True, name="grpo-mp-stop-watcher").start() + + +def _child_main( + loop_kwargs: dict[str, Any], + samples_queue: MPQueue, + model_version_value: MPValue, + stop_event: MPEvent, + child_ready_event: MPEvent, + heartbeat_value: MPValue, + failed_event: MPEvent, + exception_info_queue: MPQueue, +) -> None: + _scrub_child_env() + # `accelerate.logging.get_logger` requires `PartialState()` to have been called. + from accelerate.state import PartialState + + PartialState() + + rollout_loop = _AsyncRolloutLoop( + **loop_kwargs, + rollout_buffer=samples_queue, + model_version_value=model_version_value, + heartbeat_value=heartbeat_value, + failed_event=failed_event, + exception_info_queue=exception_info_queue, + ) + child_ready_event.set() + _spawn_stop_watcher(rollout_loop, stop_event) + try: + rollout_loop.run() + except Exception: + traceback.print_exc() + raise + + +class _AsyncRolloutLoop: + """Asyncio generate and score loops. Lives entirely inside the spawned child process. + + Owns the tokenizer, dataset iterator, reward funcs, environments, and the asyncio event loop. Talks to vLLM via + `/v1/completions`. Pushes scored `RolloutSample`s into the shared `mp.Queue` (`rollout_buffer`); reads the bumped + policy version from the shared `mp.Value` (`model_version_value`). + """ + + def __init__( + self, + *, + model_name: str, + dataset: Dataset, + reward_funcs: list[Callable[..., list[float]]], + processing_class: PreTrainedTokenizerBase, + rollout_buffer: MPQueue, + model_version_value: MPValue, + heartbeat_value: MPValue, + failed_event: MPEvent, + exception_info_queue: MPQueue, + tools: list[Callable] | None = None, + environment_factory: Callable[[], object] | None = None, + num_generations: int = 8, + max_inflight_tasks: int = 128, + queue_maxsize: int = 0, + vllm_server_url: str = "http://localhost:8000", + max_tokens: int = 32, + temperature: float = 1.0, + request_timeout: int = 120, + chat_template_kwargs: dict[str, Any] | None = None, + max_tool_calling_iterations: int | None = None, + log_completions: bool = False, + num_completions_to_print: int | None = None, + ): + self.model_name = model_name + self.dataset = dataset + self._dataset_iter = iter(dataset) + self.reward_funcs = reward_funcs + self.reward_func_names = [f.__name__ for f in reward_funcs] + self.tokenizer = add_response_schema(processing_class) + self.rollout_buffer = rollout_buffer # shared mp.Queue + self._model_version_value = model_version_value # shared mp.Value + self._heartbeat_value = heartbeat_value # shared mp.Value('d'); wall-clock seconds + self._failed_event = failed_event # shared mp.Event + self._exception_info_queue = exception_info_queue # shared mp.Queue(maxsize=1) + + self.num_generations = num_generations + self.max_inflight_tasks = max_inflight_tasks + self.queue_maxsize = queue_maxsize + self.max_tokens = max_tokens + self.temperature = temperature + self.request_timeout = request_timeout + self.chat_template_kwargs = chat_template_kwargs or {} + self.max_tool_calling_iterations = max_tool_calling_iterations + self.log_completions = log_completions + self.num_completions_to_print = num_completions_to_print + self.vllm_server_url = vllm_server_url.rstrip("/") + + self.environments = None + environment_methods = [[] for _ in range(max_inflight_tasks)] + if environment_factory is not None: + self.environments = [environment_factory() for _ in range(max_inflight_tasks)] + for i, environment in enumerate(self.environments): + has_reset = False + for name, member in inspect.getmembers(environment, predicate=inspect.ismethod): + if name == "reset": + has_reset = True + elif not name.startswith("_"): + environment_methods[i].append(member) + if not has_reset: + raise ValueError( + "Each environment instance returned by `environment_factory` must define `reset`." + ) + + base_tools = tools or [] + self._sync_tool_dicts = [{} for _ in range(max_inflight_tasks)] + for i in range(max_inflight_tasks): + for tool in base_tools + (environment_methods[i] if self.environments is not None else []): + if inspect.iscoroutinefunction(tool): + raise ValueError("Asynchronous tools are not supported yet.") + self._sync_tool_dicts[i][tool.__name__] = tool + self.tools = base_tools + (environment_methods[0] if self.environments is not None else []) + + # The chat template must be prefix-preserving in multi-turn training; if the tokenizer's + # template isn't, swap in a training-safe one. + if self.tools and not is_chat_template_prefix_preserving(self.tokenizer): + self.chat_template = get_training_chat_template(self.tokenizer) + else: + self.chat_template = None + + self._groups_to_score: asyncio.Queue[RolloutGroup | None] = asyncio.Queue(maxsize=16) + self._total_completion_tokens = 0 + self._total_groups_scored = 0 + self._generation_start_time: float | None = None + self.session: aiohttp.ClientSession | None = None + + self._loop = asyncio.new_event_loop() + self._stop_event = asyncio.Event() + + @property + def model_version(self) -> int: + return int(self._model_version_value.value) + + def run(self) -> None: + asyncio.set_event_loop(self._loop) + try: + self._loop.run_until_complete(self._run_loops(stop_event=self._stop_event)) + except BaseException as e: + # Push pickle-safe exception info to the parent before setting _failed_event, so a + # reader that sees the event is guaranteed to also see the info on the queue. + info = (type(e).__name__, str(e), traceback.format_exc()) + try: + self._exception_info_queue.put_nowait(info) + except Exception: + pass # queue full (parent hasn't drained a prior failure), best-effort put + self._failed_event.set() + logger.exception(f"Worker process failed: {e}") + raise + finally: + self._loop.close() + + async def _run_loops(self, stop_event: asyncio.Event) -> None: + async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(limit=self.max_inflight_tasks)) as session: + self.session = session + logger.info( + f"vllm worker started: num_generations={self.num_generations}, " + f"max_inflight_tasks={self.max_inflight_tasks}" + ) + await asyncio.gather( + asyncio.create_task(self._generate_loop(stop_event=stop_event)), + asyncio.create_task(self._score_loop(stop_event=stop_event)), + ) + + async def _generate_loop(self, stop_event: asyncio.Event) -> None: + pending_groups: dict[int, RolloutGroup] = {} + pending_completed: dict[int, int] = {} + inflight_tasks: dict[asyncio.Task, tuple[int, int]] = {} + free_slots = set(range(self.max_inflight_tasks)) + work_iter = self._repeat_iterator() + + self._generation_start_time = time.monotonic() + try: + while True: + # Wall-clock for cross-process comparison; parent uses time.time() in check_health. + self._heartbeat_value.value = time.time() + while free_slots and not stop_event.is_set(): + group_id, row = next(work_iter) + if group_id not in pending_groups: + prompt = row["prompt"] + prompt_ids = self.tokenizer.apply_chat_template( + prompt, + return_dict=False, + add_generation_prompt=True, + tools=self.tools or None, # `or None`: Llama bug: renders tool boilerplate for tools=[] + chat_template=self.chat_template, + **self.chat_template_kwargs, + ) + reward_kwargs = { + key: [row[key]] * self.num_generations + for key in row + if key not in {"prompt", "completion", "completion_ids"} + } + pending_groups[group_id] = RolloutGroup( + prompt=prompt, + prompt_ids=prompt_ids, + reward_kwargs=reward_kwargs, + completions=[], + completions_ids=[], + completions_logprobs=[], + tool_mask=[], + tool_call_counts=[], + tool_failure_counts=[], + model_version=self.model_version, + ) + pending_completed[group_id] = 0 + + slot = free_slots.pop() + if self.environments is not None: + self.environments[slot].reset(**row) + + task = asyncio.create_task( + self._generate_one(pending_groups[group_id].prompt, tool_dict=self._sync_tool_dicts[slot]) + ) + inflight_tasks[task] = (group_id, slot) + + if not inflight_tasks: + if stop_event.is_set(): + return + await asyncio.sleep(0.01) + continue + + done, _ = await asyncio.wait(inflight_tasks, return_when=asyncio.FIRST_COMPLETED, timeout=0.1) + if not done: + continue + + for task in done: + group_id, slot = inflight_tasks.pop(task) + free_slots.add(slot) + if task.exception() is not None: + raise task.exception() + + ( + completion, + completion_ids, + completion_logprobs, + tool_mask, + tool_call_count, + tool_failure_count, + ) = task.result() + group = pending_groups[group_id] + group.completions.append(completion) + group.completions_ids.append(completion_ids) + group.completions_logprobs.append(completion_logprobs) + group.tool_mask.append(tool_mask) + group.tool_call_counts.append(tool_call_count) + group.tool_failure_counts.append(tool_failure_count) + self._total_completion_tokens += sum(tool_mask) + pending_completed[group_id] += 1 + + if pending_completed[group_id] == self.num_generations: + group.queued_at = time.monotonic() + while True: + try: + self._groups_to_score.put_nowait(group) + break + except asyncio.QueueFull: + if stop_event.is_set(): + return + await asyncio.sleep(0.1) + del pending_groups[group_id] + del pending_completed[group_id] + finally: + for task in inflight_tasks: + task.cancel() + if inflight_tasks: + await asyncio.gather(*inflight_tasks, return_exceptions=True) + try: + self._groups_to_score.put_nowait(None) + except asyncio.QueueFull: + pass + + async def _score_loop(self, stop_event: asyncio.Event) -> None: + while not stop_event.is_set(): + self._heartbeat_value.value = time.time() + t_wait = time.monotonic() + try: + group = await asyncio.wait_for(self._groups_to_score.get(), timeout=0.5) + except asyncio.TimeoutError: + continue + if group is None: + return + score_queue_wait = time.monotonic() - t_wait + wait_scoring = time.monotonic() - group.queued_at + + if score_queue_wait > 0.5: + logger.info(f"[score] waited {score_queue_wait:.1f}s for a group to score") + + t0 = time.monotonic() + samples = await self._score_group(group) + scoring_time = time.monotonic() - t0 + logger.info( + f"[score] scored {len(samples)} samples in {scoring_time:.2f}s, " + f"buffer_qsize={self.rollout_buffer.qsize()}" + ) + + self._compute_rollout_metrics(samples, scoring_time, wait_scoring) + + if self.log_completions and samples: + print_prompt_completions_sample( + prompts=[s.prompt for s in samples], + completions=[s.completion for s in samples], + rewards={"reward": [s.metrics["reward"] for s in samples]}, + advantages=[s.advantage for s in samples], + step=self._total_groups_scored, + num_samples=self.num_completions_to_print, + ) + self._total_groups_scored += 1 + + for sample in samples: + while True: + try: + self.rollout_buffer.put_nowait(sample) + break + except queue.Full: + if stop_event.is_set(): + return + logger.info( + f"[score] rollout buffer full (maxsize={self.queue_maxsize}), " + "waiting for trainer to consume..." + ) + await asyncio.sleep(0.1) + + def _compute_rollout_metrics(self, samples: list[RolloutSample], scoring_time: float, wait_scoring: float) -> None: + assert self._generation_start_time is not None + elapsed = time.monotonic() - self._generation_start_time + generation_tok_per_sec = self._total_completion_tokens / elapsed if elapsed > 0 else 0.0 + for sample in samples: + sample.metrics["generation_tok_per_s"] = generation_tok_per_sec + sample.metrics["scoring_time_ms"] = scoring_time * 1000 + sample.metrics["wait_scoring_ms"] = wait_scoring * 1000 + sample.metrics["buffer_qsize"] = self.rollout_buffer.qsize() + + def _repeat_iterator(self) -> Iterator[tuple[int, dict[str, Any]]]: + group_id = 0 + while True: + try: + row = next(self._dataset_iter) + except StopIteration: + self._dataset_iter = iter(self.dataset) + row = next(self._dataset_iter) + for _ in range(self.num_generations): + yield group_id, row + group_id += 1 + + async def _generate_one( + self, prompt: Messages, tool_dict: dict[str, Callable] + ) -> tuple[list[dict[str, str]], list[int], list[float], list[int], int, int]: + completion, completion_ids, completion_logprobs, tool_mask = [], [], [], [] + tool_call_count = 0 + tool_failure_count = 0 + iteration_num = 0 + max_iterations = self.max_tool_calling_iterations + prompt_ids = self.tokenizer.apply_chat_template( + prompt, + return_dict=False, + add_generation_prompt=True, + tools=self.tools or None, + chat_template=self.chat_template, + **self.chat_template_kwargs, + ) + while True: + turn_ids, turn_logprobs = await self._generate_one_turn(prompt_ids) + assistant_message = parse_response(self.tokenizer, turn_ids) + completion.append(assistant_message) + completion_ids.extend(turn_ids) + completion_logprobs.extend(turn_logprobs) + tool_mask.extend([1] * len(turn_ids)) + tool_calls = assistant_message.get("tool_calls") + if tool_calls is None or (max_iterations is not None and iteration_num >= max_iterations): + return completion, completion_ids, completion_logprobs, tool_mask, tool_call_count, tool_failure_count + + tool_messages, n_calls, n_failures = self._execute_tool_calls(tool_calls, tool_dict) + tool_call_count += n_calls + tool_failure_count += n_failures + completion.extend(tool_messages) + suffix_ids = self._get_tool_suffix_ids(tool_messages) + completion_ids.extend(suffix_ids) + completion_logprobs.extend([0.0] * len(suffix_ids)) + tool_mask.extend([0] * len(suffix_ids)) + prompt_ids = prompt_ids + turn_ids + suffix_ids + iteration_num += 1 + + def _get_tool_suffix_ids(self, tool_messages: list[dict[str, Any]]) -> list[int]: + # Use the real tool name: some templates (e.g. GPT-OSS) derive the tool response header from + # the assistant's tool call name. + dummy_tool_calls = [{"type": "function", "function": {"name": tool_messages[0]["name"], "arguments": {}}}] + dummy_messages = [ + {"role": "user", "content": "dummy"}, + # `content: ""` is required: VLM processors crash on tokenize=True without it + # (KeyError in processing_utils.py, see huggingface/transformers#45290). + {"role": "assistant", "content": "", "tool_calls": dummy_tool_calls}, + ] + prefix_ids = self.tokenizer.apply_chat_template( + dummy_messages, + add_generation_prompt=False, + tokenize=True, + chat_template=self.chat_template, + return_dict=False, + **self.chat_template_kwargs, + ) + full_ids = self.tokenizer.apply_chat_template( + dummy_messages + tool_messages, + add_generation_prompt=True, + tokenize=True, + chat_template=self.chat_template, + return_dict=False, + **self.chat_template_kwargs, + ) + # Some chat templates (Qwen3/Qwen3.5) render "...<|im_end|>\n" after assistant/tool blocks. + # Align the slicing boundary to EOS, not EOS + newline. + eos_positions = [i for i, tok_id in enumerate(prefix_ids) if tok_id == self.tokenizer.eos_token_id] + if eos_positions: + prefix_ids = prefix_ids[: eos_positions[-1] + 1] + if full_ids[: len(prefix_ids)] != prefix_ids: + raise ValueError("Unexpected tokenization: the EOS-trimmed prefix IDs are not a prefix of the full IDs.") + return full_ids[len(prefix_ids) :] + + def _execute_tool_calls( + self, tool_calls: list[dict[str, Any]], tool_dict: dict[str, Callable] + ) -> tuple[list[dict[str, str]], int, int]: + tool_messages = [] + n_calls = 0 + n_failures = 0 + for tool_call in tool_calls: + n_calls += 1 + function = tool_call["function"] + name = function["name"] + try: + arguments = function.get("arguments", {}) + result = tool_dict[name](**arguments) + except Exception as error: + n_failures += 1 + result = {"error": str(error)} + tool_messages.append({"role": "tool", "name": name, "content": str(result)}) + return tool_messages, n_calls, n_failures + + async def _generate_one_turn(self, prompt_ids: list[int]) -> tuple[list[int], list[float]]: + payload = { + "model": self.model_name, + "prompt": prompt_ids, + "max_tokens": self.max_tokens, + "temperature": self.temperature, + "n": 1, + "return_token_ids": True, + "logprobs": 0, + } + output = await _retry_on_http_error( + lambda: self._post("/v1/completions", payload, self.request_timeout), + max_attempts=30, + label="vllm /v1/completions", + ) + choice = output["choices"][0] + return choice["token_ids"], choice["logprobs"]["token_logprobs"] + + async def _score_group(self, group: RolloutGroup) -> list[RolloutSample]: + kwargs = dict( + completions=group.completions, + prompt=group.prompt, + prompts=[group.prompt] * len(group.completions), + completion_ids=group.completions_ids, + **group.reward_kwargs, + ) + all_rewards = await asyncio.gather( + *[ + reward_func(**kwargs) + if inspect.iscoroutinefunction(reward_func) + else asyncio.to_thread(reward_func, **kwargs) + for reward_func in self.reward_funcs + ] + ) + + # Reward funcs may return None per-sample (unparseable gold). Convert to NaN. A completion + # for which every func returned None is unscorable: nansum would give 0 and the row would + # pull the policy away from actually-correct answers. + # Mark such rows NaN, then compute advantage on the scorable subset only. + all_rewards = [[r if r is not None else float("nan") for r in row] for row in all_rewards] + arr = np.array(all_rewards, dtype=float) + all_nan_mask = np.all(np.isnan(arr), axis=0) + rewards = np.nansum(arr, axis=0) + rewards[all_nan_mask] = np.nan + + scored_mask = ~np.isnan(rewards) + # NOTE: for NaN reward we set advantage to 0 ! + advantages = np.zeros_like(rewards) + if scored_mask.any(): + scored = rewards[scored_mask] + advantages[scored_mask] = (scored - scored.mean()) / (scored.std() + 1e-8) + reward_mean = float(scored.mean()) + reward_std = float(scored.std()) + else: + reward_mean = reward_std = float("nan") + logger.info(f"Rollout metrics: reward_mean={reward_mean:.4f}, reward_std={reward_std:.4f}") + + total_calls = sum(group.tool_call_counts) + tool_metrics = ( + [ + { + "tools/call_frequency": float(n_calls), + "tools/failure_frequency": (n_failures / n_calls) if n_calls > 0 else 0.0, + } + for n_calls, n_failures in zip(group.tool_call_counts, group.tool_failure_counts, strict=True) + ] + if total_calls > 0 + else [{}] * len(group.completions) + ) + + per_func_rewards = np.array(all_rewards, dtype=float) + return [ + RolloutSample( + prompt=group.prompt, + completion=completion, + input_ids=group.prompt_ids + completion_ids, + completion_mask=[0] * len(group.prompt_ids) + tool_mask, + old_log_probs=[0.0] * len(group.prompt_ids) + logprobs, + advantage=advantage, + model_version=group.model_version, + metrics={ + "reward": float(reward), + "reward_std": reward_std, + **{ + f"rewards/{name}": float(func_reward) + for name, func_reward in zip(self.reward_func_names, per_func_rewards[:, i], strict=True) + }, + **tm, + }, + ) + for i, (completion, completion_ids, logprobs, tool_mask, advantage, reward, tm) in enumerate( + zip( + group.completions, + group.completions_ids, + group.completions_logprobs, + group.tool_mask, + advantages, + rewards, + tool_metrics, + strict=True, + ) + ) + ] + + async def _post(self, path: str, payload: dict, timeout: float, max_retries: int = 3) -> dict: + client_timeout = aiohttp.ClientTimeout(total=timeout) + + async def _do_post(): + async with self.session.post( + f"{self.vllm_server_url}{path}", json=payload, timeout=client_timeout + ) as response: + response.raise_for_status() + content = await response.json() + return content if content else {} + + return await _retry_on_http_error(_do_post, label=f"POST {path}", max_attempts=max_retries) + + +class AsyncRolloutWorker: + """Parent-side controller: spawns a child process running `_AsyncRolloutLoop`. + + The trainer holds this object on rank 0. The child does the actual rollout work; this class only manages lifecycle + (start/stop) and exposes the shared `mp.Queue` (`rollout_buffer`) and `mp.Value` (`model_version`) the trainer + reads/writes. + + Constructor kwargs are forwarded as-is to `_AsyncRolloutLoop` when the child spawns; only `queue_maxsize` and + `child_ready_timeout` are consumed here. Because the child is spawned, every forwarded kwarg is pickled: + `reward_funcs`, `tools`, and `environment_factory` (and anything they close over) must be picklable — module-level + functions, `functools.partial`, or callable instances, never lambdas or closures. `start()` validates this up front + and raises a `TypeError` otherwise. The child also runs with `CUDA_VISIBLE_DEVICES=""`, so GPU reward models + execute on CPU. + """ + + def __init__( + self, + *, + queue_maxsize: int = 0, + child_ready_timeout: int = 300, + **loop_kwargs: Any, + ): + if not is_vllm_available(min_version="0.17.1"): + raise ImportError( + "vLLM >= 0.17.1 is required to use AsyncRolloutWorker. Install it with: pip install 'vllm>=0.17.1'" + ) + ctx = mp.get_context("spawn") + self._mp_ctx = ctx + self.rollout_buffer = ctx.Queue(maxsize=queue_maxsize) + self._model_version_value = ctx.Value("i", 0) + self._stop_event_mp = ctx.Event() + self._child_ready_event = ctx.Event() + # Liveness state shared with the child. Wall-clock seconds because monotonic() is per-process. + self._heartbeat_value = ctx.Value("d", 0.0) + self._failed_event = ctx.Event() + self._exception_info_queue = ctx.Queue(maxsize=1) + # Forwarded verbatim to _AsyncRolloutLoop in the child. queue_maxsize is also + # forwarded — the child reads it for "rollout buffer full" log lines. + loop_kwargs["queue_maxsize"] = queue_maxsize + self._loop_kwargs = loop_kwargs + self._child_ready_timeout = child_ready_timeout + self._process: mp.Process | None = None + + @property + def model_version(self) -> int: + return int(self._model_version_value.value) + + @model_version.setter + def model_version(self, value: int) -> None: + # NOTE(@aminediro) Read/write ops like += are not atomic with mp.Value + with self._model_version_value.get_lock(): + self._model_version_value.value = int(value) + + def update_model_version(self, model_version: int) -> None: + self.model_version = model_version + + def start(self) -> None: + if self._process is not None: + logger.warning("AsyncRolloutWorker.start() called but child process is already running; ignoring.") + return + # Reset so spawn-import latency (~tens of seconds) doesn't immediately trip check_health. + self._heartbeat_value.value = time.time() + try: + pickle.dumps(self._loop_kwargs) + except (pickle.PicklingError, AttributeError, TypeError) as e: + # fails fast with an actionable message instead of an opaque traceback + raise TypeError( + "AsyncRolloutWorker forwards reward_funcs / tools / environment_factory to a spawned " + "child process, so they must be picklable. Lambdas and closures are not: use a " + "module-level function, functools.partial, or a callable class instance instead." + ) from e + self._process = self._mp_ctx.Process( + target=_child_main, + args=( + self._loop_kwargs, + self.rollout_buffer, + self._model_version_value, + self._stop_event_mp, + self._child_ready_event, + self._heartbeat_value, + self._failed_event, + self._exception_info_queue, + ), + name="grpo-rollout-worker-child", + daemon=True, + ) + self._process.start() + logger.info( + f"AsyncRolloutWorker spawned child pid={self._process.pid}; " + f"waiting up to {self._child_ready_timeout}s for the ready signal" + ) + # spawn re-imports torch+transformers+trl+vllm in the child — slow on cold launch. Poll + # liveness so an early crash surfaces immediately instead of after the full timeout. + deadline = time.monotonic() + self._child_ready_timeout + while not self._child_ready_event.wait(timeout=1.0): + if not self._process.is_alive(): + exit_code = self._process.exitcode + self._process = None + raise RuntimeError( + f"AsyncRolloutWorker child exited during init (exitcode={exit_code}). " + "Check the child's stderr for the traceback." + ) + if time.monotonic() >= deadline: + raise RuntimeError( + f"AsyncRolloutWorker child did not signal ready within {self._child_ready_timeout}s." + ) + logger.info("AsyncRolloutWorker child is ready") + + def check_health(self, stale_after_s: float) -> None: + """Raise if the child crashed or hasn't ticked the heartbeat within `stale_after_s`.""" + if self._failed_event.is_set(): + try: + type_name, msg, tb = self._exception_info_queue.get_nowait() + cause = RuntimeError(f"{type_name}: {msg}\n{tb}") + except queue.Empty: + cause = None + raise RuntimeError("Rollout worker child has failed; see chained exception.") from cause + age = time.time() - self._heartbeat_value.value + if age > stale_after_s: + raise RuntimeError(f"Rollout worker heartbeat stale: {age:.0f}s > {stale_after_s:.0f}s; child is hung.") + + def stop(self) -> None: + if self._process is None: + return + logger.info("Stopping AsyncRolloutWorker child process...") + self._stop_event_mp.set() + # If start() raised before Process.start() returned (e.g. pickle failure during spawn), + # _popen is None and .join() would assert — skip cleanly. + if self._process._popen is not None: + self._process.join(timeout=15) + if self._process.is_alive(): + logger.warning("Child did not exit within 15s; terminating.") + self._process.terminate() + self._process.join(timeout=5) + if self._process.is_alive(): + self._process.kill() + self._process = None diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/async_grpo/weight_transfer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/async_grpo/weight_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..1662cf7a32bb3976cca60d236760200665577518 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/async_grpo/weight_transfer.py @@ -0,0 +1,143 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import threading +import time + +import requests +from accelerate.logging import get_logger + +from ...import_utils import is_vllm_available + + +if is_vllm_available(min_version="0.22.0"): + from vllm.distributed.weight_transfer.nccl_engine import NCCLTrainerSendWeightsArgs, NCCLWeightTransferEngine + from vllm.utils.network_utils import get_ip, get_open_port + + +logger = get_logger(__name__) + + +class WeightTransferClient: + def __init__( + self, + vllm_server_url: str, + weight_update_info: dict, + server_timeout: float = 240.0, + init_weight_transfer_timeout: int = 1800, + ): + if not is_vllm_available(min_version="0.22.0"): + raise ImportError( + "vLLM >= 0.22.0 is required to use WeightTransferClient. Install it with: pip install 'vllm>=0.22.0'" + ) + self.vllm_server_url = vllm_server_url.rstrip("/") + self.server_timeout = server_timeout + self.init_weight_transfer_timeout = init_weight_transfer_timeout + self._weight_update_info = weight_update_info + self.model_update_group = None + + def _wait_for_server_ready_sync(self, timeout_s: float | None = None, poll_interval_s: float = 2.0) -> None: + timeout_s = timeout_s if timeout_s is not None else self.server_timeout + logger.info(f"Waiting for vLLM server at {self.vllm_server_url} ...") + start = time.time() + while True: + elapsed = time.time() - start + try: + response = requests.get(f"{self.vllm_server_url}/health", timeout=5) + if response.status_code == 200: + logger.info(f"vLLM server ready after {elapsed:.1f}s") + return + except (requests.ConnectionError, requests.Timeout, OSError): + pass + if elapsed >= timeout_s: + raise TimeoutError( + f"Timed out after {timeout_s:.0f}s waiting for vLLM server at {self.vllm_server_url}. " + "Make sure the vLLM server is running and reachable. If the server needs more time to load " + "the model, increase `vllm_server_timeout` in your AsyncGRPOConfig." + ) + if int(elapsed) % 10 < poll_interval_s: + logger.info(f"Still waiting for vLLM server... ({elapsed:.0f}s)") + time.sleep(poll_interval_s) + + def init_weight_transfer(self) -> None: + self._wait_for_server_ready_sync() + response = requests.get(f"{self.vllm_server_url}/get_world_size") + inference_world_size = response.json()["world_size"] + world_size = inference_world_size + 1 + master_address = get_ip() + master_port = get_open_port() + init_info = { + "master_address": master_address, + "master_port": master_port, + "rank_offset": 1, + "world_size": world_size, + } + t_init = threading.Thread( + target=requests.post, + args=(f"{self.vllm_server_url}/init_weight_transfer_engine",), + kwargs={"json": {"init_info": init_info}, "timeout": self.init_weight_transfer_timeout}, + ) + t_init.start() + self.model_update_group = NCCLWeightTransferEngine.trainer_init( + { + "master_address": master_address, + "master_port": master_port, + "world_size": world_size, + } + ) + t_init.join() + logger.info("Initialised weight-transfer NCCL group with vLLM") + + def send_weights(self, iterator) -> None: + if self.model_update_group is None: + return + t0 = time.time() + # Prepare the workers for the reload; must complete before any weights are sent. + requests.post( + f"{self.vllm_server_url}/start_weight_update", + json={"is_checkpoint_format": True}, + timeout=1800, + ) + # The /update_weights POST drives the workers' blocking NCCL recv, so it runs on a thread + # concurrently with the trainer-side broadcast. + t_update = threading.Thread( + target=requests.post, + args=(f"{self.vllm_server_url}/update_weights",), + kwargs={"json": {"update_info": self._weight_update_info}, "timeout": 1800}, + ) + t_update.start() + NCCLWeightTransferEngine.trainer_send_weights( + iterator=iterator, + trainer_args=NCCLTrainerSendWeightsArgs(group=self.model_update_group, packed=True), + ) + t_update.join() + requests.post(f"{self.vllm_server_url}/finish_weight_update", timeout=1800) + logger.debug(f"[weight_sync] send_weights took {time.time() - t0:.1f}s") + + def pause(self) -> None: + t0 = time.time() + requests.post(f"{self.vllm_server_url}/pause", params={"mode": "keep"}) + logger.debug(f"[weight_sync] pause HTTP took {time.time() - t0:.1f}s") + + def resume(self) -> None: + t0 = time.time() + requests.post(f"{self.vllm_server_url}/resume") + logger.debug(f"[weight_sync] resume HTTP took {time.time() - t0:.1f}s") + + def destroy(self) -> None: + if self.model_update_group is None: + return + self.model_update_group.group.store = None + self.model_update_group.group.socket = None + self.model_update_group = None diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/bco/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/bco/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3a6871ca60e002b21ac74a69e4113ded3391f622 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/bco/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .bco_config import BCOConfig +from .bco_trainer import BCOTrainer diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/bco/bco_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/bco/bco_config.py new file mode 100644 index 0000000000000000000000000000000000000000..d804f73938c75c3a8f6ba7eac3611febcc1d5bfd --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/bco/bco_config.py @@ -0,0 +1,164 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class BCOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`experimental.bco.BCOTrainer`]. + + This class includes only the parameters that are specific to BCO training. For a full list of training arguments, + please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may + differ from those in [`~transformers.TrainingArguments`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + max_length (`int` or `None`, *optional*, defaults to `1024`): + Maximum length of the sequences (prompt + completion) in the batch. This argument is required if you want + to use the default data collator. + max_completion_length (`int`, *optional*): + Maximum length of the completion. This argument is required if you want to use the default data collator + and your model is an encoder-decoder. + beta (`float`, *optional*, defaults to `0.1`): + Parameter controlling the deviation from the reference model. Higher β means less deviation from the + reference model. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model and reference model. + generate_during_eval (`bool`, *optional*, defaults to `False`): + If `True`, generates and logs completions from both the model and the reference model to W&B or Comet + during evaluation. + is_encoder_decoder (`bool`, *optional*): + When using the `model_init` argument (callable) to instantiate the model instead of the `model` argument, + you need to specify if the model returned by the callable is an encoder-decoder model. + precompute_ref_log_probs (`bool`, *optional*, defaults to `False`): + Whether to precompute reference model log probabilities for training and evaluation datasets. This is + useful when training without the reference model to reduce the total GPU memory needed. + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model and + reference model from strings. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to allow loading models that ship custom Python code from the Hub. Forwarded to + [`~transformers.AutoModelForCausalLM.from_pretrained`] for both the model and reference model. + dataset_num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + prompt_sample_size (`int`, *optional*, defaults to `1024`): + Number of prompts that are fed to density ratio classifier. + min_density_ratio (`float`, *optional*, defaults to `0.5`): + Minimum value of the density ratio. The estimated density ratio is clamped to this value. + max_density_ratio (`float`, *optional*, defaults to `10.0`): + Maximum value of the density ratio. The estimated density ratio is clamped to this value. + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `5e-7` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=5e-7, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + max_length: int | None = field( + default=1024, + metadata={ + "help": "Maximum length of the sequences (prompt + completion) in the batch. " + "This argument is required if you want to use the default data collator." + }, + ) + max_completion_length: int | None = field( + default=None, + metadata={ + "help": "Maximum length of the completion. This argument is required if you want to use the " + "default data collator and your model is an encoder-decoder." + }, + ) + beta: float = field( + default=0.1, + metadata={ + "help": "Parameter controlling the deviation from the reference model. " + "Higher β means less deviation from the reference model." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the model and reference model."}, + ) + generate_during_eval: bool = field( + default=False, + metadata={ + "help": "If `True`, generates and logs completions from both the model and the reference model " + "to W&B during evaluation." + }, + ) + is_encoder_decoder: bool | None = field( + default=None, + metadata={ + "help": "When using the `model_init` argument (callable) to instantiate the model instead of the " + "`model` argument, you need to specify if the model returned by the callable is an " + "encoder-decoder model." + }, + ) + precompute_ref_log_probs: bool = field( + default=False, + metadata={ + "help": "Whether to precompute reference model log probabilities for training and evaluation datasets. " + "This is useful when training without the reference model to reduce the total GPU memory " + "needed." + }, + ) + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the " + "model from a string." + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": "Whether to allow loading models that ship custom Python code from the Hub. Forwarded to " + "`AutoModelForCausalLM.from_pretrained` for both the model and reference model." + }, + ) + dataset_num_proc: int | None = field( + default=None, + metadata={"help": "Number of processes to use for processing the dataset."}, + ) + prompt_sample_size: int = field( + default=1024, + metadata={"help": "Number of prompts that are fed to density ratio classifier."}, + ) + min_density_ratio: float = field( + default=0.5, + metadata={"help": "Minimum value of the density ratio. The estimated density ratio is clamped to this value."}, + ) + max_density_ratio: float = field( + default=10.0, + metadata={"help": "Maximum value of the density ratio. The estimated density ratio is clamped to this value."}, + ) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/bco/bco_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/bco/bco_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..a4b0f6f992aa08dbcb21e1c7d93f3714340d366d --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/bco/bco_trainer.py @@ -0,0 +1,1558 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import dataclasses +import inspect +import json +import os +import random +import textwrap +from collections import defaultdict +from collections.abc import Callable +from contextlib import contextmanager, nullcontext +from dataclasses import dataclass +from operator import itemgetter +from pathlib import Path +from typing import Any, Literal + +import numpy as np +import pandas as pd +import torch +import torch.nn as nn +import torch.nn.functional as F +import transformers +from accelerate import Accelerator, PartialState +from accelerate.logging import get_logger +from accelerate.utils import is_peft_model, tqdm +from datasets import Dataset +from packaging.version import Version +from torch import autocast +from torch.utils.data import DataLoader, SequentialSampler +from transformers import ( + AutoModelForCausalLM, + BaseImageProcessor, + DataCollator, + FeatureExtractionMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, + TrainingArguments, + is_comet_available, + is_sklearn_available, + is_wandb_available, +) +from transformers.trainer_utils import EvalLoopOutput, has_length +from transformers.utils import is_peft_available + +from ...data_utils import maybe_apply_chat_template, maybe_extract_prompt, maybe_unpair_preference_dataset +from ...import_utils import is_joblib_available +from ...models.utils import prepare_deepspeed +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import disable_dropout_in_model, log_table_to_comet_experiment, selective_log_softmax +from ..utils import DPODataCollatorWithPadding, create_reference_model, pad_to_length, peft_module_casting_to_bf16 +from .bco_config import BCOConfig + + +if is_peft_available(): + from peft import PeftConfig, get_peft_model, prepare_model_for_kbit_training + +if is_wandb_available(): + import wandb + +if is_sklearn_available(): + from sklearn.linear_model import LogisticRegression + +if is_joblib_available(): + import joblib + +logger = get_logger(__name__) + +RUNNING_NAME = "running.json" +CLF_NAME = "clf.pkl" + + +@torch.no_grad() +def get_global_statistics( + accelerator, xs: torch.Tensor, mask=None, device="cpu" +) -> tuple[torch.Tensor, torch.Tensor, int]: + """ + Computes element-wise mean and variance of the tensor across processes. Reference: + https://github.com/OpenLMLab/MOSS-RLHF/blob/40b91eb2f2b71b16919addede0341d2bef70825d/utils.py#L57C1-L73C75 + """ + xs = xs.to(accelerator.device) + sum_and_count = torch.tensor([xs.sum(), (xs.numel() if mask is None else mask.sum())], device=xs.device) + sum_and_count = accelerator.reduce(sum_and_count) + global_sum, count = sum_and_count + global_mean = global_sum / count + + sum_var = torch.sum(((xs - global_mean) ** 2).mul(1 if mask is None else mask)) + sum_var = accelerator.reduce(sum_var) + global_var = sum_var / count + + return global_mean.to(device), global_var.to(device), count.item() + + +@dataclass +class RunningMoments: + """ + Calculates the running mean and standard deviation of a data stream. Reference: + https://github.com/OpenLMLab/MOSS-RLHF/blob/40b91eb2f2b71b16919addede0341d2bef70825d/utils.py#L75 + """ + + accelerator: Accelerator + mean: float = 0 + std: float = 1 + var: float = 1 + count: float = 1e-24 + + @torch.no_grad() + def update(self, xs: torch.Tensor) -> tuple[float, float]: + """ + Updates running moments from batch's moments computed across ranks + """ + if self.accelerator.use_distributed: + xs_mean, xs_var, xs_count = get_global_statistics(self.accelerator, xs) + else: + xs_count = xs.numel() + xs_var, xs_mean = torch.var_mean(xs, unbiased=False) + xs_mean, xs_var = xs_mean.float(), xs_var.float() + + delta = xs_mean - self.mean + tot_count = self.count + xs_count + + new_sum = xs_var * xs_count + # correct old_sum deviation accounting for the new mean + old_sum = self.var * self.count + delta**2 * self.count * xs_count / tot_count + tot_sum = old_sum + new_sum + + self.mean += (delta * xs_count / tot_count).item() + new_var = tot_sum / tot_count + self.std = (new_var * tot_count / (tot_count - 1)).float().sqrt().item() + self.var = new_var.item() + self.count = tot_count + + return xs_mean.item(), (xs_var * xs_count / (xs_count - 1)).float().sqrt().item() + + def save_to_json(self, json_path: str): + """Save the content of this instance in JSON format inside `json_path`.""" + # save everything except accelerator + if self.accelerator.is_main_process: + save_dict = dataclasses.asdict(self, dict_factory=lambda x: {k: v for (k, v) in x if k != "accelerator"}) + json_string = json.dumps(save_dict, indent=2, sort_keys=True) + "\n" + with open(json_path, "w", encoding="utf-8") as f: + f.write(json_string) + + @classmethod + def load_from_json(cls, accelerator: Accelerator, json_path: str): + """Create an instance from the content of `json_path`.""" + # load everything except accelerator + with open(json_path, encoding="utf-8") as f: + text = f.read() + return cls(accelerator=accelerator, **json.loads(text)) + + +def _tokenize( + batch: dict[str, list[Any]], + tokenizer: PreTrainedTokenizerBase, + embedding_tokenizer: PreTrainedTokenizerBase | None = None, +) -> dict[str, list[Any]]: + """Tokenize a batch from a BCO specific dataset.""" + prompt_tokenized = tokenizer(batch["prompt"], add_special_tokens=False) + prompt_input_ids = prompt_tokenized["input_ids"] + prompt_attention_mask = prompt_tokenized["attention_mask"] + prompt_and_completion = [ + prompt + completion for prompt, completion in zip(batch["prompt"], batch["completion"], strict=True) + ] + full_tokenized = tokenizer(prompt_and_completion, add_special_tokens=False) + full_input_ids = full_tokenized["input_ids"] + full_attention_mask = full_tokenized["attention_mask"] + + answer_input_ids = [f[len(p) :] for f, p in zip(full_input_ids, prompt_input_ids, strict=True)] + answer_attention_mask = [f[len(p) :] for f, p in zip(full_attention_mask, prompt_attention_mask, strict=True)] + + # Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]` + full_concat_input_ids = [np.concatenate([p, a]) for p, a in zip(prompt_input_ids, answer_input_ids, strict=True)] + # Prepare input tokens for token by token comparison + full_input_ids = [np.array(f) for f in full_input_ids] + for full, concat in zip(full_input_ids, full_concat_input_ids, strict=True): + if len(full) != len(concat): + raise ValueError( + "The elements in 'full_input_ids' and 'full_concat_input_ids' must have the same pairwise length." + ) + + # On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens + # can be merged together when tokenizing prompt+answer. This could result + # on the last token from the prompt being different when tokenized on its own + # vs when done as prompt+answer. + response_token_ids_start_idx = [len(p) for p in prompt_input_ids] + + # If tokenized prompt is different than both prompt+answer, then it means the + # last token has changed due to merging. + for idx, (p, f, r) in enumerate(zip(prompt_input_ids, full_input_ids, response_token_ids_start_idx, strict=True)): + if not np.array_equal(p, f[:r]): + response_token_ids_start_idx[idx] -= 1 + + prompt_input_ids = [f[:r] for f, r in zip(full_input_ids, response_token_ids_start_idx, strict=True)] + prompt_attention_mask = [f[:r] for f, r in zip(full_attention_mask, response_token_ids_start_idx, strict=True)] + + for p, m in zip(prompt_input_ids, prompt_attention_mask, strict=True): + if len(p) != len(m): + raise ValueError("Prompt input ids and attention mask should have the same length.") + + answer_input_ids = [f[r:] for f, r in zip(full_input_ids, response_token_ids_start_idx, strict=True)] + answer_attention_mask = [f[r:] for f, r in zip(full_attention_mask, response_token_ids_start_idx, strict=True)] + + output = dict( + prompt_input_ids=prompt_input_ids, + prompt_attention_mask=prompt_attention_mask, + answer_input_ids=answer_input_ids, + answer_attention_mask=answer_attention_mask, + ) + + if embedding_tokenizer is not None: + embedding_tokenized = embedding_tokenizer(batch["prompt"], add_special_tokens=False) + + output.update( + { + "embedding_input_ids": embedding_tokenized["input_ids"], + "embedding_attention_mask": embedding_tokenized["attention_mask"], + } + ) + + return output + + +def _process_tokens(example: dict[str, Any], model: "PreTrainedModel" = None, **kwargs) -> dict: + """Process tokens of a BCO specific dataset. + + At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt + + completion responses is/are too long. First we truncate the prompt; if we're still too long, we truncate the + completion. + + We also create the labels for the completion responses, which are of length equal to the sum of the length of the + prompt and the completion response, with `-100` for the prompt tokens. + """ + prompt = example["prompt"] + completion = example["completion"] + + batch = { + f"{kwargs['prefix']}prompt": prompt, + f"{kwargs['prefix']}completion": completion, + f"{kwargs['prefix']}label": example["label"], + } + + if not kwargs["is_encoder_decoder"]: + # Check issues below for more details + # 1. https://github.com/huggingface/trl/issues/907 + # 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 + # 3. https://github.com/LianjiaTech/BELLE/issues/337 + + if not isinstance(prompt, str): + raise ValueError(f"prompt should be an str but got {type(prompt)}") + + if not isinstance(completion, str): + raise ValueError(f"completion should be an str but got {type(completion)}") + + # keys of format prompt_* refers to just the prompt and answer_* refers to just the answer + all_tokens = { + "prompt_input_ids": example["prompt_input_ids"], + "prompt_attention_mask": example["prompt_attention_mask"], + "answer_input_ids": example["answer_input_ids"], + "answer_attention_mask": example["answer_attention_mask"], + } + + # calculate max length by checking if BOS/EOS is already there + max_length = kwargs["max_length"] + bos_token_id = kwargs["tokenizer"].bos_token_id + eos_token_id = kwargs["tokenizer"].eos_token_id + if bos_token_id != all_tokens["prompt_input_ids"][0]: + max_length -= 1 + if eos_token_id != all_tokens["answer_input_ids"][-1]: + max_length -= 1 + + # if combined sequence is too long (> max_length - 1 for BOS token - 1 for EOS), truncate the response + if len(all_tokens["prompt_input_ids"]) + len(all_tokens["answer_input_ids"]) > max_length: + for k in ["answer_input_ids", "answer_attention_mask"]: + all_tokens[k] = all_tokens[k][: max_length - len(all_tokens["prompt_input_ids"])] + + # all input_ids and attention mask as is. We then check if we need to add BOS/EOS tokens + batch[f"{kwargs['prefix']}prompt_input_ids"] = all_tokens["prompt_input_ids"] + batch[f"{kwargs['prefix']}prompt_attention_mask"] = all_tokens["prompt_attention_mask"] + batch[f"{kwargs['prefix']}completion_input_ids"] = ( + all_tokens["prompt_input_ids"] + all_tokens["answer_input_ids"] + ) + batch[f"{kwargs['prefix']}completion_attention_mask"] = ( + all_tokens["prompt_attention_mask"] + all_tokens["answer_attention_mask"] + ) + + # add BOS, which affects both prompt and the full completion + if bos_token_id is not None: + if len(all_tokens["prompt_input_ids"]) == 0 or bos_token_id != all_tokens["prompt_input_ids"][0]: + batch[f"{kwargs['prefix']}prompt_input_ids"] = [bos_token_id] + batch[ + f"{kwargs['prefix']}prompt_input_ids" + ] + batch[f"{kwargs['prefix']}prompt_attention_mask"] = [1] + batch[ + f"{kwargs['prefix']}prompt_attention_mask" + ] + batch[f"{kwargs['prefix']}completion_input_ids"] = [bos_token_id] + batch[ + f"{kwargs['prefix']}completion_input_ids" + ] + batch[f"{kwargs['prefix']}completion_attention_mask"] = [1] + batch[ + f"{kwargs['prefix']}completion_attention_mask" + ] + # add EOS, which affects only the full completion + if len(all_tokens["answer_input_ids"]) == 0 or eos_token_id != all_tokens["answer_input_ids"][-1]: + batch[f"{kwargs['prefix']}completion_input_ids"] = batch[f"{kwargs['prefix']}completion_input_ids"] + [ + eos_token_id + ] + batch[f"{kwargs['prefix']}completion_attention_mask"] = batch[ + f"{kwargs['prefix']}completion_attention_mask" + ] + [1] + + batch[f"{kwargs['prefix']}completion_labels"] = batch[f"{kwargs['prefix']}completion_input_ids"][:] + batch[f"{kwargs['prefix']}completion_labels"][: len(batch[f"{kwargs['prefix']}prompt_input_ids"])] = [ + -100 + ] * len(batch[f"{kwargs['prefix']}prompt_input_ids"]) + else: + completion_tokens = kwargs["tokenizer"]( + completion, truncation=True, max_length=kwargs["max_completion_length"], add_special_tokens=True + ) + prompt_tokens = kwargs["tokenizer"](prompt, add_special_tokens=True) + + batch[f"{kwargs['prefix']}prompt_input_ids"] = prompt_tokens["input_ids"] + batch[f"{kwargs['prefix']}prompt_attention_mask"] = prompt_tokens["attention_mask"] + + batch[f"{kwargs['prefix']}completion_labels"] = completion_tokens["input_ids"] + batch[f"{kwargs['prefix']}completion_attention_mask"] = completion_tokens["attention_mask"] + if model is not None and hasattr(model, "prepare_decoder_input_ids_from_labels"): + batch[f"{kwargs['prefix']}completion_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels( + labels=torch.tensor(batch["completion_labels"]) + ) + + return batch + + +class BCOTrainer(_BaseTrainer): + r""" + Initialize BCOTrainer from [BCO](https://huggingface.co/papers/2404.04656) paper. + + Args: + model ([`~transformers.PreTrainedModel`]): + The model to train, preferably an [`~transformers.AutoModelForSequenceClassification`]. + ref_model ([`~transformers.PreTrainedModel`]): + Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation + and loss. If no reference model is provided, the trainer will create a reference model with the same + architecture as the model to be optimized. + args ([`experimental.bco.BCOConfig`]): + The arguments to use for training. + train_dataset ([`~datasets.Dataset`]): + The dataset to use for training. + eval_dataset ([`~datasets.Dataset`]): + The dataset to use for evaluation. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + data_collator ([`~transformers.DataCollator`], *optional*): + The data collator to use for training. If None is specified, the default data collator + ([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the + maximum length of the sequences in the batch, given a dataset of paired sequences. + model_init (`Callable[[], transformers.PreTrainedModel]`): + The model initializer to use for training. If None is specified, the default model initializer will be + used. + callbacks (`list[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + peft_config ([`~peft.PeftConfig`], *optional*): + The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in + a PEFT model. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to + metric values. + model_adapter_name (`str`, defaults to `None`): + Name of the train target PEFT adapter, when using LoRA with multiple adapters. + ref_adapter_name (`str`, defaults to `None`): + Name of the reference PEFT adapter, when using LoRA with multiple adapters. + embedding_func (`Callable`, *optional*): + Function to compute prompt embeddings, used to train the underlying distribution matching (UDM) classifier + when the desirable and undesirable datasets have divergent prompt distributions. Requires the scikit-learn + and joblib libraries. + embedding_tokenizer ([`~transformers.PreTrainedTokenizerBase`], *optional*): + Tokenizer used to prepare prompts for `embedding_func`. + """ + + _tag_names = ["trl", "bco"] + _name = "BCO" + _paper = { + "title": "Binary Classifier Optimization for Large Language Model Alignment", + "id": "2404.04656", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{jung2024binary, + title = {{Binary Classifier Optimization for Large Language Model Alignment}}, + author = {Seungjae Jung and Gunsoo Han and Daniel Wontae Nam and Kyoung{-}Woon On}, + year = 2024, + eprint = {arXiv:2404.04656} + }"""), + } + + def __init__( + self, + model: PreTrainedModel | nn.Module | str = None, + ref_model: PreTrainedModel | nn.Module | str | None = None, + args: BCOConfig = None, + train_dataset: Dataset | None = None, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + processing_class: PreTrainedTokenizerBase + | BaseImageProcessor + | FeatureExtractionMixin + | ProcessorMixin + | None = None, + data_collator: DataCollator | None = None, + model_init: Callable[[], PreTrainedModel] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + peft_config: "PeftConfig | None" = None, + compute_metrics: Callable[[EvalLoopOutput], dict] | None = None, + model_adapter_name: str | None = None, + ref_adapter_name: str | None = None, + embedding_func: Callable | None = None, + embedding_tokenizer: PreTrainedTokenizerBase | None = None, + ): + if embedding_func is not None and not (is_sklearn_available() and is_joblib_available()): + raise ImportError( + "BCOTrainer with UDM requires the scikit-learn and joblib libraries. Please install it with `pip install scikit-learn joblib`." + ) + + if type(args) is TrainingArguments: + raise ValueError("Please use `BCOConfig` instead `TrainingArguments`.") + + if train_dataset is None: + raise ValueError("`train_dataset` is required") + + if not isinstance(model, str) and model is not None and ref_model is model: + raise ValueError( + "`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the " + "same as `model`, you must mass a copy of it, or `None` if you use peft." + ) + + if args.model_init_kwargs is None: + model_init_kwargs = {} + elif not isinstance(model, str): + raise ValueError("You passed model_kwargs to the BCOTrainer. But your model is already instantiated.") + else: + model_init_kwargs = args.model_init_kwargs + dtype = model_init_kwargs.get("dtype", "auto") + if dtype is not None: + # Convert to `torch.dtype` if an str is passed + if isinstance(dtype, str) and dtype != "auto": + dtype = getattr(torch, dtype) + if dtype != "auto" and not isinstance(dtype, torch.dtype): + raise ValueError( + f"Invalid `dtype` passed to the BCOConfig. Expected a string with either `torch.dtype` or 'auto', but got {dtype}." + ) + model_init_kwargs["dtype"] = dtype + model_init_kwargs["device_map"] = model_init_kwargs.get("device_map", "auto") + + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + + if isinstance(model, str): + model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs) + + if isinstance(ref_model, str): + ref_model = AutoModelForCausalLM.from_pretrained(ref_model, **model_init_kwargs) + + # PEFT + # Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16` + # has been called in order to properly call autocast if needed. + self._peft_has_been_casted_to_bf16 = False + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first " + "merge and unload the existing adapter, save the resulting base model, and then pass that base " + "model along with the new `peft_config` to the trainer." + ) + + if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False): + _support_gc_kwargs = hasattr( + args, "gradient_checkpointing_kwargs" + ) and "gradient_checkpointing_kwargs" in list( + inspect.signature(prepare_model_for_kbit_training).parameters + ) + + prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing} + + if _support_gc_kwargs: + prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs + + model = prepare_model_for_kbit_training(model, **prepare_model_kwargs) + elif args.gradient_checkpointing: + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + # get peft model with the given config + model = get_peft_model(model, peft_config) + if args.bf16 and getattr(model, "is_loaded_in_4bit", False): + peft_module_casting_to_bf16(model) + # If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager + self._peft_has_been_casted_to_bf16 = True + + # For models that use gradient_checkpointing, we need to attach a hook that enables input + # to explicitly have `requires_grad=True`, otherwise training will either silently + # fail or completely fail. + elif args.gradient_checkpointing: + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + if args.generate_during_eval and not (is_wandb_available() or is_comet_available()): + raise ValueError( + "`generate_during_eval=True` requires Weights and Biases or Comet to be installed." + " Please install `wandb` or `comet-ml` to resolve." + ) + + if model is not None: + self.is_encoder_decoder = model.config.is_encoder_decoder + elif args.is_encoder_decoder is None: + raise ValueError("When no model is provided, you need to pass the parameter is_encoder_decoder.") + else: + self.is_encoder_decoder = args.is_encoder_decoder + + self.model_adapter_name = model_adapter_name + self.ref_adapter_name = ref_adapter_name + + if ref_model: + self.ref_model = ref_model + elif is_peft_model(model) or args.precompute_ref_log_probs: + # The `model` with adapters turned off will be used as the reference model + self.ref_model = None + else: + self.ref_model = create_reference_model(model) + + if processing_class is None: + raise ValueError( + "max_length or a processing_class must be specified when using the default DPODataCollatorWithPadding" + ) + if args.max_length is None: + logger.warning( + "When using DPODataCollatorWithPadding, you should set `max_length` in the `BCOConfig`. " + "It will be set to `512` by default, but you should do it yourself in the future.", + ) + max_length = 512 + if args.max_length is not None: + max_length = args.max_length + + max_completion_length = None + if args.max_completion_length is None and self.is_encoder_decoder: + logger.warning( + "When using DPODataCollatorWithPadding with an encoder decoder architecture, you should set `max_completion_length` in the BCOTrainer's init" + " it will be set to `128` by default, but you should do it yourself in the future.", + ) + max_completion_length = 128 + if args.max_completion_length is not None and self.is_encoder_decoder: + max_completion_length = args.max_completion_length + + if data_collator is None: + data_collator = DPODataCollatorWithPadding( + pad_token_id=processing_class.pad_token_id, + is_encoder_decoder=self.is_encoder_decoder, + ) + + if args.remove_unused_columns: + args.remove_unused_columns = False + # warn users + logger.warning( + "When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your BCOConfig" + " we have set it for you, but you should do it yourself in the future.", + ) + + self.use_dpo_data_collator = True + else: + self.use_dpo_data_collator = False + + # Disable dropout in the model and reference model + if args.disable_dropout: + disable_dropout_in_model(model) + if self.ref_model is not None: + disable_dropout_in_model(self.ref_model) + + self.max_length = max_length + self.generate_during_eval = args.generate_during_eval + self.max_completion_length = max_completion_length + self.precompute_ref_log_probs = args.precompute_ref_log_probs + + # Since ref_logs are precomputed on the first call to get_train/eval_dataloader + # keep track of first called to avoid computation of future calls + self._precomputed_train_ref_log_probs = False + self._precomputed_eval_ref_log_probs = False + + # metric + self._stored_metrics = defaultdict(lambda: defaultdict(list)) + + # BCO parameter + self.beta = args.beta + self.aux_loss_enabled = getattr(model.config, "output_router_logits", False) + self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0) + if self.aux_loss_enabled and self.aux_loss_coef == 0.0: + logger.warning( + "You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to " + "`0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value " + "greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary " + "loss.", + ) + + # Underlying Distribution Matching argument + self.embedding_func = embedding_func + self.embedding_tokenizer = embedding_tokenizer + + with PartialState().main_process_first(): + # Extract the prompt if needed + train_dataset = train_dataset.map( + maybe_extract_prompt, num_proc=args.dataset_num_proc, desc="Extracting prompt from train dataset" + ) + # Unpair the dataset if needed + train_dataset = maybe_unpair_preference_dataset( + train_dataset, args.dataset_num_proc, desc="Unpairing train dataset" + ) + # Apply the chat template if needed + train_dataset = train_dataset.map( + maybe_apply_chat_template, + fn_kwargs={"processing_class": processing_class}, + num_proc=args.dataset_num_proc, + ) + if eval_dataset is not None: + # Extract the prompt if needed + eval_dataset = eval_dataset.map( + maybe_extract_prompt, num_proc=args.dataset_num_proc, desc="Extracting prompt from eval dataset" + ) + # Unpair the dataset if needed + eval_dataset = maybe_unpair_preference_dataset( + eval_dataset, args.dataset_num_proc, desc="Unpairing eval dataset" + ) + eval_dataset = eval_dataset.map( + maybe_apply_chat_template, + fn_kwargs={"processing_class": processing_class}, + num_proc=args.dataset_num_proc, + ) + + # Tokenize and prepare the training datasets + train_dataset = train_dataset.map( + _tokenize, + batched=True, + fn_kwargs={"tokenizer": processing_class, "embedding_tokenizer": self.embedding_tokenizer}, + num_proc=args.dataset_num_proc, + desc="Tokenizing train dataset", + ) + + # Prepare the datasets + fn_kwargs = { + "prefix": "", + "is_encoder_decoder": self.is_encoder_decoder, + "tokenizer": processing_class, + "max_length": self.max_length, + "max_completion_length": self.max_completion_length, + } + train_dataset = train_dataset.map( + _process_tokens, + fn_kwargs=fn_kwargs, + num_proc=args.dataset_num_proc, + desc="Processing tokenized train dataset", + ) + + if eval_dataset is not None: + # Tokenize + eval_dataset = eval_dataset.map( + _tokenize, + fn_kwargs={"tokenizer": processing_class, "embedding_tokenizer": self.embedding_tokenizer}, + batched=True, + num_proc=args.dataset_num_proc, + desc="Tokenizing eval dataset", + ) + + # Process + fn_kwargs = { + "prefix": "", + "is_encoder_decoder": self.is_encoder_decoder, + "tokenizer": processing_class, + "max_length": self.max_length, + "max_completion_length": self.max_completion_length, + } + eval_dataset = eval_dataset.map( + _process_tokens, + fn_kwargs=fn_kwargs, + num_proc=args.dataset_num_proc, + desc="Processing tokenized eval dataset", + ) + + desirable = train_dataset.filter( + lambda x: x["label"], num_proc=args.dataset_num_proc, desc="Filtering desirable examples" + ) + undesirable = train_dataset.filter( + lambda x: not x["label"], num_proc=args.dataset_num_proc, desc="Filtering undesirable examples" + ) + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + model_init=model_init, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the + # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set + # self.model_accepts_loss_kwargs to False to enable scaling. + self.model_accepts_loss_kwargs = False + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + if not hasattr(self, "accelerator"): + raise AttributeError( + "Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`." + ) + + # Deepspeed Zero-3 does not support precompute_ref_log_probs + if self.is_deepspeed_enabled: + if self.accelerator.state.deepspeed_plugin.zero_stage == 3 and self.precompute_ref_log_probs: + raise ValueError( + "You cannot use `precompute_ref_log_probs=True` with Deepspeed ZeRO-3. Please set `precompute_ref_log_probs=False`." + ) + + if self.ref_model is None: + if not (is_peft_model(model) or self.precompute_ref_log_probs): + raise ValueError( + "No reference model and model is not a Peft model. Try setting `precompute_ref_log_probs=True`" + ) + else: + if self.is_deepspeed_enabled: + self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator) + else: + self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True) + + self.running = RunningMoments(accelerator=self.accelerator) + + if self.embedding_func is None or args.resume_from_checkpoint: + return + + chosen_embeddings = self._get_sample_prompt_embeddings(desirable, sample_size=self.args.prompt_sample_size) + rejected_embeddings = self._get_sample_prompt_embeddings(undesirable, sample_size=self.args.prompt_sample_size) + + embeddings = torch.cat((chosen_embeddings, rejected_embeddings), dim=0) + labels = torch.cat( + (torch.ones_like(chosen_embeddings[:, 0]), torch.zeros_like(rejected_embeddings[:, 0])), dim=0 + ) + + self.clf = LogisticRegression(class_weight="balanced").fit( + embeddings.cpu().float().numpy(), labels.cpu().numpy() + ) + chosen_mean = self.clf.score( + chosen_embeddings.cpu().float().numpy(), torch.ones_like(chosen_embeddings[:, 0]).cpu().numpy() + ) + rejected_mean = self.clf.score( + rejected_embeddings.cpu().float().numpy(), torch.zeros_like(rejected_embeddings[:, 0]).cpu().numpy() + ) + logger.info(f"UDM classifier training scores: chosen: {chosen_mean}, rejected: {rejected_mean}") + + @property + def match_underlying_distribution(self): + return self.embedding_func is not None and self.embedding_tokenizer is not None + + def _get_chosen_prob(self, prompt_embeddings: torch.FloatTensor) -> torch.FloatTensor: + """ + Calculates the probability if the given prompt embedding is from desirable dataset. This function calculates + the probability in the process and ensemble across processes. + """ + dtype = prompt_embeddings.dtype + device = prompt_embeddings.device + rank = self.accelerator.process_index + + padded_prompt_embeddings = self.accelerator.pad_across_processes( + prompt_embeddings, pad_index=self.embedding_tokenizer.pad_token_id + ) + sample_size = padded_prompt_embeddings.shape[0] + nonzero = padded_prompt_embeddings.mean(dim=1) != self.embedding_tokenizer.pad_token_id + prompt_embeddings = self.accelerator.gather(padded_prompt_embeddings) + + # cannot predict for all empty values + if prompt_embeddings.shape[0] == 0: + return torch.tensor([], device=device, dtype=dtype) + + prob = self.clf.predict_proba(prompt_embeddings.cpu().float().numpy())[:, 1] + prob = torch.as_tensor(prob, dtype=dtype, device=device) + prob = self.accelerator.reduce(prob, reduction="mean") + + prob = prob[sample_size * rank : sample_size * (rank + 1)] + prob = prob[nonzero] + + return prob + + def _vectorize_prompt(self, input_ids: torch.LongTensor, attention_mask: torch.LongTensor) -> torch.FloatTensor: + """ + Replaces processing_class.pad_token_id to embedding_tokenizer.pad_token_id and applies self.embedding_func + """ + input_ids = torch.where( + input_ids == self.processing_class.pad_token_id, + self.embedding_tokenizer.pad_token_id, + input_ids, + ) + + with torch.no_grad(): + embeddings = self.embedding_func( + input_ids=input_ids, + attention_mask=attention_mask, + ) + + return embeddings + + def _get_prompt_embeddings( + self, batch: dict[str, list | torch.LongTensor] + ) -> tuple[torch.FloatTensor, torch.FloatTensor]: + """Extract embeddings from frozen embedding model""" + + if not self.match_underlying_distribution: + return None, None + + embeddings = self._vectorize_prompt( + input_ids=batch["embedding_input_ids"], + attention_mask=batch["embedding_attention_mask"], + ) + + labels = torch.tensor(batch["label"], dtype=torch.bool, device=embeddings.device) + chosen_idx = torch.where(labels)[0] + rejected_idx = torch.where(~labels)[0] + + chosen_embeddings = embeddings[chosen_idx, ...] + rejected_embeddings = embeddings[rejected_idx, ...] + + return (chosen_embeddings, rejected_embeddings) + + def _get_sample_prompt_embeddings(self, dataset: Dataset, sample_size: int = 512) -> torch.FloatTensor: + """ + Sample instances from dataset and get prompt embeddings. Used for density ratio classifier training. + """ + n_samples = min(len(dataset), sample_size) + rand_indices = np.random.choice(len(dataset), size=(n_samples,)) + + embedding_dataset = dataset.select(rand_indices) + + dataloader_params = { + "batch_size": self.args.per_device_train_batch_size, + "collate_fn": self.data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "shuffle": False, + } + + # prepare dataloader + data_loader = self.accelerator.prepare(DataLoader(embedding_dataset, **dataloader_params)) + + with torch.no_grad(): + all_embeddings = torch.empty(0) + for padded_batch in tqdm(iterable=data_loader, desc="Building sample prompt embeddings"): + embeddings = self._vectorize_prompt( + input_ids=padded_batch["embedding_input_ids"], + attention_mask=padded_batch["embedding_attention_mask"], + ) + embeddings = self.accelerator.gather_for_metrics(embeddings) + all_embeddings = torch.cat((all_embeddings, embeddings.cpu())) + + return all_embeddings + + def _save_optimizer_and_scheduler(self, output_dir): + output_dir = output_dir if output_dir is not None else self.args.output_dir + super()._save_optimizer_and_scheduler(output_dir) + + if self.accelerator.is_main_process: + # When saving optimizer and scheduler to checkpoint, save also the running delta object. + self.running.save_to_json(os.path.join(output_dir, RUNNING_NAME)) + + if self.match_underlying_distribution: + joblib.dump(self.clf, os.path.join(output_dir, CLF_NAME), compress=True) + + def _load_optimizer_and_scheduler(self, checkpoint): + if checkpoint is None: + logger.warning_once(f"Missing Checkpoint {checkpoint}") + return + + super()._load_optimizer_and_scheduler(checkpoint) + + # when loading optimizer and scheduler from checkpoint, also load the running delta object. + running_file = os.path.join(checkpoint, RUNNING_NAME) + if os.path.isfile(running_file): + self.running = RunningMoments.load_from_json(self.accelerator, running_file) + + if self.match_underlying_distribution: + clf_file = os.path.join(checkpoint, CLF_NAME) + if os.path.isfile(clf_file): + self.clf = joblib.load(clf_file) + + @contextmanager + def null_ref_context(self): + """Context manager for handling null reference model (that is, peft adapter manipulation).""" + with ( + self.accelerator.unwrap_model(self.model).disable_adapter() + if is_peft_model(self.model) and not self.ref_adapter_name + else nullcontext() + ): + if self.ref_adapter_name: + self.model.set_adapter(self.ref_adapter_name) + yield + if self.ref_adapter_name: + self.model.set_adapter(self.model_adapter_name or "default") + + def get_train_dataloader(self) -> DataLoader: + """ + Returns the training [`~torch.utils.data.DataLoader`]. + + Subclass of transformers.src.transformers.trainer.get_train_dataloader to precompute `ref_log_probs`. + """ + + if self.precompute_ref_log_probs and not self._precomputed_train_ref_log_probs: + dataloader_params = { + "batch_size": self.args.per_device_train_batch_size, + "collate_fn": self.data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "shuffle": False, + } + + # prepare dataloader + data_loader = self.accelerator.prepare(DataLoader(self.train_dataset, **dataloader_params)) + reference_completion_logps = [] + + for padded_batch in tqdm(iterable=data_loader, desc="Train dataset reference log probs"): + reference_completion_logp = self.compute_reference_log_probs(padded_batch) + + reference_completion_logp = self.accelerator.gather_for_metrics(reference_completion_logp) + reference_completion_logps.append(reference_completion_logp.cpu()) + + self.train_dataset = self.train_dataset.add_column( + name="reference_logps", column=torch.cat(reference_completion_logps).float().numpy() + ) + + self._precomputed_train_ref_log_probs = True + + return super().get_train_dataloader() + + def get_eval_dataloader(self, eval_dataset: Dataset | None = None) -> DataLoader: + """ + Returns the evaluation [`~torch.utils.data.DataLoader`]. + + Subclass of transformers.src.transformers.trainer.get_eval_dataloader to precompute `ref_log_probs`. + + Args: + eval_dataset (`torch.utils.data.Dataset`, *optional*): + If provided, will override `self.eval_dataset`. If it is a [`~datasets.Dataset`], columns not accepted + by the `model.forward()` method are automatically removed. It must implement `__len__`. + """ + if eval_dataset is None and self.eval_dataset is None: + raise ValueError("Trainer: evaluation requires an eval_dataset.") + eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset + + if self.precompute_ref_log_probs and not self._precomputed_eval_ref_log_probs: + dataloader_params = { + "batch_size": self.args.per_device_eval_batch_size, + "collate_fn": self.data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "shuffle": False, + } + + # prepare dataloader + data_loader = self.accelerator.prepare(DataLoader(eval_dataset, **dataloader_params)) + + reference_completion_logps = [] + + for padded_batch in tqdm(iterable=data_loader, desc="Eval dataset reference log probs"): + reference_completion_logp = self.compute_reference_log_probs(padded_batch) + + reference_completion_logp = self.accelerator.gather_for_metrics(reference_completion_logp) + reference_completion_logps.append(reference_completion_logp.cpu()) + + eval_dataset = eval_dataset.add_column( + name="reference_logps", column=torch.cat(reference_completion_logps).float().numpy() + ) + + # Save calculated reference_chosen_logps and reference_rejected_logps to the eval_dataset for subsequent runs + if self.eval_dataset is not None: + self.eval_dataset = eval_dataset + self._precomputed_eval_ref_log_probs = True + + return super().get_eval_dataloader(eval_dataset=eval_dataset) + + def compute_reference_log_probs(self, padded_batch: dict) -> dict: + """Computes log probabilities of the reference model for a single padded batch of a BCO specific dataset.""" + with torch.no_grad(): + if self.ref_model is None: + with self.null_ref_context(): + if self.is_encoder_decoder: + completion_logits = self.model( + padded_batch["prompt_input_ids"], + attention_mask=padded_batch["prompt_attention_mask"], + decoder_input_ids=padded_batch.get("completion_decoder_input_ids"), + labels=padded_batch["completion_labels"], + ).logits + + else: + completion_logits = self.model( + padded_batch["completion_input_ids"], + attention_mask=padded_batch["completion_attention_mask"], + ).logits + + else: + if self.is_encoder_decoder: + completion_logits = self.ref_model( + padded_batch["prompt_input_ids"], + attention_mask=padded_batch["prompt_attention_mask"], + decoder_input_ids=padded_batch.get("completion_decoder_input_ids"), + labels=padded_batch["completion_labels"], + ).logits + + else: + completion_logits = self.ref_model( + padded_batch["completion_input_ids"], attention_mask=padded_batch["completion_attention_mask"] + ).logits + + completion_logps = self.get_batch_logps( + completion_logits, + padded_batch["completion_labels"], + average_log_prob=False, + is_encoder_decoder=self.is_encoder_decoder, + ) + + return completion_logps + + @staticmethod + def get_batch_logps( + logits: torch.FloatTensor, + labels: torch.LongTensor, + average_log_prob: bool = False, + is_encoder_decoder: bool = False, + ) -> torch.FloatTensor: + """Compute the log probabilities of the given labels under the given logits. + + Args: + logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size) + labels: + Labels for which to compute the log probabilities. Label tokens with a value of `-100` are ignored. + Shape: (batch_size, sequence_length) + average_log_prob: + If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the + log probabilities of the (non-masked) tokens. + is_encoder_decoder: + Whether the model is an encoder-decoder model. If True, the labels are not shifted, and the logits are + assumed to already be aligned with the labels. If False, the labels are shifted to the right by one + position, and the logits are assumed to be aligned with the shifted labels. + + Returns: + A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the + given logits. + """ + if logits.shape[:-1] != labels.shape: + raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.") + + if not is_encoder_decoder: + labels = labels[:, 1:].clone() + logits = logits[:, :-1, :] + else: + # Fixes end-dec RuntimeError + labels = labels.clone() + + loss_mask = labels != -100 + + # dummy token; we'll ignore the losses on these tokens later + labels[labels == -100] = 0 + + per_token_logps = selective_log_softmax(logits, labels) + + if average_log_prob: + return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1) + else: + return (per_token_logps * loss_mask).sum(-1) + + def forward( + self, model: nn.Module, batch: dict[str, list | torch.LongTensor] + ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + model_kwargs = ( + { + "labels": batch["completion_labels"], + "decoder_input_ids": batch.get("completion_decoder_input_ids"), + } + if self.is_encoder_decoder + else {} + ) + if self.aux_loss_enabled: + model_kwargs["output_router_logits"] = True + + outputs = model( + batch["completion_input_ids"], + attention_mask=batch["completion_attention_mask"], + **model_kwargs, + ) + completion_logits = outputs.logits + + completion_logps = self.get_batch_logps( + completion_logits, + batch["completion_labels"], + average_log_prob=False, + is_encoder_decoder=self.is_encoder_decoder, + ) + + if completion_logps.shape[0] != len(batch["label"]): + raise ValueError( + "There is a mismatch between the number of examples in this batch and the number of " + "examples for which an output sequence was predicted." + ) + + chosen_idx = [i for i in range(completion_logps.shape[0]) if batch["label"][i] is True] + rejected_idx = [i for i in range(completion_logps.shape[0]) if batch["label"][i] is False] + + chosen_logps = completion_logps[chosen_idx, ...] + rejected_logps = completion_logps[rejected_idx, ...] + + chosen_logits = completion_logits[chosen_idx, ...] + rejected_logits = completion_logits[rejected_idx, ...] + + if self.aux_loss_enabled: + return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, outputs.aux_loss) + else: + return (chosen_logps, rejected_logps, chosen_logits, rejected_logits) + + def _get_udm_weight(self, rejected_embeddings: torch.FloatTensor) -> torch.FloatTensor: + prob_desirable = self._get_chosen_prob(rejected_embeddings) + min_ratio = self.args.min_density_ratio + max_ratio = self.args.max_density_ratio + + weight = (prob_desirable / (1 - prob_desirable + 1e-8)).clamp(min=min_ratio, max=max_ratio) + + return weight + + def bco_loss( + self, + policy_chosen_logps: torch.FloatTensor, + policy_rejected_logps: torch.FloatTensor, + reference_chosen_logps: torch.FloatTensor, + reference_rejected_logps: torch.FloatTensor, + chosen_embeddings: torch.FloatTensor | None, + rejected_embeddings: torch.FloatTensor | None, + do_train: bool = True, + ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + """Compute the BCO loss for a batch of policy and reference model log probabilities. + + Args: + policy_chosen_logps: + Log probabilities of the policy model for the chosen responses. Shape: (num(chosen) in batch_size,) + policy_rejected_logps: + Log probabilities of the policy model for the rejected responses. Shape: (num(rejected) in batch_size,) + reference_chosen_logps: + Log probabilities of the reference model for the chosen responses. Shape: (num(chosen) in batch_size,) + reference_rejected_logps: + Log probabilities of the reference model for the rejected responses. Shape: (num(rejected) in + batch_size,) + chosen_embeddings: embeddings of desirable prompts + rejected_embeddings: embeddings of undesirable prompts + do_train: whether to update the running delta value. Default is True. + + Returns: + A tuple of four tensors: (losses, chosen_rewards, rejected_rewards, delta). The losses tensor contains the + BCO loss for each example in the batch. The chosen_rewards and rejected_rewards tensors contain the rewards + for the chosen and rejected responses, respectively. The delta value contains the moving average of all + implicit rewards. + """ + + chosen_logratios = policy_chosen_logps - reference_chosen_logps + chosen_rewards = self.beta * chosen_logratios + + rejected_logratios = policy_rejected_logps - reference_rejected_logps + rejected_rewards = self.beta * rejected_logratios + + if do_train: + self.running.update(torch.cat((chosen_rewards, rejected_rewards), 0).detach()) + delta = torch.as_tensor(self.running.mean, device=chosen_rewards.device) + + chosen_losses = -F.logsigmoid(chosen_rewards - delta) + rejected_losses = -F.logsigmoid(-(rejected_rewards - delta)) + + if self.match_underlying_distribution: + chosen_weight = torch.ones_like(chosen_losses) + rejected_weight = self._get_udm_weight(rejected_embeddings) + + losses = torch.cat((chosen_weight * chosen_losses, rejected_weight * rejected_losses), dim=0) + else: + losses = torch.cat((chosen_losses, rejected_losses), dim=0) + + return losses, chosen_rewards, rejected_rewards, delta + + def get_batch_loss_metrics( + self, + model, + batch: dict[str, list | torch.LongTensor], + do_train: bool = True, + ): + """Compute the BCO loss and other metrics for the given batch of inputs for train or test.""" + metrics = {} + batch = {k: (v.to(self.accelerator.device) if isinstance(v, torch.Tensor) else v) for k, v in batch.items()} + + forward_output = self.forward(model, batch) + ( + policy_chosen_logps, + policy_rejected_logps, + policy_chosen_logits, + policy_rejected_logits, + ) = forward_output[:4] + if self.aux_loss_enabled: + aux_loss = forward_output[4] + + # if reference_logps in batch use them, otherwise use the reference model + if "reference_logps" in batch: + chosen_idx = [i for i in range(batch["reference_logps"].shape[0]) if batch["label"][i] is True] + rejected_idx = [i for i in range(batch["reference_logps"].shape[0]) if batch["label"][i] is False] + + reference_chosen_logps = batch["reference_logps"][chosen_idx, ...] + reference_rejected_logps = batch["reference_logps"][rejected_idx, ...] + else: + with torch.no_grad(): + if self.ref_model is None: + with self.null_ref_context(): + ( + reference_chosen_logps, + reference_rejected_logps, + _, + _, + ) = self.forward(self.model, batch)[:4] + else: + ( + reference_chosen_logps, + reference_rejected_logps, + _, + _, + ) = self.forward(self.ref_model, batch)[:4] + + chosen_embeddings, rejected_embeddings = self._get_prompt_embeddings(batch) + + losses, chosen_rewards, rejected_rewards, delta = self.bco_loss( + policy_chosen_logps, + policy_rejected_logps, + reference_chosen_logps, + reference_rejected_logps, + chosen_embeddings, + rejected_embeddings, + do_train=do_train, + ) + metrics["delta"] = self.accelerator.gather_for_metrics(delta).mean().item() + + num_chosen = torch.Tensor([len(chosen_rewards)]).to(self.accelerator.device) + num_rejected = torch.Tensor([len(rejected_rewards)]).to(self.accelerator.device) + + all_num_chosen = self.accelerator.gather_for_metrics(num_chosen).sum().item() + all_num_rejected = self.accelerator.gather_for_metrics(num_rejected).sum().item() + + if all_num_chosen > 0: + metrics["rewards/chosen_sum"] = ( + self.accelerator.gather_for_metrics(chosen_rewards.nansum()).nansum().item() + ) + metrics["logps/chosen_sum"] = ( + self.accelerator.gather_for_metrics(policy_chosen_logps.nansum()).nansum().item() + ) + metrics["logits/chosen_sum"] = ( + self.accelerator.gather_for_metrics(policy_chosen_logits.nansum()).nansum().item() + ) + metrics["count/chosen"] = all_num_chosen + + if all_num_rejected > 0: + metrics["rewards/rejected_sum"] = ( + self.accelerator.gather_for_metrics(rejected_rewards.nansum()).nansum().item() + ) + metrics["logps/rejected_sum"] = ( + self.accelerator.gather_for_metrics(policy_rejected_logps.nansum()).nansum().item() + ) + metrics["logits/rejected_sum"] = ( + self.accelerator.gather_for_metrics(policy_rejected_logits.nansum()).nansum().item() + ) + metrics["count/rejected"] = all_num_rejected + + loss = losses.nanmean() + if self.aux_loss_enabled: + loss += self.aux_loss_coef * aux_loss + + return loss, metrics + + def compute_loss( + self, + model: PreTrainedModel | nn.Module, + inputs: dict[str, torch.Tensor | Any], + return_outputs=False, + num_items_in_batch=None, + ) -> torch.Tensor | tuple[torch.Tensor, dict[str, torch.Tensor]]: + compute_loss_context_manager = ( + autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() + ) + + with compute_loss_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs) + + # Make sure to move the loss to the device the original accumulating loss is at back in the `Trainer` class: + loss = loss.to(self.args.device) + # force log the metrics + if self.accelerator.is_main_process: + self.store_metrics(metrics, train_eval="train") + + if return_outputs: + return (loss, metrics) + return loss + + def store_metrics(self, metrics: dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None: + for key, value in metrics.items(): + self._stored_metrics[train_eval][key].append(value) + + def _get_train_sampler(self, dataset: Dataset | None = None) -> torch.utils.data.Sampler | None: + if dataset is None: + dataset = self.train_dataset + if dataset is None or not has_length(dataset): + return None + return SequentialSampler(dataset) + + def generate_from_model_and_ref(self, model, batch: dict[str, torch.LongTensor]) -> tuple[str, str]: + """Generate samples from the model and reference model for the given batch of inputs.""" + + # If one uses `generate_during_eval` with peft + bf16, we need to explicitly call generate with + # the torch amp context manager as some hidden states are silently casted to full precision. + generate_context_manager = ( + autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() + ) + with generate_context_manager: + policy_output = model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + + # if reference_output in batch use that otherwise use the reference model + if "reference_output" in batch: + reference_output = batch["reference_output"] + else: + if self.ref_model is None: + with self.null_ref_context(): + reference_output = self.model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + else: + reference_output = self.ref_model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + + policy_output = pad_to_length(policy_output, self.max_length, self.processing_class.pad_token_id) + policy_output_decoded = self.processing_class.batch_decode(policy_output, skip_special_tokens=True) + + reference_output = pad_to_length(reference_output, self.max_length, self.processing_class.pad_token_id) + reference_output_decoded = self.processing_class.batch_decode(reference_output, skip_special_tokens=True) + + return policy_output_decoded, reference_output_decoded + + def prediction_step( + self, + model: PreTrainedModel | nn.Module, + inputs: dict[str, torch.Tensor | Any], + prediction_loss_only: bool, + ignore_keys: list[str] | None = None, + ): + if ignore_keys is None: + if hasattr(model, "config"): + ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", []) + else: + ignore_keys = [] + + prediction_context_manager = ( + autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() + ) + with torch.no_grad(), prediction_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs, do_train=False) + + # force log the metrics + if self.accelerator.is_main_process: + self.store_metrics(metrics, train_eval="eval") + + if prediction_loss_only: + return (loss.detach(), None, None) + + # logits for the chosen and rejected samples from model + logits_dict = {} + if "logits/chosen_sum" in metrics: + logits_dict["eval_logits/chosen"] = metrics["logits/chosen_sum"] + if "logits/rejected_sum" in metrics: + logits_dict["eval_logits/rejected"] = metrics["logits/rejected_sum"] + logits = [v for k, v in logits_dict.items() if k not in ignore_keys] + logits = torch.tensor(logits, device=self.accelerator.device) + labels = torch.zeros(logits.shape[0], device=self.accelerator.device) + + return (loss.detach(), logits, labels) + + def evaluation_loop( + self, + dataloader: DataLoader, + description: str, + prediction_loss_only: bool | None = None, + ignore_keys: list[str] | None = None, + metric_key_prefix: str = "eval", + ) -> EvalLoopOutput: + """ + Overriding built-in evaluation loop to store metrics for each batch. Prediction/evaluation loop, shared by + `Trainer.evaluate()` and `Trainer.predict()`. + + Works both with or without labels. + """ + + # Sample and save to game log if requested (for one batch to save time) + if self.generate_during_eval: + # Generate random indices within the range of the total number of samples + num_samples = len(dataloader.dataset) + random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size) + + # Use dataloader.dataset.select to get the random batch without iterating over the DataLoader + random_batch_dataset = dataloader.dataset.select(random_indices) + random_batch = self.data_collator(random_batch_dataset) + random_batch = self._prepare_inputs(random_batch) + + target_labels = torch.tensor(random_batch["label"], dtype=torch.bool, device=self.accelerator.device) + target_indices = torch.where(~target_labels)[0] + target_batch = { + "prompt_input_ids": random_batch["prompt_input_ids"][target_indices], + "prompt_attention_mask": random_batch["prompt_attention_mask"][target_indices], + "prompt": itemgetter(*target_indices)(random_batch["prompt"]), + } + policy_output_decoded, ref_output_decoded = self.generate_from_model_and_ref(self.model, target_batch) + + table = pd.DataFrame( + columns=["Prompt", "Policy", "Ref Model"], + data=[ + [prompt, pol[len(prompt) :], ref[len(prompt) :]] + for prompt, pol, ref in zip( + target_batch["prompt"], policy_output_decoded, ref_output_decoded, strict=True + ) + ], + ) + if "wandb" in self.args.report_to: + wandb.log({"game_log": wandb.Table(data=table)}) + + if "comet_ml" in self.args.report_to: + log_table_to_comet_experiment( + name="game_log.csv", + table=table, + ) + + # Base evaluation + initial_output = super().evaluation_loop( + dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix + ) + + return initial_output + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + """ + Log `logs` on the various objects watching training, including stored metrics. + + Args: + logs (`dict[str, float]`): + The values to log. + start_time (`float`, *optional*): + Start time of the training. + """ + # logs either has 'loss' or 'eval_loss' + train_eval = "train" if "loss" in logs else "eval" + # train metrics should have no prefix, eval should have 'eval_' + prefix = "eval_" if train_eval == "eval" else "" + # accumulate average metrics from sums and lengths + for split in ["chosen", "rejected"]: + if f"count/{split}" in self._stored_metrics[train_eval]: + count_sum = torch.Tensor(self._stored_metrics[train_eval][f"count/{split}"]).sum().item() + for metric in ["rewards", "logps", "logits"]: + logs[f"{prefix}{metric}/{split}"] = ( + torch.Tensor(self._stored_metrics[train_eval][f"{metric}/{split}_sum"]).sum().item() + / count_sum + ) + # delete obsolete metric + del self._stored_metrics[train_eval][f"{metric}/{split}_sum"] + del self._stored_metrics[train_eval][f"count/{split}"] + # calculate reward margin + if f"{prefix}rewards/chosen" in logs and f"{prefix}rewards/rejected" in logs: + logs[f"{prefix}rewards/margins"] = logs[f"{prefix}rewards/chosen"] - logs[f"{prefix}rewards/rejected"] + # Add averaged stored metrics to logs + for key, metrics in self._stored_metrics[train_eval].items(): + logs[f"{prefix}{key}"] = torch.Tensor(metrics).mean().item() + del self._stored_metrics[train_eval] + return super().log(logs, start_time) + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/bema_for_ref_model/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/bema_for_ref_model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8d7de0bee7977851b77a803f297a91ed6d170e27 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/bema_for_ref_model/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .callback import BEMACallback +from .dpo_trainer import DPOTrainer diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/bema_for_ref_model/callback.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/bema_for_ref_model/callback.py new file mode 100644 index 0000000000000000000000000000000000000000..d7a593b27014bc8df85f2006c0d07d73341c2960 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/bema_for_ref_model/callback.py @@ -0,0 +1,221 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging + +import torch +from transformers import PreTrainedModel, TrainerControl, TrainerState, TrainingArguments +from transformers.trainer_callback import CallbackHandler + +from ...trainer.callbacks import BEMACallback as _BEMACallback + + +# Logger for module-level logging +logger = logging.getLogger(__name__) + + +class CallbackHandlerWithRefModel(CallbackHandler): + """ + A [`~transformers.CallbackHandler`] that supports passing a reference model to callbacks. + """ + + def __init__(self, callbacks, model, ref_model, processing_class, optimizer, lr_scheduler): + super().__init__(callbacks, model, processing_class, optimizer, lr_scheduler) + self.ref_model = ref_model + + # Copied from CallbackHandler.call_event with the addition of `ref_model` to the callback call. + def call_event(self, event, args, state, control, **kwargs): + for callback in self.callbacks: + result = getattr(callback, event)( + args, + state, + control, + model=self.model, + ref_model=self.ref_model, # <- Added ref_model to the callback call + processing_class=self.processing_class, + optimizer=self.optimizer, + lr_scheduler=self.lr_scheduler, + train_dataloader=self.train_dataloader, + eval_dataloader=self.eval_dataloader, + **kwargs, + ) + # A Callback can skip the return of `control` if it doesn't change it. + if result is not None: + control = result + return control + + +class BEMACallback(_BEMACallback): + # docstyle-ignore + r""" + A [`~transformers.TrainerCallback`] that implements [BEMA](https://huggingface.co/papers/2508.00180) + (Bias-Corrected Exponential Moving Average) by [Adam Block](https://huggingface.co/abblock) and [Cyril + Zhang](https://huggingface.co/cyrilzhang). Code from https://github.com/abblock/bema under MIT license. + + BEMA computes model weights that scale like: + + $$ + \theta_t' = \alpha_t \cdot (\theta_t - \theta_0) + \text{EMA}_t + $$ + + where \\( \theta_t \\) is the current model weights, \\( \theta_0 \\) is a snapshot of the model weights at the + first `update_after` step, \\( \text{EMA}_t \\) is the exponential moving average of the model weights, and + \\( \alpha_t \\) is a scaling factor that decays with the number of steps \\( t \\) as + + $$ + \alpha_t = (\rho + \gamma \cdot t)^{-\eta}. + $$ + + The EMA is computed as: + + $$ + \text{EMA}_t = (1 - \beta_t) \cdot \text{EMA}_{t-1} + \beta_t \cdot \theta_t + $$ + + where \\( \beta_t \\) is a decay factor that decays with the number of steps \\( t \\) as + + $$ + \beta_t = (\rho + \gamma \cdot t)^{-\kappa}. + $$ + + Args: + update_freq (`int`, *optional*, defaults to `400`): + Update the BEMA weights every X steps. Denoted this as \\( \phi \\) in the paper. + ema_power (`float`, *optional*, defaults to `0.5`): + Power for the EMA decay factor. Denoted \\( \kappa \\) in the paper. To disable EMA, set this to `0.0`. + bias_power (`float`, *optional*, defaults to `0.2`): + Power for the BEMA scaling factor. Denoted \\( \eta \\) in the paper. To disable BEMA, set this to `0.0`. + lag (`int`, *optional*, defaults to `10`): + Initial offset in the weight decay schedule that controls early-stage smoothness by acting as a virtual + starting age for the updates. Denoted as \\( \rho \\) in the paper. + update_after (`int`, *optional*, defaults to `0`): + Burn-in time before starting to update the BEMA weights. Denoted \\( \tau \\) in the paper. + multiplier (`float`, *optional*, defaults to `1.0`): + Initial value for the EMA decay factor. Denoted as \\( \gamma \\) in the paper. + min_ema_multiplier (`float`, *optional*, defaults to `0.0`): + Minimum value for the EMA decay factor. + device (`str`, *optional*, defaults to `"cpu"`): + Device to use for the BEMA buffers, e.g. `"cpu"` or `"cuda"`. Note that in most cases, this device SHOULD + BE DIFFERENT from the device used for training in order to avoid OOM. + update_ref_model (`bool`, *optional*, defaults to `False`): + Whether to update the reference model with BEMA weights. This creates a lagged, smoothed version of the + main model as the reference model. + ref_model_update_freq (`int`, *optional*, defaults to `400`): + Update the reference model with BEMA weights every this many steps. + ref_model_update_after (`int`, *optional*, defaults to `0`): + Number of steps to wait before starting to update the reference model. + + Example: + + ```python + >>> from trl import BEMACallback + + >>> trainer = Trainer(..., callbacks=[BEMACallback()]) + ``` + """ + + def __init__( + self, + update_freq: int = 400, + ema_power: float = 0.5, + bias_power: float = 0.2, + lag: int = 10, + update_after: int = 0, + multiplier: float = 1.0, + min_ema_multiplier: float = 0.0, + device: str = "cpu", + update_ref_model: bool = False, + ref_model_update_freq: int = 400, + ref_model_update_after: int = 0, + ): + super().__init__( + update_freq, + ema_power, + bias_power, + lag, + update_after, + multiplier, + min_ema_multiplier, + device, + ) + # Reference model update parameters + self.update_ref_model = update_ref_model + self.ref_model_update_freq = ref_model_update_freq + self.ref_model_update_after = ref_model_update_after + + @torch.no_grad() + def on_step_end( + self, args: TrainingArguments, state: TrainerState, control: TrainerControl, model: PreTrainedModel, **kwargs + ): + super().on_step_end(args, state, control, model, **kwargs) + + step = state.global_step + # Update reference model if enabled + if ( + self.update_ref_model + and step >= self.ref_model_update_after + and (step - self.ref_model_update_after) % self.ref_model_update_freq == 0 + ): + if "ref_model" not in kwargs: + raise ValueError("'ref_model' not found in kwargs.") + + ref_model = kwargs["ref_model"] + + # Get the current BEMA state dict + bema_state_dict = self.running_model.state_dict() + + # Handle the case where ref_model is None (PEFT case) + if ref_model is None: + # In PEFT case, ref_model is None and we need to update the base model of the main model + main_model = self._unwrap_model(model) + if hasattr(main_model, "get_base_model"): + # This is a PEFT model, update the base model + base_model = main_model.get_base_model() + self._update_model_with_bema_weights(base_model, bema_state_dict, is_peft_base=True) + else: + # Regular model, update directly + self._update_model_with_bema_weights(main_model, bema_state_dict, is_peft_base=False) + else: + # ref_model is provided, unwrap it and update + ref_model = self._unwrap_model(ref_model) + if hasattr(ref_model, "get_base_model"): + # This is a PEFT model, update the base model + base_model = ref_model.get_base_model() + self._update_model_with_bema_weights(base_model, bema_state_dict, is_peft_base=True) + else: + # Regular model, update directly + self._update_model_with_bema_weights(ref_model, bema_state_dict, is_peft_base=False) + + logger.info("BEMACallback: Updated reference model with BEMA weights") + + def _update_model_with_bema_weights(self, model, bema_state_dict, is_peft_base=False): + """Helper method to update a model with BEMA weights, handling PEFT and distributed scenarios.""" + if is_peft_base: + # For PEFT base models, filter out adapter parameters + filtered_state_dict = {} + for key, value in bema_state_dict.items(): + # Skip adapter parameters + if not key.startswith("lora_") and not key.startswith("adapter_"): + # Remove 'base_model.' prefix if it exists + if key.startswith("base_model."): + base_key = key[len("base_model.") :] + else: + base_key = key + filtered_state_dict[base_key] = value + + # Update the base model + model.load_state_dict(filtered_state_dict, strict=False) + else: + # Regular model, update directly + model.load_state_dict(bema_state_dict, strict=False) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/bema_for_ref_model/dpo_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/bema_for_ref_model/dpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..8c50a232dc38c236dc64d79d32714b799ceeea8d --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/bema_for_ref_model/dpo_trainer.py @@ -0,0 +1,30 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from ...trainer.dpo_trainer import DPOTrainer as _DPOTrainer +from .callback import CallbackHandlerWithRefModel + + +class DPOTrainer(_DPOTrainer): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # Replace with a new one that calls the events with the reference model + self.callback_handler = CallbackHandlerWithRefModel( + self.callback_handler.callbacks, + self.model, + self.ref_model, + self.processing_class, + self.optimizer, + self.lr_scheduler, + ) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/cpo/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/cpo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..57e151f53f63b9af52f3b7ba9355e1b3e223fc93 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/cpo/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .cpo_config import CPOConfig +from .cpo_trainer import CPOTrainer + + +__all__ = ["CPOConfig", "CPOTrainer"] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/cpo/cpo_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/cpo/cpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..61cb88a34fb9d1871f2b9ac9d4ccff7da14ea3a4 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/cpo/cpo_config.py @@ -0,0 +1,182 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class CPOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`experimental.cpo.CPOTrainer`]. + + This class includes only the parameters that are specific to CPO training. For a full list of training arguments, + please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may + differ from those in [`~transformers.TrainingArguments`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + max_length (`int` or `None`, *optional*, defaults to `1024`): + Maximum length of the sequences (prompt + completion) in the batch. This argument is required if you want + to use the default data collator. + max_completion_length (`int`, *optional*): + Maximum length of the completion. This argument is required if you want to use the default data collator + and your model is an encoder-decoder. + beta (`float`, *optional*, defaults to `0.1`): + Parameter controlling the deviation from the reference model. Higher β means less deviation from the + reference model. For the IPO loss (`loss_type="ipo"`), β is the regularization parameter denoted by τ in + the [paper](https://huggingface.co/papers/2310.12036). + label_smoothing (`float`, *optional*, defaults to `0.0`): + Label smoothing factor. This argument is required if you want to use the default data collator. + loss_type (`str`, *optional*, defaults to `"sigmoid"`): + Type of loss to use. Possible values are: + + - `"sigmoid"`: sigmoid loss from the original [DPO](https://huggingface.co/papers/2305.18290) paper. + - `"hinge"`: hinge loss on the normalized likelihood from the + [SLiC](https://huggingface.co/papers/2305.10425) paper. + - `"ipo"`: IPO loss from the [IPO](https://huggingface.co/papers/2310.12036) paper. + - `"simpo"`: SimPO loss from the [SimPO](https://huggingface.co/papers/2405.14734) paper. + - `"alphapo"`: AlphaPO loss from the [AlphaPO](https://huggingface.co/papers/2501.03884) paper. This + automatically sets `loss_type="simpo"` and `cpo_alpha=0.0`. + + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. + cpo_alpha (`float`, *optional*, defaults to `1.0`): + Weight of the BC regularizer in CPO training. + simpo_gamma (`float`, *optional*, defaults to `0.5`): + Target reward margin for the SimPO loss, used only when the `loss_type="simpo"`. + alpha (`float`, *optional*, defaults to `0.0`): + Alpha parameter that controls reward function shape across all loss types. When alpha=0 (default), uses + standard log probability rewards. When `alpha != 0`, applies AlphaPO transformation: `r = (1 - p^(-alpha)) + / alpha` from the [AlphaPO paper](https://huggingface.co/papers/2501.03884). This parameter works with all + loss types. + generate_during_eval (`bool`, *optional*, defaults to `False`): + If `True`, generates and logs completions from the model to W&B or Comet during evaluation. + is_encoder_decoder (`bool`, *optional*): + When using the `model_init` argument (callable) to instantiate the model instead of the `model` argument, + you need to specify if the model returned by the callable is an encoder-decoder model. + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a + string. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to allow loading models that ship custom Python code from the Hub. Forwarded to + [`~transformers.AutoModelForCausalLM.from_pretrained`]. + dataset_num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `1e-6` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=1e-6, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + max_length: int | None = field( + default=1024, + metadata={"help": "Maximum length of the sequences (prompt + completion) in the batch."}, + ) + max_completion_length: int | None = field( + default=None, + metadata={ + "help": "Maximum length of the completion. This argument is required if you want to use the default data " + "collator and your model is an encoder-decoder." + }, + ) + beta: float = field( + default=0.1, + metadata={ + "help": "Parameter controlling the deviation from the reference model. Higher β means less deviation from " + "the reference model." + }, + ) + label_smoothing: float = field( + default=0.0, + metadata={"help": "Label smoothing factor."}, + ) + loss_type: str = field( + default="sigmoid", + metadata={ + "help": "Type of loss to use.", + "choices": ["sigmoid", "hinge", "ipo", "simpo", "alphapo"], + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the model."}, + ) + cpo_alpha: float = field( + default=1.0, + metadata={"help": "Weight of the BC regularizer in CPO training."}, + ) + simpo_gamma: float = field( + default=0.5, + metadata={"help": "Target reward margin for the SimPO loss, used only when the `loss_type='simpo'`."}, + ) + alpha: float = field( + default=0.0, + metadata={ + "help": "Alpha parameter that controls reward function shape across all loss types. When alpha=0 " + "(default), uses standard log probability rewards. When `alpha != 0`, applies AlphaPO transformation: " + "`r = (1 - p^(-alpha)) / alpha` from the AlphaPO paper. This parameter works with all loss types." + }, + ) + generate_during_eval: bool = field( + default=False, + metadata={"help": "If `True`, generates and logs completions from the model to W&B during evaluation."}, + ) + is_encoder_decoder: bool | None = field( + default=None, + metadata={"help": "Whether the model is an encoder-decoder model."}, + ) + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model " + "from a string." + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": "Whether to allow loading models that ship custom Python code from the Hub. Forwarded to " + "`AutoModelForCausalLM.from_pretrained`." + }, + ) + dataset_num_proc: int | None = field( + default=None, + metadata={"help": "Number of processes to use for processing the dataset."}, + ) + + def __post_init__(self): + # Syntactic sugar for AlphaPO: set loss_type to "simpo" and cpo_alpha to 0.0 + if self.loss_type == "alphapo": + self.loss_type = "simpo" + self.cpo_alpha = 0.0 + + super().__post_init__() diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/cpo/cpo_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/cpo/cpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..7d2da929a1088e300822e9c2551b3c5110c85d19 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/cpo/cpo_trainer.py @@ -0,0 +1,1071 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import random +import textwrap +from collections import defaultdict +from collections.abc import Callable +from contextlib import nullcontext +from pathlib import Path +from typing import Any, Literal + +import numpy as np +import pandas as pd +import torch +import torch.nn as nn +import torch.nn.functional as F +import transformers +from accelerate import PartialState +from accelerate.logging import get_logger +from accelerate.utils import is_peft_model +from datasets import Dataset +from packaging.version import Version +from torch import autocast +from torch.utils.data import DataLoader +from transformers import ( + AutoModelForCausalLM, + BaseImageProcessor, + DataCollator, + FeatureExtractionMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, + is_comet_available, + is_wandb_available, +) +from transformers.trainer_utils import EvalLoopOutput +from transformers.utils import is_peft_available, is_torch_fx_proxy + +from ...data_utils import maybe_apply_chat_template, maybe_extract_prompt +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import disable_dropout_in_model, log_table_to_comet_experiment, selective_log_softmax +from ..utils import ( + DPODataCollatorWithPadding, + add_bos_token_if_needed, + add_eos_token_if_needed, + pad_to_length, + peft_module_casting_to_bf16, +) +from .cpo_config import CPOConfig + + +if is_peft_available(): + from peft import PeftConfig, get_peft_model, prepare_model_for_kbit_training + + +if is_wandb_available(): + import wandb + + +logger = get_logger(__name__) + + +class CPOTrainer(_BaseTrainer): + r""" + Initialize CPOTrainer. + + Args: + model ([`~transformers.PreTrainedModel`]): + The model to train, preferably an [`~transformers.AutoModelForSequenceClassification`]. + args ([`experimental.cpo.CPOConfig`]): + The CPO config arguments to use for training. + data_collator ([`~transformers.DataCollator`]): + The data collator to use for training. If None is specified, the default data collator + ([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the + maximum length of the sequences in the batch, given a dataset of paired sequences. + train_dataset ([`~datasets.Dataset`]): + The dataset to use for training. + eval_dataset ([`~datasets.Dataset`]): + The dataset to use for evaluation. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + model_init (`Callable[[], transformers.PreTrainedModel]`): + The model initializer to use for training. If None is specified, the default model initializer will be + used. + callbacks (`list[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + peft_config ([`~peft.PeftConfig`], *optional*): + The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in + a PEFT model. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to + metric values. + """ + + _tag_names = ["trl", "cpo"] + _name = "CPO" + _paper = { + "title": "Contrastive Preference Optimization: Pushing the Boundaries of LLM Performance in Machine Translation", + "id": "2401.08417", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @inproceedings{xu2024contrastive, + title = {{Contrastive Preference Optimization: Pushing the Boundaries of LLM Performance in Machine Translation}}, + author = {Haoran Xu and Amr Sharaf and Yunmo Chen and Weiting Tan and Lingfeng Shen and Benjamin Van Durme and Kenton Murray and Young Jin Kim}, + year = 2024, + booktitle = {Forty-first International Conference on Machine Learning, {ICML} 2024, Vienna, Austria, July 21-27, 2024}, + publisher = {OpenReview.net}, + url = {https://openreview.net/forum?id=51iwkioZpn} + }"""), + } + + def __init__( + self, + model: PreTrainedModel | nn.Module | str | None = None, + args: CPOConfig | None = None, + data_collator: DataCollator | None = None, + train_dataset: Dataset | None = None, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + processing_class: PreTrainedTokenizerBase + | BaseImageProcessor + | FeatureExtractionMixin + | ProcessorMixin + | None = None, + model_init: Callable[[], PreTrainedModel] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + peft_config: "PeftConfig | None" = None, + compute_metrics: Callable[[EvalLoopOutput], dict] | None = None, + ): + if train_dataset is None: + raise ValueError("`train_dataset` is required") + + if args.model_init_kwargs is None: + model_init_kwargs = {} + elif not isinstance(model, str): + raise ValueError("You passed model_kwargs to the CPOTrainer. But your model is already instantiated.") + else: + model_init_kwargs = args.model_init_kwargs + dtype = model_init_kwargs.get("dtype", "auto") + if dtype is not None: + # Convert to `torch.dtype` if an str is passed + if isinstance(dtype, str) and dtype != "auto": + dtype = getattr(torch, dtype) + if dtype != "auto" and not isinstance(dtype, torch.dtype): + raise ValueError( + f"Invalid `dtype` passed to the CPOConfig. Expected a string with either `torch.dtype` or 'auto', but got {dtype}." + ) + model_init_kwargs["dtype"] = dtype + model_init_kwargs["device_map"] = model_init_kwargs.get("device_map", "auto") + + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + + if isinstance(model, str): + model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs) + + # PEFT + # Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16` + # has been called in order to properly call autocast if needed. + self._peft_has_been_casted_to_bf16 = False + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first " + "merge and unload the existing adapter, save the resulting base model, and then pass that base " + "model along with the new `peft_config` to the trainer." + ) + + if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False): + _support_gc_kwargs = hasattr( + args, "gradient_checkpointing_kwargs" + ) and "gradient_checkpointing_kwargs" in list( + inspect.signature(prepare_model_for_kbit_training).parameters + ) + + prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing} + + if _support_gc_kwargs: + prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs + + model = prepare_model_for_kbit_training(model, **prepare_model_kwargs) + elif args.gradient_checkpointing: + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + # get peft model with the given config + model = get_peft_model(model, peft_config) + if args.bf16 and getattr(model, "is_loaded_in_4bit", False): + peft_module_casting_to_bf16(model) + # If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager + self._peft_has_been_casted_to_bf16 = True + + # For models that use gradient_checkpointing, we need to attach a hook that enables input + # to explicitly have `requires_grad=True`, otherwise training will either silently + # fail or completely fail. + elif args.gradient_checkpointing: + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + if args.generate_during_eval and not (is_wandb_available() or is_comet_available()): + raise ValueError( + "`generate_during_eval=True` requires Weights and Biases or Comet to be installed." + " Please install `wandb` or `comet-ml` to resolve." + ) + + if model is not None: + self.is_encoder_decoder = model.config.is_encoder_decoder + elif args.is_encoder_decoder is None: + raise ValueError("When no model is provided, you need to pass the parameter is_encoder_decoder.") + else: + self.is_encoder_decoder = args.is_encoder_decoder + + if self.is_encoder_decoder: + self.decoder_start_token_id = model.config.decoder_start_token_id + self.pad_token_id = model.config.pad_token_id + + if processing_class is None: + raise ValueError("processing_class must be specified to tokenize a CPO dataset.") + if args.max_length is None: + logger.warning( + "`max_length` is not set in the CPOConfig's init" + " it will default to `512` by default, but you should do it yourself in the future.", + ) + max_length = 512 + else: + max_length = args.max_length + + if args.max_completion_length is None and self.is_encoder_decoder: + logger.warning( + "When using an encoder decoder architecture, you should set `max_completion_length` in the CPOConfig's init" + " it will default to `128` by default, but you should do it yourself in the future.", + ) + max_completion_length = 128 + else: + max_completion_length = args.max_completion_length + + if data_collator is None: + data_collator = DPODataCollatorWithPadding( + pad_token_id=processing_class.pad_token_id, + is_encoder_decoder=self.is_encoder_decoder, + ) + + if args.remove_unused_columns: + args.remove_unused_columns = False + # warn users + logger.warning( + "When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your TrainingArguments" + " we have set it for you, but you should do it yourself in the future.", + ) + + self.use_dpo_data_collator = True + else: + self.use_dpo_data_collator = False + + # Disable dropout in the model + if args.disable_dropout: + disable_dropout_in_model(model) + + self.max_length = max_length + self.generate_during_eval = args.generate_during_eval + self.max_completion_length = max_completion_length + self.processing_class = processing_class + + if processing_class.pad_token is None: + processing_class.pad_token = processing_class.eos_token + self.pad_token_id = processing_class.pad_token_id + + if args.loss_type in ["hinge", "ipo"] and args.label_smoothing > 0: + logger.warning( + f"You are using the {args.loss_type} loss type that does not support label smoothing. The " + "`label_smoothing` parameter will be ignored. Set `label_smoothing` to `0.0` to remove this warning.", + ) + if args.loss_type == "kto_pair": + raise ValueError("Support for kto_pair has been removed in CPOTrainer. Please use KTOTrainer.") + + self.beta = args.beta + self.label_smoothing = args.label_smoothing + self.loss_type = args.loss_type + self.cpo_alpha = args.cpo_alpha + self.aux_loss_enabled = getattr(model.config, "output_router_logits", False) + self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0) + if self.aux_loss_enabled and self.aux_loss_coef == 0.0: + logger.warning( + "You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to " + "`0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value " + "greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary " + "loss.", + ) + + if args.loss_type == "simpo": + self.simpo_gamma = args.simpo_gamma + + # AlphaPO parameter for reward shaping + self.alpha = args.alpha + + self._stored_metrics = defaultdict(lambda: defaultdict(list)) + + # Compute that only on the main process for faster data processing. + # see: https://github.com/huggingface/trl/pull/1255 + with PartialState().main_process_first(): + # Extract the prompt if needed, and apply the chat template if needed + train_dataset = train_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc) + train_dataset = train_dataset.map( + maybe_apply_chat_template, + fn_kwargs={"processing_class": processing_class}, + num_proc=args.dataset_num_proc, + ) + if eval_dataset is not None: + eval_dataset = eval_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc) + eval_dataset = eval_dataset.map( + maybe_apply_chat_template, + fn_kwargs={"processing_class": processing_class}, + num_proc=args.dataset_num_proc, + ) + + # tokenize the dataset + train_dataset = train_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc) + if eval_dataset is not None: + eval_dataset = eval_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc) + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + model_init=model_init, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the + # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set + # self.model_accepts_loss_kwargs to False to enable scaling. + self.model_accepts_loss_kwargs = False + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + if not hasattr(self, "accelerator"): + raise AttributeError( + "Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`." + ) + + def build_tokenized_answer(self, prompt, answer): + """ + Llama tokenizer does satisfy `enc(a + b) = enc(a) + enc(b)`. It does ensure `enc(a + b) = enc(a) + enc(a + + b)[len(enc(a)):]`. Reference: + https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 + """ + + full_tokenized = self.processing_class(prompt + answer, add_special_tokens=False) + prompt_input_ids = self.processing_class(prompt, add_special_tokens=False)["input_ids"] + + answer_input_ids = full_tokenized["input_ids"][len(prompt_input_ids) :] + answer_attention_mask = full_tokenized["attention_mask"][len(prompt_input_ids) :] + + # Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]` + full_concat_input_ids = np.concatenate([prompt_input_ids, answer_input_ids]) + + # Prepare input tokens for token by token comparison + full_input_ids = np.array(full_tokenized["input_ids"]) + + if len(full_input_ids) != len(full_concat_input_ids): + raise ValueError("Prompt input ids and answer input ids should have the same length.") + + # On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens + # can be merged together when tokenizing prompt+answer. This could result + # on the last token from the prompt being different when tokenized on its own + # vs when done as prompt+answer. + response_token_ids_start_idx = len(prompt_input_ids) + + # If tokenized prompt is different than both prompt+answer, then it means the + # last token has changed due to merging. + if prompt_input_ids != full_tokenized["input_ids"][:response_token_ids_start_idx]: + response_token_ids_start_idx -= 1 + + prompt_input_ids = full_tokenized["input_ids"][:response_token_ids_start_idx] + prompt_attention_mask = full_tokenized["attention_mask"][:response_token_ids_start_idx] + + if len(prompt_input_ids) != len(prompt_attention_mask): + raise ValueError("Prompt input ids and attention mask should have the same length.") + + answer_input_ids = full_tokenized["input_ids"][response_token_ids_start_idx:] + answer_attention_mask = full_tokenized["attention_mask"][response_token_ids_start_idx:] + + return dict( + prompt_input_ids=prompt_input_ids, + prompt_attention_mask=prompt_attention_mask, + input_ids=answer_input_ids, + attention_mask=answer_attention_mask, + ) + + def tokenize_row(self, feature, model: PreTrainedModel | nn.Module | None = None) -> dict: + """Tokenize a single row from a CPO specific dataset. + + At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt + + chosen or prompt + rejected responses is/are too long. First we truncate the prompt; if we're still too long, + we truncate the chosen/rejected. + + We also create the labels for the chosen/rejected responses, which are of length equal to the sum of the length + of the prompt and the chosen/rejected response, with `-100` for the prompt tokens. + """ + batch = {} + prompt = feature["prompt"] + chosen = feature["chosen"] + rejected = feature["rejected"] + + if not self.is_encoder_decoder: + # Check issues below for more details + # 1. https://github.com/huggingface/trl/issues/907 + # 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 + # 3. https://github.com/LianjiaTech/BELLE/issues/337 + + if not isinstance(prompt, str): + raise ValueError(f"prompt should be an str but got {type(prompt)}") + prompt_tokens = self.processing_class(prompt, add_special_tokens=False) + prompt_tokens = {f"prompt_{k}": v for k, v in prompt_tokens.items()} + + if not isinstance(chosen, str): + raise ValueError(f"chosen should be an str but got {type(chosen)}") + chosen_tokens = self.build_tokenized_answer(prompt, chosen) + + if not isinstance(rejected, str): + raise ValueError(f"rejected should be an str but got {type(rejected)}") + rejected_tokens = self.build_tokenized_answer(prompt, rejected) + + # Last prompt token might get merged by tokenizer and + # it should not be included for generation if that happens + prompt_len_input_ids = len(prompt_tokens["prompt_input_ids"]) + + chosen_prompt_len_input_ids = len(chosen_tokens["prompt_input_ids"]) + rejected_prompt_len_input_ids = len(rejected_tokens["prompt_input_ids"]) + prompt_len_input_ids = min(chosen_prompt_len_input_ids, rejected_prompt_len_input_ids) + + for k, v in prompt_tokens.items(): + prompt_tokens[k] = v[:prompt_len_input_ids] + + # Make sure prompts only have one different token at most an + # and length only differs by 1 at most + num_diff_tokens = sum( + a != b + for a, b in zip(chosen_tokens["prompt_input_ids"], rejected_tokens["prompt_input_ids"], strict=False) + ) + num_diff_len = abs(chosen_prompt_len_input_ids - rejected_prompt_len_input_ids) + if num_diff_tokens > 1 or num_diff_len > 1: + raise ValueError( + "Chosen and rejected prompt_input_ids might only differ on the " + "last token due to tokenizer merge ops." + ) + + # add BOS token to head of prompt. Avoid adding if it's already there + prompt_tokens, chosen_tokens, rejected_tokens = add_bos_token_if_needed( + self.processing_class.bos_token_id, + prompt_len_input_ids, + prompt_tokens, + chosen_prompt_len_input_ids, + chosen_tokens, + rejected_prompt_len_input_ids, + rejected_tokens, + ) + + # add EOS token to end of answer. Avoid adding if it's already there + chosen_tokens, rejected_tokens = add_eos_token_if_needed( + self.processing_class.eos_token_id, chosen_tokens, rejected_tokens + ) + + longer_response_length = max(len(chosen_tokens["input_ids"]), len(rejected_tokens["input_ids"])) + + # if combined sequence is too long, truncate the response + for answer_tokens in [chosen_tokens, rejected_tokens]: + if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length: + for k in ["input_ids", "attention_mask"]: + answer_tokens[k] = answer_tokens[k][: self.max_length - longer_response_length] + + # Create labels + chosen_sequence_tokens = { + k: chosen_tokens[f"prompt_{k}"] + chosen_tokens[k] for k in ["input_ids", "attention_mask"] + } + rejected_sequence_tokens = { + k: rejected_tokens[f"prompt_{k}"] + rejected_tokens[k] for k in ["input_ids", "attention_mask"] + } + chosen_sequence_tokens["labels"] = chosen_sequence_tokens["input_ids"][:] + chosen_sequence_tokens["labels"][: len(chosen_tokens["prompt_input_ids"])] = [-100] * len( + chosen_tokens["prompt_input_ids"] + ) + rejected_sequence_tokens["labels"] = rejected_sequence_tokens["input_ids"][:] + rejected_sequence_tokens["labels"][: len(rejected_tokens["prompt_input_ids"])] = [-100] * len( + rejected_tokens["prompt_input_ids"] + ) + + for k, toks in { + "chosen_": chosen_sequence_tokens, + "rejected_": rejected_sequence_tokens, + "": prompt_tokens, + }.items(): + for type_key, tokens in toks.items(): + if type_key == "token_type_ids": + continue + batch[f"{k}{type_key}"] = tokens + + else: + chosen_tokens = self.processing_class( + chosen, truncation=True, max_length=self.max_completion_length, add_special_tokens=True + ) + rejected_tokens = self.processing_class( + rejected, truncation=True, max_length=self.max_completion_length, add_special_tokens=True + ) + prompt_tokens = self.processing_class(prompt, add_special_tokens=True) + + batch["chosen_labels"] = chosen_tokens["input_ids"] + batch["rejected_labels"] = rejected_tokens["input_ids"] + batch["prompt_input_ids"] = prompt_tokens["input_ids"] + batch["prompt_attention_mask"] = prompt_tokens["attention_mask"] + + if model is not None and hasattr(model, "prepare_decoder_input_ids_from_labels"): + batch["rejected_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels( + labels=torch.tensor(batch["rejected_labels"]) + ) + batch["chosen_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels( + labels=torch.tensor(batch["chosen_labels"]) + ) + + return batch + + @staticmethod + def concatenated_inputs( + batch: dict[str, list | torch.LongTensor], + is_encoder_decoder: bool = False, + padding_value: int = 0, + device: torch.device | None = None, + ) -> dict[str, torch.LongTensor]: + """Concatenate the chosen and rejected inputs into a single tensor. + + Args: + batch: + A batch of data. Must contain the keys 'chosen_input_ids' and 'rejected_input_ids', which are tensors + of shape (batch_size, sequence_length). + is_encoder_decoder: + Whether the model is an encoder-decoder model. + padding_value: + The padding value to use for the concatenated inputs_ids. + device: + The device for the concatenated inputs. + + Returns: + A dictionary containing the concatenated inputs under the key 'concatenated_input_ids'. + """ + concatenated_batch = {} + + if is_encoder_decoder: + max_length = max(batch["chosen_labels"].shape[1], batch["rejected_labels"].shape[1]) + else: + max_length = max(batch["chosen_input_ids"].shape[1], batch["rejected_input_ids"].shape[1]) + + for k in batch: + if k.startswith("chosen") and isinstance(batch[k], torch.Tensor): + if "labels" in k or is_encoder_decoder: + pad_value = -100 + elif k.endswith("_input_ids"): + pad_value = padding_value + elif k.endswith("_attention_mask"): + pad_value = 0 + concatenated_key = k.replace("chosen", "concatenated") + concatenated_batch[concatenated_key] = pad_to_length(batch[k], max_length, pad_value=pad_value) + for k in batch: + if k.startswith("rejected") and isinstance(batch[k], torch.Tensor): + if "labels" in k or is_encoder_decoder: + pad_value = -100 + elif k.endswith("_input_ids"): + pad_value = padding_value + elif k.endswith("_attention_mask"): + pad_value = 0 + concatenated_key = k.replace("rejected", "concatenated") + concatenated_batch[concatenated_key] = torch.cat( + ( + concatenated_batch[concatenated_key], + pad_to_length(batch[k], max_length, pad_value=pad_value), + ), + dim=0, + ).to(device=device) + + if is_encoder_decoder: + concatenated_batch["concatenated_input_ids"] = batch["prompt_input_ids"].repeat(2, 1).to(device=device) + concatenated_batch["concatenated_attention_mask"] = ( + batch["prompt_attention_mask"].repeat(2, 1).to(device=device) + ) + + return concatenated_batch + + def cpo_loss( + self, + policy_chosen_logps: torch.FloatTensor, + policy_rejected_logps: torch.FloatTensor, + ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + """Compute the CPO loss for a batch of policy and reference model log probabilities. + + Args: + policy_chosen_logps: + Log probabilities of the policy model for the chosen responses. Shape: (batch_size,) + policy_rejected_logps: + Log probabilities of the policy model for the rejected responses. Shape: (batch_size,) + + Returns: + A tuple of three tensors: (losses, chosen_rewards, rejected_rewards). The losses tensor contains the CPO + loss for each example in the batch. The chosen_rewards and rejected_rewards tensors contain the rewards for + the chosen and rejected responses, respectively. + """ + # Apply AlphaPO reward transformation if alpha != 0 + if self.alpha != 0.0: + # Compute probabilities + chosen_probs = torch.exp(policy_chosen_logps) + rejected_probs = torch.exp(policy_rejected_logps) + + # Apply AlphaPO transformation: r = (1 - p^(-alpha)) / alpha + policy_chosen_rewards = (1 - chosen_probs.pow(-self.alpha)) / self.alpha + policy_rejected_rewards = (1 - rejected_probs.pow(-self.alpha)) / self.alpha + + logits = (policy_chosen_rewards - policy_rejected_rewards).to(self.accelerator.device) + else: + # Standard log probability rewards when alpha = 0 + logits = (policy_chosen_logps - policy_rejected_logps).to(self.accelerator.device) + + # The beta is a temperature parameter for the CPO loss, typically something in the range of 0.1 to 0.5. + # We ignore the reference model as beta -> 0. The label_smoothing parameter encodes our uncertainty about the labels and + # calculates a conservative CPO loss. + + if self.loss_type == "simpo": + gamma_logratios = self.simpo_gamma / self.beta + logits = logits - gamma_logratios + # This reduces to Equation 3 from the CPO paper when label_smoothing -> 0. + losses = ( + -F.logsigmoid(self.beta * logits) * (1 - self.label_smoothing) + - F.logsigmoid(-self.beta * logits) * self.label_smoothing + ) + elif self.loss_type == "sigmoid": + # This reduces to Equation 3 from the CPO paper when label_smoothing -> 0. + losses = ( + -F.logsigmoid(self.beta * logits) * (1 - self.label_smoothing) + - F.logsigmoid(-self.beta * logits) * self.label_smoothing + ) + elif self.loss_type == "hinge": + losses = torch.relu(1 - self.beta * logits) + elif self.loss_type == "ipo": + # eqn (17) of the paper where beta is the regularization parameter for the IPO loss, denoted by tau in the paper. + losses = (logits - 1 / (2 * self.beta)) ** 2 + else: + raise ValueError( + f"Unknown loss type: {self.loss_type}. Should be one of ['sigmoid', 'hinge', 'ipo', 'simpo']" + ) + + # Calculate rewards for logging + if self.alpha != 0.0: + # When using AlphaPO transformation, use the transformed rewards + chosen_rewards = self.beta * policy_chosen_rewards.to(self.accelerator.device).detach() + rejected_rewards = self.beta * policy_rejected_rewards.to(self.accelerator.device).detach() + else: + # Standard log probability rewards + chosen_rewards = self.beta * (policy_chosen_logps.to(self.accelerator.device)).detach() + rejected_rewards = self.beta * (policy_rejected_logps.to(self.accelerator.device)).detach() + + return losses, chosen_rewards, rejected_rewards + + @staticmethod + def get_batch_logps( + logits: torch.FloatTensor, + labels: torch.LongTensor, + average_log_prob: bool = False, + is_encoder_decoder: bool = False, + ) -> torch.FloatTensor: + """Compute the log probabilities of the given labels under the given logits. + + Args: + logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size) + labels: + Labels for which to compute the log probabilities. Label tokens with a value of `-100` are ignored. + Shape: (batch_size, sequence_length) + average_log_prob: + If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the + log probabilities of the (non-masked) tokens. + is_encoder_decoder: Whether the model is an encoder-decoder model. + + Returns: + A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the + given logits. + """ + if logits.shape[:-1] != labels.shape: + raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.") + + if not is_encoder_decoder: + labels = labels[:, 1:].clone() + logits = logits[:, :-1, :] + loss_mask = labels != -100 + + # dummy token; we'll ignore the losses on these tokens later + labels[labels == -100] = 0 + + per_token_logps = selective_log_softmax(logits, labels) + + if average_log_prob: + return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1) + else: + return (per_token_logps * loss_mask).sum(-1) + + def concatenated_forward( + self, model: nn.Module, batch: dict[str, list | torch.LongTensor] + ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + """Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together. + + We do this to avoid doing two forward passes, because it's faster for FSDP. + """ + concatenated_batch = self.concatenated_inputs( + batch, + is_encoder_decoder=self.is_encoder_decoder, + padding_value=self.pad_token_id, + device=self.accelerator.device, + ) + len_chosen = batch["chosen_labels"].shape[0] + + model_kwargs = ( + { + "decoder_input_ids": self._shift_right(concatenated_batch["concatenated_labels"]), + } + if self.is_encoder_decoder + else {} + ) + + if self.aux_loss_enabled: + model_kwargs["output_router_logits"] = True + + outputs = model( + concatenated_batch["concatenated_input_ids"], + attention_mask=concatenated_batch["concatenated_attention_mask"], + use_cache=False, + **model_kwargs, + ) + all_logits = outputs.logits + + def cross_entropy_loss(logits, labels): + if not self.is_encoder_decoder: + # Shift so that tokens < n predict n + logits = logits[..., :-1, :].contiguous() + labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = nn.CrossEntropyLoss() + logits = logits.view(-1, logits.shape[-1]) + labels = labels.view(-1) + # Enable model parallelism + labels = labels.to(logits.device) + loss = loss_fct(logits, labels) + return loss + + labels = concatenated_batch["concatenated_labels"].clone() + + if self.cpo_alpha == 0: + nll_loss = torch.tensor(0.0).to(self.accelerator.device) + else: + nll_loss = cross_entropy_loss(all_logits[:len_chosen], labels[:len_chosen]) + + all_logps = self.get_batch_logps( + all_logits, + concatenated_batch["concatenated_labels"], + average_log_prob=self.loss_type in ["ipo", "simpo"], + is_encoder_decoder=self.is_encoder_decoder, + ) + + chosen_logps = all_logps[:len_chosen] + rejected_logps = all_logps[len_chosen:] + + chosen_logits = all_logits[:len_chosen] + rejected_logits = all_logits[len_chosen:] + + if self.aux_loss_enabled: + return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, nll_loss, outputs.aux_loss) + + return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, nll_loss) + + def get_batch_loss_metrics( + self, + model, + batch: dict[str, list | torch.LongTensor], + train_eval: Literal["train", "eval"] = "train", + ): + """Compute the CPO loss and other metrics for the given batch of inputs for train or test.""" + metrics = {} + + forward_output = self.concatenated_forward(model, batch) + ( + policy_chosen_logps, + policy_rejected_logps, + policy_chosen_logits, + policy_rejected_logits, + policy_nll_loss, + ) = forward_output[:5] + if self.aux_loss_enabled: + aux_loss = forward_output[5] + + losses, chosen_rewards, rejected_rewards = self.cpo_loss( + policy_chosen_logps, + policy_rejected_logps, + ) + + loss = losses.mean() + self.cpo_alpha * policy_nll_loss + reward_accuracies = (chosen_rewards > rejected_rewards).float() + + prefix = "eval_" if train_eval == "eval" else "" + metrics[f"{prefix}rewards/chosen"] = self.accelerator.gather_for_metrics(chosen_rewards).mean().item() + metrics[f"{prefix}rewards/rejected"] = self.accelerator.gather_for_metrics(rejected_rewards).mean().item() + metrics[f"{prefix}rewards/accuracies"] = self.accelerator.gather_for_metrics(reward_accuracies).mean().item() + metrics[f"{prefix}rewards/margins"] = ( + self.accelerator.gather_for_metrics(chosen_rewards - rejected_rewards).mean().item() + ) + metrics[f"{prefix}logps/rejected"] = ( + self.accelerator.gather_for_metrics(policy_rejected_logps).detach().mean().item() + ) + metrics[f"{prefix}logps/chosen"] = ( + self.accelerator.gather_for_metrics(policy_chosen_logps).detach().mean().item() + ) + metrics[f"{prefix}logits/rejected"] = ( + self.accelerator.gather_for_metrics(policy_rejected_logits.detach().mean()).mean().item() + ) + metrics[f"{prefix}logits/chosen"] = ( + self.accelerator.gather_for_metrics(policy_chosen_logits.detach().mean()).mean().item() + ) + metrics[f"{prefix}nll_loss"] = self.accelerator.gather_for_metrics(policy_nll_loss).detach().mean().item() + + if self.aux_loss_enabled: + loss += self.aux_loss_coef * aux_loss + + return loss, metrics + + def compute_loss( + self, + model: PreTrainedModel | nn.Module, + inputs: dict[str, torch.Tensor | Any], + return_outputs=False, + num_items_in_batch=None, + ) -> torch.Tensor | tuple[torch.Tensor, dict[str, torch.Tensor]]: + compute_loss_context_manager = ( + autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() + ) + + with compute_loss_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="train") + + # force log the metrics + self.store_metrics(metrics, train_eval="train") + + if return_outputs: + return (loss, metrics) + return loss + + def generate_from_model(self, model, batch: dict[str, torch.LongTensor]) -> str: + """Generate samples from the model and reference model for the given batch of inputs.""" + + # If one uses `generate_during_eval` with peft + bf16, we need to explicitly call generate with + # the torch amp context manager as some hidden states are silently casted to full precision. + generate_context_manager = ( + autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() + ) + + with generate_context_manager: + policy_output = model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + + policy_output = pad_to_length(policy_output, self.max_length, self.processing_class.pad_token_id) + policy_output_decoded = self.processing_class.batch_decode(policy_output, skip_special_tokens=True) + + return policy_output_decoded + + def prediction_step( + self, + model: PreTrainedModel | nn.Module, + inputs: dict[str, torch.Tensor | Any], + prediction_loss_only: bool, + ignore_keys: list[str] | None = None, + ): + if ignore_keys is None: + if hasattr(model, "config"): + ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", []) + else: + ignore_keys = [] + + prediction_context_manager = ( + autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() + ) + + with torch.no_grad(), prediction_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="eval") + + # force log the metrics + self.store_metrics(metrics, train_eval="eval") + + if prediction_loss_only: + return (loss.detach(), None, None) + + # logits for the chosen and rejected samples from model + logits_dict = { + "eval_logits/chosen": metrics["eval_logits/chosen"], + "eval_logits/rejected": metrics["eval_logits/rejected"], + } + logits = [v for k, v in logits_dict.items() if k not in ignore_keys] + logits = torch.tensor(logits, device=self.accelerator.device) + labels = torch.zeros(logits.shape[0], device=self.accelerator.device) + + return (loss.detach(), logits, labels) + + def store_metrics(self, metrics: dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None: + for key, value in metrics.items(): + self._stored_metrics[train_eval][key].append(value) + + def evaluation_loop( + self, + dataloader: DataLoader, + description: str, + prediction_loss_only: bool | None = None, + ignore_keys: list[str] | None = None, + metric_key_prefix: str = "eval", + ) -> EvalLoopOutput: + """ + Overriding built-in evaluation loop to store metrics for each batch. Prediction/evaluation loop, shared by + `Trainer.evaluate()` and `Trainer.predict()`. + + Works both with or without labels. + """ + + # Sample and save to game log if requested (for one batch to save time) + if self.generate_during_eval: + # Generate random indices within the range of the total number of samples + num_samples = len(dataloader.dataset) + random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size) + + # Use dataloader.dataset.select to get the random batch without iterating over the DataLoader + random_batch_dataset = dataloader.dataset.select(random_indices) + random_batch = self.data_collator(random_batch_dataset) + random_batch = self._prepare_inputs(random_batch) + + policy_output_decoded = self.generate_from_model(self.model, random_batch) + + table = pd.DataFrame( + columns=["Prompt", "Policy"], + data=[ + [prompt, pol[len(prompt) :]] + for prompt, pol in zip(random_batch["prompt"], policy_output_decoded, strict=True) + ], + ) + if "wandb" in self.args.report_to: + wandb.log({"game_log": wandb.Table(data=table)}) + + if "comet_ml" in self.args.report_to: + log_table_to_comet_experiment( + name="game_log.csv", + table=table, + ) + + # Base evaluation + initial_output = super().evaluation_loop( + dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix + ) + + return initial_output + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + """ + Log `logs` on the various objects watching training, including stored metrics. + + Args: + logs (`dict[str, float]`): + The values to log. + start_time (`float`, *optional*): + Start time of the training. + """ + # logs either has 'loss' or 'eval_loss' + train_eval = "train" if "loss" in logs else "eval" + # Add averaged stored metrics to logs + for key, metrics in self._stored_metrics[train_eval].items(): + logs[key] = torch.tensor(metrics).mean().item() + del self._stored_metrics[train_eval] + return super().log(logs, start_time) + + def _shift_right(self, input_ids): + if self.decoder_start_token_id is None: + raise ValueError( + "model.config.decoder_start_token_id has to be defined. It is usually set to the pad_token_id." + ) + + # shift inputs to the right + if is_torch_fx_proxy(input_ids): + # Item assignment is not supported natively for proxies. + shifted_input_ids = torch.full(input_ids.shape[:-1] + (1,), self.decoder_start_token_id) + shifted_input_ids = torch.cat([shifted_input_ids, input_ids[..., :-1]], dim=-1) + else: + shifted_input_ids = input_ids.new_zeros(input_ids.shape) + shifted_input_ids[..., 1:] = input_ids[..., :-1].clone() + shifted_input_ids[..., 0] = self.decoder_start_token_id + + if self.pad_token_id is None: + raise ValueError("model.config.pad_token_id has to be defined.") + # replace possible -100 values in labels by `pad_token_id` + shifted_input_ids.masked_fill_(shifted_input_ids == -100, self.pad_token_id) + + return shifted_input_ids + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/distillation/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/distillation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..894333c1d01c23f82964cd651ee45a7c3d652e65 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/distillation/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .distillation_config import DistillationConfig +from .distillation_trainer import DistillationTrainer + + +__all__ = ["DistillationConfig", "DistillationTrainer"] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/distillation/distillation_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/distillation/distillation_config.py new file mode 100644 index 0000000000000000000000000000000000000000..c70dd4b2d6d32a347590dfb48573fd2acd641407 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/distillation/distillation_config.py @@ -0,0 +1,454 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class DistillationConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`DistillationTrainer`]. + + Extends [`~transformers.TrainingArguments`] with parameters specific to knowledge distillation. This config is + independent of [`SFTConfig`] — all necessary fields are declared here. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + > Parameters that control the model + + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of the + trainer is provided as a string. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to + [`~transformers.AutoModelForCausalLM.from_pretrained`] and + [`~transformers.AutoTokenizer.from_pretrained`], for both the student and teacher. + max_length (`int` or `None`, *optional*, defaults to `1024`): + Maximum total sequence length (prompt + completion) for tokenization and truncation. + + > Parameters that control the distillation + + temperature (`float`, *optional*, defaults to `1.0`): + Temperature for sampling during generation and for computing the distillation loss. Higher values produce + softer probability distributions. + lmbda (`float`, *optional*, defaults to `1.0`): + Probability of using on-policy (student-generated) data for each gradient accumulation slice. A value of + `0.0` means fully off-policy (dataset completions only), `1.0` means fully on-policy. + beta (`float`, *optional*, defaults to `1.0`): + Interpolation coefficient for the Generalized Jensen-Shannon Divergence loss. When `0.0`, the loss is the + forward KL divergence. When `1.0`, the loss is the reverse KL divergence. When `0.5`, it is the standard + JSD. + reverse_kl_top_1_mode (`str`, *optional*, defaults to `"sampled"`): + Selection rule for the reverse-KL top-1 token when `beta > 0` and `loss_top_k == 1`. `"sampled"` uses the + actual completion token in the batch. `"argmax"` uses the student's highest-probability token. This + setting does not affect the forward-KL support, which always uses the teacher's top-1 token. Ignored when + `beta == 0` or `loss_top_k != 1`. + max_completion_length (`int`, *optional*, defaults to `512`): + Maximum number of tokens to generate per completion during on-policy generation. + max_prompt_length (`int` or `None`, *optional*): + Maximum number of tokens for the prompt. If `None`, auto-computed as `max_length - max_completion_length`. + Prompts are truncated according to the tokenizer's `truncation_side` setting. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the student model during training. + + > Parameters that control the teacher model + + teacher_model_name_or_path (`str` or `None`, *optional*): + Model name or path for the teacher model. Used when the teacher is loaded locally. + teacher_model_revision (`str` or `None`, *optional*): + Model revision of the teacher model (e.g., branch name, tag, or commit hash). + teacher_model_init_kwargs (`dict[str, Any]` or `None`, *optional*): + Keyword arguments passed to `AutoModelForCausalLM.from_pretrained` when instantiating the teacher model + from a string. + use_teacher_server (`bool`, *optional*, defaults to `False`): + Whether to use an external vLLM teacher server instead of a local teacher model. + teacher_model_server_url (`str` or `None`, *optional*): + Base URL of a vLLM server hosting the teacher model (e.g., `"http://localhost:8000"`). When set, teacher + logprobs are fetched from the server instead of running a local forward pass when `use_teacher_server=True`. + loss_top_k (`int`, *optional*, defaults to `1`): + Number of top tokens to use when computing the JSD/KL loss. Both student and teacher distributions are + restricted to these K tokens and re-normalized before computing divergence. If 0, the full vocabulary + is used. For local teachers, the general support rule is teacher top-k for forward KL, student top-k for + reverse KL, and the union for mixed JSD. When `beta > 0` and `loss_top_k == 1`, the forward support still + uses the teacher's top-1 token, while the reverse top-1 token is controlled by `reverse_kl_top_1_mode`. + When `use_teacher_server=True`, the pure forward path (`beta=0`) requires this to be positive and uses the + teacher's top-k logprobs for the forward term. When `beta > 0`, server-backed distillation requires + `loss_top_k == 1` and only supports `"sampled"` reverse top-1 tokens. + loss_add_tail (`bool`, *optional*, defaults to `True`): + Whether to append a tail bucket that represents the remaining probability mass outside the selected top-k + support when computing the loss. + + > Parameters that control on-policy generation + + num_generations (`int`, *optional*, defaults to `1`): + Number of completions to generate per prompt during on-policy generation. + generation_batch_size (`int` or `None`, *optional*): + Number of unique prompts per worker per optimizer step. If `None`, computed from + `(per_device_train_batch_size * gradient_accumulation_steps) // num_generations`. + top_p (`float`, *optional*, defaults to `0.95`): + Top-p (nucleus) sampling parameter for on-policy generation. + top_k (`int`, *optional*, defaults to `0`): + Top-k sampling parameter for on-policy generation. `0` disables top-k filtering. + + > Parameters that control vLLM for student generation + + use_vllm (`bool`, *optional*, defaults to `False`): + Whether to use vLLM for generating on-policy completions from the student model. + vllm_mode (`str`, *optional*, defaults to `"colocate"`): + Mode for student vLLM integration. Either `"server"` or `"colocate"`. + vllm_server_base_url (`str` or `None`, *optional*): + Base URL for the student vLLM server. If provided, `vllm_server_host` and `vllm_server_port` are ignored. + vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`): + Host of the student vLLM server. + vllm_server_port (`int`, *optional*, defaults to `8001`): + Port of the student vLLM server. + vllm_server_timeout (`float`, *optional*, defaults to `240.0`): + Timeout for connecting to the student vLLM server. + vllm_group_port (`int`, *optional*, defaults to `51216`): + Port for the vLLM weight-update group (NCCL communicator). + vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.3`): + GPU memory utilization for the colocated student vLLM engine. + vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`): + Tensor parallel size for the colocated student vLLM engine. + vllm_max_model_length (`int` or `None`, *optional*): + Maximum model sequence length for the colocated vLLM engine. + vllm_model_impl (`str`, *optional*, defaults to `"vllm"`): + Model implementation backend for vLLM. Use `"vllm"` or `"transformers"`. + vllm_structured_outputs_regex (`str` or `None`, *optional*): + Regex pattern for vLLM structured outputs. + vllm_sync_frequency (`int`, *optional*, defaults to `1`): + Frequency (in training steps) to synchronize student model weights to the vLLM engine. + vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`): + Enable vLLM sleep mode to offload student weights during the optimizer step. + + > Parameters that control logging + + log_completions (`bool`, *optional*, defaults to `False`): + Whether to log a sample of (prompt, completion) pairs every `log_completions_steps` steps. If `rich` is + installed, it prints the sample. If `wandb` and/or `trackio` logging is enabled, it logs it to `wandb` + and/or `trackio`. + log_completions_steps (`int`, *optional*, defaults to `100`): + Number of steps between logging completions. Only used if `log_completions` is `True`. + num_completions_to_print (`int` or `None`, *optional*): + Number of completions to print. If `None`, all completions are logged. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs", "teacher_model_init_kwargs"] + + # Model + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument " + "of the trainer is provided as a string." + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. " + "Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoTokenizer.from_pretrained`, for both the " + "student and teacher." + }, + ) + max_length: int | None = field( + default=1024, + metadata={"help": "Maximum total sequence length (prompt + completion) for tokenization and truncation."}, + ) + + # Overridden defaults + learning_rate: float = field( + default=1e-6, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + # Distillation core + temperature: float = field( + default=1.0, + metadata={ + "help": "Temperature for sampling and loss computation. Higher values produce softer distributions." + }, + ) + lmbda: float = field( + default=1.0, + metadata={ + "help": "Probability of using on-policy (student-generated) data per gradient accumulation slice. " + "0.0 = fully off-policy, 1.0 = fully on-policy." + }, + ) + beta: float = field( + default=1.0, + metadata={ + "help": "Interpolation coefficient for the Generalized JSD loss. " + "0.0 = forward KL, 0.5 = JSD, 1.0 = reverse KL." + }, + ) + reverse_kl_top_1_mode: str = field( + default="sampled", + metadata={ + "help": "Reverse-KL top-1 token selection when beta > 0 and loss_top_k == 1. " + "Use 'sampled' for the actual completion token or 'argmax' for the student's top-1 token. " + "The forward-KL support always uses the teacher's top-1 token. Ignored when beta == 0 or loss_top_k != 1." + }, + ) + max_completion_length: int = field( + default=512, + metadata={"help": "Maximum number of tokens to generate per completion."}, + ) + max_prompt_length: int | None = field( + default=None, + metadata={ + "help": "Maximum number of tokens for the prompt. If None, auto-computed as " + "max_length - max_completion_length. Prompts are truncated according to the " + "tokenizer's truncation_side setting." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the student model during training."}, + ) + + # Teacher model (local) + teacher_model_name_or_path: str | None = field( + default=None, + metadata={"help": "Model name or path for the teacher model."}, + ) + teacher_model_revision: str | None = field( + default=None, + metadata={"help": "Model revision of the teacher model (e.g., branch name, tag, or commit hash)."}, + ) + teacher_model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained` when instantiating the teacher." + }, + ) + + # Teacher model (external vLLM server) + use_teacher_server: bool = field( + default=False, + metadata={"help": "Whether to use an external vLLM teacher server instead of a local teacher model."}, + ) + teacher_model_server_url: str | None = field( + default=None, + metadata={ + "help": 'Base URL of a vLLM server hosting the teacher model (e.g., "http://localhost:8000"). ' + "Required when use_teacher_server=True." + }, + ) + loss_top_k: int = field( + default=1, + metadata={ + "help": "Number of top tokens to use when computing the JSD/KL loss. " + "Both student and teacher distributions are restricted to these K tokens " + "(selected based on beta: teacher's top-k for forward KL, student's top-k for reverse KL, " + "union of both for JSD) and re-normalized before computing divergence. " + "If 0, the full vocabulary is used (slower but exact). " + "When beta > 0 and loss_top_k == 1, the forward support still uses the teacher's top-1 token, " + "while the reverse top-1 token is controlled by reverse_kl_top_1_mode. " + "When use_teacher_server=True, beta=0 requires loss_top_k > 0 and uses the teacher's top-k " + "logprobs for the forward term. When beta > 0, server-backed distillation requires loss_top_k == 1 " + "and only supports 'sampled' reverse top-1 tokens." + }, + ) + loss_add_tail: bool = field( + default=True, + metadata={ + "help": "Whether to append a tail bucket representing the remaining probability mass outside the selected top-k support." + }, + ) + + # On-policy generation + num_generations: int = field( + default=1, + metadata={"help": "Number of completions to generate per prompt during on-policy generation."}, + ) + generation_batch_size: int | None = field( + default=None, + metadata={ + "help": "Number of unique prompts per worker per optimizer step. " + "If None, computed from (per_device_train_batch_size * gradient_accumulation_steps) // num_generations." + }, + ) + top_p: float = field( + default=0.95, + metadata={"help": "Top-p (nucleus) sampling parameter for on-policy generation."}, + ) + top_k: int = field( + default=0, + metadata={"help": "Top-k sampling parameter for on-policy generation. 0 disables top-k filtering."}, + ) + + # vLLM for student generation + use_vllm: bool = field( + default=False, + metadata={"help": "Whether to use vLLM for generating on-policy completions from the student model."}, + ) + vllm_mode: str = field( + default="colocate", + metadata={"help": 'Mode for student vLLM integration. Either "server" or "colocate".'}, + ) + vllm_server_base_url: str | None = field( + default=None, + metadata={"help": "Base URL for the student vLLM server."}, + ) + vllm_server_host: str = field( + default="0.0.0.0", + metadata={"help": "Host of the student vLLM server."}, + ) + vllm_server_port: int = field( + default=8001, + metadata={"help": "Port of the student vLLM server."}, + ) + vllm_server_timeout: float = field( + default=240.0, + metadata={"help": "Timeout for connecting to the student vLLM server."}, + ) + vllm_group_port: int = field( + default=51216, + metadata={"help": "Port for the vLLM weight-update group (NCCL communicator)."}, + ) + vllm_gpu_memory_utilization: float = field( + default=0.3, + metadata={"help": "GPU memory utilization for the colocated student vLLM engine."}, + ) + vllm_tensor_parallel_size: int = field( + default=1, + metadata={"help": "Tensor parallel size for the colocated student vLLM engine."}, + ) + vllm_max_model_length: int | None = field( + default=None, + metadata={"help": "Maximum model sequence length for the colocated vLLM engine."}, + ) + vllm_model_impl: str = field( + default="vllm", + metadata={"help": 'Model implementation backend for vLLM. Use "vllm" or "transformers".'}, + ) + vllm_structured_outputs_regex: str | None = field( + default=None, + metadata={"help": "Regex pattern for vLLM structured outputs."}, + ) + vllm_sync_frequency: int = field( + default=1, + metadata={"help": "Frequency (in training steps) to synchronize student weights to the vLLM engine."}, + ) + vllm_enable_sleep_mode: bool = field( + default=False, + metadata={"help": "Enable vLLM sleep mode to offload student weights during the optimizer step."}, + ) + + # W&B + + # Logging + log_completions: bool = field( + default=False, + metadata={ + "help": "Whether to log a sample of (prompt, completion) pairs every `log_completions_steps` steps. If `rich` is " + "installed, it prints the sample. If `wandb` and/or `trackio` logging is enabled, it logs it to `wandb` " + "and/or `trackio`." + }, + ) + log_completions_steps: int = field( + default=100, + metadata={"help": "Number of steps between logging completions."}, + ) + num_completions_to_print: int | None = field( + default=None, + metadata={"help": "Number of completions to print. If None, all completions are logged."}, + ) + + def __post_init__(self): + super().__post_init__() + + if self.lmbda < 0.0 or self.lmbda > 1.0: + raise ValueError(f"lmbda must be in [0.0, 1.0], got {self.lmbda}.") + if self.beta < 0.0 or self.beta > 1.0: + raise ValueError(f"beta must be in [0.0, 1.0], got {self.beta}.") + if self.reverse_kl_top_1_mode not in {"sampled", "argmax"}: + raise ValueError("reverse_kl_top_1_mode must be one of: 'sampled', 'argmax'") + + if self.max_length is not None and self.max_completion_length >= self.max_length: + raise ValueError( + f"max_completion_length ({self.max_completion_length}) must be smaller than " + f"max_length ({self.max_length}) to leave room for the prompt." + ) + + if self.max_prompt_length is None and self.max_length is not None: + self.max_prompt_length = self.max_length - self.max_completion_length + + if self.num_generations < 1: + raise ValueError(f"num_generations must be at least 1, got {self.num_generations}.") + + local_sequence_batch_size = self.per_device_train_batch_size * self.gradient_accumulation_steps + if self.generation_batch_size is None: + self.generation_batch_size = local_sequence_batch_size // self.num_generations + if self.generation_batch_size < 1: + raise ValueError(f"generation_batch_size must be at least 1, got {self.generation_batch_size}.") + if self.generation_batch_size * self.num_generations != local_sequence_batch_size: + raise ValueError( + "generation_batch_size * num_generations must equal per_device_train_batch_size * " + f"gradient_accumulation_steps. Got {self.generation_batch_size} * {self.num_generations} != " + f"{self.per_device_train_batch_size} * {self.gradient_accumulation_steps}." + ) + + if self.use_teacher_server and self.use_liger_kernel: + raise ValueError( + "use_liger_kernel=True is not supported with use_teacher_server=True because the Liger loss path " + "requires a local teacher model." + ) + if self.use_teacher_server and ( + self.teacher_model_server_url is None or not self.teacher_model_server_url.strip() + ): + raise ValueError("teacher_model_server_url must be set when use_teacher_server=True.") + + if self.use_teacher_server and self.beta == 0 and self.loss_top_k < 1: + raise ValueError( + f"loss_top_k must be positive when using use_teacher_server=True with beta=0 " + f"(got loss_top_k={self.loss_top_k}). The pure forward server path only has access to the " + f"teacher's top-k logprobs, so it cannot compute the exact full-vocabulary loss when loss_top_k=0." + ) + if self.use_teacher_server and self.reverse_kl_top_1_mode == "argmax": + raise ValueError( + "reverse_kl_top_1_mode='argmax' is not supported with use_teacher_server=True because the server " + "cannot provide teacher logprobs for arbitrary student-selected tokens." + ) + if self.use_teacher_server and self.beta > 0 and self.loss_top_k != 1: + raise ValueError( + f"loss_top_k must be 1 when using use_teacher_server=True with beta>0 " + f"(got loss_top_k={self.loss_top_k}). Mixed forward/reverse distillation with an external teacher " + "is only implemented for top-1 support." + ) + if self.reverse_kl_top_1_mode != "sampled" and (self.beta == 0 or self.loss_top_k != 1): + warnings.warn( + f"reverse_kl_top_1_mode='{self.reverse_kl_top_1_mode}' has no effect when beta={self.beta} " + f"and loss_top_k={self.loss_top_k}. It only applies when beta > 0 and loss_top_k == 1.", + UserWarning, + stacklevel=2, + ) + + if self.num_generations > 1 and self.lmbda < 1.0: + warnings.warn( + f"num_generations={self.num_generations} with lmbda={self.lmbda} means off-policy batches include " + f"{self.num_generations} copies of each sample. Consider lmbda=1.0 when num_generations > 1.", + UserWarning, + stacklevel=2, + ) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/distillation/distillation_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/distillation/distillation_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..283543b2764d2f7ebe190b78e3c5bd7d93aa6166 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/distillation/distillation_trainer.py @@ -0,0 +1,1748 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import random +import textwrap +import warnings +from collections import defaultdict +from collections.abc import Callable +from contextlib import nullcontext +from functools import partial +from typing import Any, Optional + +import torch +import torch.distributed as dist +import torch.nn as nn +import torch.nn.functional as F +from accelerate.utils import DistributedType, broadcast_object_list, gather_object +from datasets import Dataset +from torch.utils.data import DataLoader +from transformers import AutoTokenizer, TrainerCallback, is_trackio_available, is_wandb_available +from transformers.data.data_collator import DataCollator +from transformers.feature_extraction_utils import FeatureExtractionMixin +from transformers.generation.configuration_utils import GenerationConfig +from transformers.image_processing_utils import BaseImageProcessor +from transformers.modeling_utils import PreTrainedModel +from transformers.processing_utils import ProcessorMixin +from transformers.tokenization_utils_base import PreTrainedTokenizerBase +from transformers.trainer_utils import EvalPrediction, seed_worker +from transformers.utils import is_liger_kernel_available, is_peft_available, is_rich_available + +from ...extras.profiling import profiling_decorator +from ...generation.vllm_generation import VLLMGeneration +from ...import_utils import is_vllm_available +from ...models import prepare_deepspeed +from ...models.utils import _ForwardRedirection, unwrap_model_for_generation +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import ( + RepeatSampler, + create_model_from_path, + disable_dropout_in_model, + pad, + split_tensor_dict, +) +from .distillation_config import DistillationConfig + + +if is_peft_available(): + from peft import PeftConfig, get_peft_model + +if is_liger_kernel_available(): + from liger_kernel.chunked_loss import LigerFusedLinearJSDLoss + +if is_wandb_available(): + import wandb + +if is_trackio_available(): + import trackio + +if is_rich_available(): + from rich.console import Console + from rich.panel import Panel + from rich.table import Table + from rich.text import Text + + +def _print_completions_sample(prompts: list[str], completions: list[str], step: int, num_samples: int = None) -> None: + """Print a sample of prompt-completion pairs using rich.""" + if not is_rich_available(): + return + + console = Console() + table = Table(show_header=True, header_style="bold white", expand=True) + table.add_column("Prompt", style="bright_yellow") + table.add_column("Completion", style="bright_green") + + if num_samples is not None: + if num_samples >= len(prompts): + num_samples = None + elif num_samples <= 0: + return + + if num_samples is not None: + indices = random.sample(range(len(prompts)), num_samples) + prompts = [prompts[i] for i in indices] + completions = [completions[i] for i in indices] + + for prompt, completion in zip(prompts, completions, strict=True): + table.add_row(Text(prompt), Text(completion)) + table.add_section() + + panel = Panel(table, expand=False, title=f"Step {step}", border_style="bold white") + console.print(panel) + + +def _add_tail_bucket(log_probs, valid_mask): + """Append a (K+1)-th tail element: log(1 - sum(exp(top_k_logps))). + + This creates a proper probability distribution over K+1 elements, preventing trivial zero loss when top_k is small + (especially top_k=1). + """ + log_sum = torch.logsumexp(log_probs, dim=-1, keepdim=True) + log_sum = torch.clamp(log_sum, max=-1e-7) # ensure sum < 1 + tail = torch.log(-torch.expm1(log_sum)) # log(1 - exp(log_sum)) + tail_mask = torch.ones_like(valid_mask[..., :1], dtype=torch.bool) + return torch.cat([log_probs, tail], dim=-1), torch.cat([valid_mask, tail_mask], dim=-1) + + +def _jsd_divergence(student_log_probs, teacher_log_probs, beta, support_mask=None): + """Compute JSD (or forward/reverse KL) from log-probability tensors. + + When *support_mask* is not None, uses manual computation with masked positions zeroed. When None, uses + ``F.kl_div``. + """ + if support_mask is not None: + safe_student = torch.where(support_mask, student_log_probs, torch.zeros_like(student_log_probs)) + safe_teacher = torch.where(support_mask, teacher_log_probs, torch.zeros_like(teacher_log_probs)) + student_probs = torch.where(support_mask, student_log_probs.exp(), torch.zeros_like(student_log_probs)) + teacher_probs = torch.where(support_mask, teacher_log_probs.exp(), torch.zeros_like(teacher_log_probs)) + + if beta == 0: + return torch.nan_to_num(teacher_probs * (safe_teacher - safe_student), nan=0.0) + elif beta == 1: + return torch.nan_to_num(student_probs * (safe_student - safe_teacher), nan=0.0) + else: + beta_t = torch.tensor(beta, dtype=student_log_probs.dtype, device=student_log_probs.device) + tiny = torch.finfo(student_probs.dtype).tiny + mixture_probs = (1 - beta_t) * student_probs + beta_t * teacher_probs + safe_mixture = torch.where( + support_mask, + torch.log(mixture_probs.clamp_min(tiny)), + torch.zeros_like(student_log_probs), + ) + kl_teacher = torch.nan_to_num(teacher_probs * (safe_teacher - safe_mixture), nan=0.0) + kl_student = torch.nan_to_num(student_probs * (safe_student - safe_mixture), nan=0.0) + return beta_t * kl_teacher + (1 - beta_t) * kl_student + else: + if beta == 0: + return F.kl_div(student_log_probs, teacher_log_probs, reduction="none", log_target=True) + elif beta == 1: + return F.kl_div(teacher_log_probs, student_log_probs, reduction="none", log_target=True) + else: + beta_t = torch.tensor(beta, dtype=student_log_probs.dtype, device=student_log_probs.device) + mixture_log_probs = torch.logsumexp( + torch.stack([student_log_probs + torch.log1p(-beta_t), teacher_log_probs + torch.log(beta_t)]), + dim=0, + ) + kl_teacher = F.kl_div(mixture_log_probs, teacher_log_probs, reduction="none", log_target=True) + kl_student = F.kl_div(mixture_log_probs, student_log_probs, reduction="none", log_target=True) + return beta_t * kl_teacher + (1 - beta_t) * kl_student + + +def build_teacher_request_inputs( + input_ids: torch.Tensor, + attention_mask: torch.Tensor, + prompt_attention_mask: torch.Tensor | None = None, + labels: torch.Tensor | None = None, +) -> tuple[list[list[int]], list[int], list[int]]: + """Trim padded batch tensors into per-sample sequences for teacher-server requests.""" + + if input_ids.shape != attention_mask.shape: + raise ValueError( + f"input_ids and attention_mask must have the same shape, got {input_ids.shape} and {attention_mask.shape}." + ) + + input_ids_cpu = input_ids.detach().cpu() + attention_mask_cpu = attention_mask.detach().cpu().bool() + + if prompt_attention_mask is not None: + prompt_lengths = prompt_attention_mask.detach().cpu().sum(dim=1).to(torch.long) + else: + if labels is None: + raise ValueError("labels are required when prompt_attention_mask is not provided.") + if labels.shape != input_ids.shape: + raise ValueError(f"labels must match input_ids shape, got {labels.shape} and {input_ids.shape}.") + full_lengths = attention_mask_cpu.sum(dim=1).to(torch.long) + completion_lengths = (labels.detach().cpu() != -100).sum(dim=1).to(torch.long) + prompt_lengths = full_lengths - completion_lengths + + trimmed_input_ids: list[list[int]] = [] + prompt_lengths_list: list[int] = [] + completion_lengths_list: list[int] = [] + + for row, mask, prompt_length in zip(input_ids_cpu, attention_mask_cpu, prompt_lengths, strict=True): + trimmed_row = row[mask] + prompt_len = int(prompt_length.item()) + if prompt_len < 0 or prompt_len > trimmed_row.numel(): + raise ValueError( + f"Invalid prompt length {prompt_len} for trimmed sequence of length {trimmed_row.numel()}." + ) + trimmed_input_ids.append(trimmed_row.tolist()) + prompt_lengths_list.append(prompt_len) + completion_lengths_list.append(int(trimmed_row.numel()) - prompt_len) + + return trimmed_input_ids, prompt_lengths_list, completion_lengths_list + + +class _DistillationCollator: + """Data collator for the distillation trainer with independent prompt/completion budgets. + + Unlike ``DataCollatorForChatML``, this collator tokenizes prompts and completions separately so that long + completions can never truncate the prompt to empty. It also handles prompt-only data (no assistant completions) for + pure on-policy distillation (``lmbda=1``). + """ + + def __init__( + self, + tokenizer: "PreTrainedTokenizerBase", + max_length: int, + max_prompt_length: int, + messages_key: str = "messages", + ignore_index: int = -100, + ): + self.tokenizer = tokenizer + self.max_length = max_length + self.max_prompt_length = max_prompt_length + self.messages_key = messages_key + self.ignore_index = ignore_index + + if tokenizer.pad_token_id is None: + raise ValueError("The tokenizer does not have a pad token. Please set `pad_token_id` in the tokenizer.") + + def __call__(self, examples: list[dict[str, Any]]) -> dict[str, torch.Tensor]: + all_input_ids: list[list[int]] = [] + all_labels: list[list[int]] = [] + all_prompt_ids: list[list[int]] = [] + + for example in examples: + messages = example[self.messages_key] + + # Split: prompt = everything before the last assistant turn, completion = last assistant turn + has_completion = len(messages) > 1 and messages[-1].get("role") == "assistant" + prompt_messages = messages[:-1] if has_completion else messages + + # Tokenize prompt with its own budget using the tokenizer's truncation side + formatted_prompt = self.tokenizer.apply_chat_template( + prompt_messages, tokenize=False, add_generation_prompt=True + ) + prompt_ids = self.tokenizer( + formatted_prompt, + truncation=True, + max_length=self.max_prompt_length, + padding=False, + add_special_tokens=False, + )["input_ids"] + + if has_completion: + # Tokenize the full message (prompt + completion) without truncation first + formatted_full = self.tokenizer.apply_chat_template( + messages, tokenize=False, add_generation_prompt=False + ) + full_ids = self.tokenizer(formatted_full, truncation=False, padding=False, add_special_tokens=False)[ + "input_ids" + ] + + # Identify completion tokens: everything after the prompt in the full sequence. + # Use the un-truncated prompt length as the split point. + formatted_prompt_ids = self.tokenizer( + formatted_prompt, truncation=False, padding=False, add_special_tokens=False + )["input_ids"] + completion_ids = full_ids[len(formatted_prompt_ids) :] + + # Trim completion so prompt + completion <= max_length + max_comp = self.max_length - len(prompt_ids) + if max_comp > 0 and len(completion_ids) > max_comp: + completion_ids = completion_ids[:max_comp] + elif max_comp <= 0: + completion_ids = [] + + input_ids = prompt_ids + completion_ids + labels = [self.ignore_index] * len(prompt_ids) + list(completion_ids) + else: + # Prompt-only: no completion to train on (on-policy will generate one) + input_ids = list(prompt_ids) + labels = [self.ignore_index] * len(prompt_ids) + + all_input_ids.append(input_ids) + all_labels.append(labels) + all_prompt_ids.append(list(prompt_ids)) + + # Convert to tensors and left-pad + pad_id = self.tokenizer.pad_token_id + input_ids_t = pad( + [torch.tensor(ids, dtype=torch.long) for ids in all_input_ids], + padding_side="left", + padding_value=pad_id, + ) + attention_mask_t = pad( + [torch.ones(len(ids), dtype=torch.long) for ids in all_input_ids], + padding_side="left", + padding_value=0, + ) + labels_t = pad( + [torch.tensor(lab, dtype=torch.long) for lab in all_labels], + padding_side="left", + padding_value=self.ignore_index, + ) + prompts_t = pad( + [torch.tensor(ids, dtype=torch.long) for ids in all_prompt_ids], + padding_side="left", + padding_value=pad_id, + ) + prompt_mask_t = pad( + [torch.ones(len(ids), dtype=torch.long) for ids in all_prompt_ids], + padding_side="left", + padding_value=0, + ) + + return { + "input_ids": input_ids_t, + "attention_mask": attention_mask_t, + "labels": labels_t, + "prompts": prompts_t, + "prompt_attention_mask": prompt_mask_t, + } + + +class _RepeatBatchDataLoader: + """Repeats each collated batch ``repeat_count`` times without re-collation. + + ``RepeatSampler`` with ``repeat_count > 1`` causes the DataLoader to re-collate (re-tokenize) the same examples on + every repeat, which is wasteful. This wrapper instead keeps ``repeat_count=1`` in the sampler and repeats the + already-collated tensor dict, avoiding redundant tokenization. + """ + + def __init__(self, dataloader, repeat_count: int): + self.dataloader = dataloader + self.repeat_count = repeat_count + + def __iter__(self): + for batch in self.dataloader: + for _ in range(self.repeat_count): + yield batch + + def __len__(self): + return len(self.dataloader) * self.repeat_count + + def set_epoch(self, epoch: int): + if hasattr(self.dataloader, "set_epoch"): + self.dataloader.set_epoch(epoch) + + def __getattr__(self, attr): + return getattr(self.dataloader, attr) + + +class DistillationTrainer(_BaseTrainer): + """ + Trainer for knowledge distillation from a teacher model to a student model. + + Supports: + - Generalized JSD loss (forward KL, reverse KL, or interpolated JSD via `beta`) + - On-policy / off-policy mixing via `lmbda` (buffered across gradient accumulation) + - Local teacher model or external teacher via vLLM server + - Student on-policy generation via vLLM or model.generate() + - Liger kernel for memory-efficient fused JSD loss + """ + + _tag_names = ["trl", "distillation"] + _name = "Distillation" + _paper = { + "title": "On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes", + "id": "2306.13649", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @inproceedings{agarwal2024on-policy, + title = {{On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes}}, + author = {Rishabh Agarwal and Nino Vieillard and Yongchao Zhou and Piotr Stanczyk and Sabela Ramos Garea and Matthieu Geist and Olivier Bachem}, + year = 2024, + booktitle = {The Twelfth International Conference on Learning Representations, {ICLR} 2024, Vienna, Austria, May 7-11, 2024}, + publisher = {OpenReview.net}, + url = {https://openreview.net/forum?id=3zKtaqxLhW}, + }"""), + } + + def __init__( + self, + model: PreTrainedModel | nn.Module | str | None = None, + teacher_model: PreTrainedModel | nn.Module | str = None, + args: DistillationConfig | None = None, + data_collator: DataCollator | None = None, # type: ignore + train_dataset: Dataset | None = None, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + processing_class: PreTrainedTokenizerBase + | BaseImageProcessor + | FeatureExtractionMixin + | ProcessorMixin + | None = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + peft_config: Optional["PeftConfig"] = None, + ): + if args is None: + args = DistillationConfig(output_dir="tmp_distillation") + + # ── Student model loading ── + model_init_kwargs = args.model_init_kwargs or {} + if isinstance(model_init_kwargs, str): + import json + + model_init_kwargs = json.loads(model_init_kwargs) + teacher_model_init_kwargs = args.teacher_model_init_kwargs or {} + if isinstance(teacher_model_init_kwargs, str): + import json + + teacher_model_init_kwargs = json.loads(teacher_model_init_kwargs) + if isinstance(model, str): + model_name_or_path = model + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + model = create_model_from_path(model, **model_init_kwargs) + else: + model_name_or_path = model.config._name_or_path if model is not None else None + + # ── Processing class (tokenizer) ── + if processing_class is None and model_name_or_path is not None: + processing_class = AutoTokenizer.from_pretrained( + model_name_or_path, trust_remote_code=args.trust_remote_code + ) + if processing_class is not None: + if getattr(processing_class, "pad_token", None) is None: + processing_class.pad_token = processing_class.eos_token + + # ── PEFT ── + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + model = get_peft_model(model, peft_config) + + # ── Data collator ── + if data_collator is None: + data_collator = _DistillationCollator( + tokenizer=processing_class, + max_length=args.max_length, + max_prompt_length=args.max_prompt_length, + ) + + # ── Liger fused JSD loss ── + self.use_liger_loss = False + if args.use_liger_kernel: + self.liger_jsd_loss = LigerFusedLinearJSDLoss( + beta=args.beta, + ignore_index=-100, + temperature=args.temperature, + compiled=False, + weight_hard_loss=0.0, + weight_soft_loss=1.0, + ) + self.use_liger_loss = True + self._forward_redirection = _ForwardRedirection() + + # ── Teacher model setup ── + self.teacher_client = None + self.use_teacher_server = args.use_teacher_server + self.teacher_model_server_url = args.teacher_model_server_url + self._local_teacher_tokenizer_matches_student = True + if self.use_teacher_server: + from ...generation.vllm_client import VLLMClient + + self.teacher_client = VLLMClient(base_url=self.teacher_model_server_url, connection_timeout=60.0) + teacher_model = None + elif teacher_model is not None: + if args.teacher_model_init_kwargs is not None and not isinstance(teacher_model, str): + raise ValueError( + "You passed teacher_model_init_kwargs to the config, but your teacher_model is already " + "instantiated." + ) + + teacher_model_name_or_path = ( + teacher_model + if isinstance(teacher_model, str) + else getattr(getattr(teacher_model, "config", None), "_name_or_path", None) + ) + if teacher_model_name_or_path is None: + raise ValueError( + "DistillationTrainer requires a local teacher model with `config._name_or_path` set so its " + "tokenizer can be validated against the student tokenizer." + ) + + teacher_model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + teacher_tokenizer_kwargs = {} + teacher_revision = teacher_model_init_kwargs.get("revision", args.teacher_model_revision) + if teacher_revision is not None: + teacher_tokenizer_kwargs["revision"] = teacher_revision + teacher_tokenizer_kwargs["trust_remote_code"] = teacher_model_init_kwargs["trust_remote_code"] + teacher_processing_class = AutoTokenizer.from_pretrained( + teacher_model_name_or_path, **teacher_tokenizer_kwargs + ) + if getattr(teacher_processing_class, "pad_token", None) is None: + teacher_processing_class.pad_token = teacher_processing_class.eos_token + self._local_teacher_tokenizer_matches_student = self._local_teacher_tokenizers_match( + processing_class, teacher_processing_class + ) + if not self._local_teacher_tokenizer_matches_student: + warnings.warn( + "DistillationTrainer's built-in local-teacher loss assumes the student and teacher share the " + "same tokenizer. The loaded local teacher tokenizer does not match the student tokenizer, so " + "the teacher weights will be left unchanged for subclass overrides. Direct use of the base " + "DistillationTrainer with this local teacher remains unsupported.", + UserWarning, + stacklevel=2, + ) + + if isinstance(teacher_model, str): + dtype = teacher_model_init_kwargs.get("dtype") + teacher_model_init_kwargs["dtype"] = dtype if dtype in ["auto", None] else getattr(torch, dtype) + + if isinstance(teacher_model, str): + init_kwargs = dict(teacher_model_init_kwargs) + if args.teacher_model_revision is not None: + init_kwargs.setdefault("revision", args.teacher_model_revision) + teacher_model = create_model_from_path(teacher_model, **init_kwargs) + + # Trainer does not need to remove unused columns — the collator handles raw data + args.remove_unused_columns = False + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # ── Prepare teacher model (after super().__init__ so accelerator is ready) ── + if teacher_model is not None: + if self._local_teacher_tokenizer_matches_student: + teacher_model.resize_token_embeddings(self.model.config.get_text_config().vocab_size) + if self.is_deepspeed_enabled: + self.teacher_model = prepare_deepspeed(teacher_model, self.accelerator) + else: + self.teacher_model = self.accelerator.prepare_model(teacher_model, evaluation_mode=True) + else: + self.teacher_model = None + + if args.disable_dropout: + disable_dropout_in_model(self.model) + + # ── Store config values ── + self.lmbda = args.lmbda + self.beta = args.beta + self.temperature = args.temperature + self.top_p = args.top_p + self.num_generations = args.num_generations + self.reverse_kl_top_1_mode = args.reverse_kl_top_1_mode + self.loss_top_k = args.loss_top_k + self.loss_add_tail = args.loss_add_tail + + # ── Buffer state ── + self._buffered_inputs = None + self._buffered_on_policy_flags = None + self._buffered_text_logs = None + self._buffer_step = 0 + + # ── Loss tracking ── + self._on_policy_loss_total = 0.0 + self._off_policy_loss_total = 0.0 + self._on_policy_step_equiv = 0.0 + self._off_policy_step_equiv = 0.0 + + # ── Generation config ── + generation_kwargs = { + "max_new_tokens": args.max_completion_length, + "temperature": args.temperature, + "top_p": args.top_p, + "do_sample": True, + "top_k": args.top_k, + "pad_token_id": self.processing_class.pad_token_id, + } + self.generation_config = GenerationConfig(**generation_kwargs) + self.generation_kwargs = generation_kwargs + if ( + hasattr(self.model.generation_config, "eos_token_id") + and self.model.generation_config.eos_token_id is not None + ): + self.generation_config.eos_token_id = self.model.generation_config.eos_token_id + + # ── Metrics & Logging ── + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + self._total_train_tokens = 0 + self.log_completions = args.log_completions + self.log_completions_steps = args.log_completions_steps + self.num_completions_to_print = args.num_completions_to_print + + self._textual_logs = { + "prompt": [], + "completion": [], + } + + # ── vLLM for student generation ── + self.use_vllm = args.use_vllm + if self.use_vllm: + if not is_vllm_available(): + raise ImportError( + "vLLM is not available and use_vllm is set to True. Please install vLLM with " + "`pip install vllm` to use it." + ) + self.vllm_generation = VLLMGeneration( + model=self.model, + accelerator=self.accelerator, + processing_class=self.processing_class, + mode=args.vllm_mode, + structured_outputs_regex=args.vllm_structured_outputs_regex, + server_base_url=args.vllm_server_base_url, + server_host=args.vllm_server_host, + server_port=args.vllm_server_port, + group_port=args.vllm_group_port, + server_timeout=args.vllm_server_timeout, + tensor_parallel_size=args.vllm_tensor_parallel_size, + gpu_memory_utilization=args.vllm_gpu_memory_utilization, + max_model_length=args.vllm_max_model_length, + max_num_seqs=args.per_device_train_batch_size * args.gradient_accumulation_steps, + enable_sleep_mode=args.vllm_enable_sleep_mode, + model_impl=args.vllm_model_impl, + temperature=args.temperature, + top_p=args.top_p, + top_k=args.top_k, + max_completion_length=args.max_completion_length, + logprobs=None, + ) + self.vllm_sync_frequency = args.vllm_sync_frequency + self._last_vllm_sync_step = -1 + + @staticmethod + def _local_teacher_tokenizers_match( + student_processing_class: PreTrainedTokenizerBase, + teacher_processing_class: PreTrainedTokenizerBase, + ) -> bool: + """Check whether the student and local teacher tokenizers share the same vocabulary.""" + return student_processing_class.get_vocab() == teacher_processing_class.get_vocab() + + def _raise_if_local_teacher_tokenizer_mismatch(self) -> None: + """Guard the base local-teacher JSD path, while still allowing subclass overrides.""" + if self.teacher_model is not None and not self._local_teacher_tokenizer_matches_student: + raise ValueError( + "DistillationTrainer's built-in local-teacher loss only supports student/teacher pairs that use " + "the same tokenizer. Use a same-tokenizer local teacher, set `use_teacher_server=True`, or " + "override the local teacher loss path in a subclass." + ) + + def _compute_prompt_length(self, inputs: dict[str, torch.Tensor | Any]) -> int: + """Compute the earliest prompt boundary that still includes every completion token in the batch.""" + if inputs.get("labels") is not None: + attention_mask = inputs["attention_mask"] + labels = inputs["labels"] + full_lengths = attention_mask.sum(dim=1) + completion_lengths = (labels != -100).sum(dim=1) + return int((full_lengths - completion_lengths).min().item()) + return inputs["prompts"].shape[1] + + def _get_completion_lengths(self, generated_tokens: torch.Tensor, prompt_width: int) -> torch.Tensor: + """Infer per-sample completion lengths from generated tokens.""" + completion_tokens = generated_tokens[:, prompt_width:] + pad_token_id = self.processing_class.pad_token_id + eos_token_id = self.generation_config.eos_token_id + if eos_token_id is None: + eos_token_ids = set() + elif isinstance(eos_token_id, int): + eos_token_ids = {eos_token_id} + else: + eos_token_ids = set(eos_token_id) + pad_equals_eos = pad_token_id is not None and pad_token_id in eos_token_ids + + completion_lengths = [] + for row in completion_tokens.tolist(): + if pad_equals_eos and eos_token_ids: + completion_length = len(row) + for idx, token_id in enumerate(row): + if token_id in eos_token_ids: + completion_length = idx + 1 + break + elif pad_token_id is not None: + completion_length = len(row) + while completion_length > 0 and row[completion_length - 1] == pad_token_id: + completion_length -= 1 + else: + completion_length = len(row) + completion_lengths.append(completion_length) + + return torch.tensor(completion_lengths, device=generated_tokens.device, dtype=torch.long) + + # ────────────────────────────────────────────────────────────────────── + # Dataset / Dataloader + # ────────────────────────────────────────────────────────────────────── + + def _set_signature_columns_if_needed(self): + super()._set_signature_columns_if_needed() + extra_columns = ["prompts", "prompt_attention_mask", "messages", "chat_template_kwargs", "tools"] + if self._signature_columns is None: + self._signature_columns = extra_columns + else: + for col in extra_columns: + if col not in self._signature_columns: + self._signature_columns.append(col) + + def _get_train_sampler(self, dataset=None): + if dataset is None: + dataset = self.train_dataset + return RepeatSampler( + data_source=dataset, + mini_repeat_count=self.num_generations, + batch_size=self.args.generation_batch_size * self.accelerator.num_processes, + repeat_count=1, + shuffle=True, + seed=self.args.seed, + ) + + def get_train_dataloader(self): + """ + Override to load one generation batch per optimizer window. + + The dataloader yields batches of size `per_device_train_batch_size * gradient_accumulation_steps`. + RepeatSampler ensures each generation batch is repeated `gradient_accumulation_steps` times so the Trainer's + loop iterates the correct number of times. + """ + if self.train_dataset is None: + raise ValueError("Trainer: training requires a train_dataset.") + + train_dataset = self.train_dataset + data_collator = self.data_collator + + dataloader_params = { + "batch_size": self._train_batch_size * self.args.gradient_accumulation_steps, + "collate_fn": data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "persistent_workers": self.args.dataloader_persistent_workers, + } + + if not isinstance(train_dataset, torch.utils.data.IterableDataset): + dataloader_params["sampler"] = self._get_train_sampler() + dataloader_params["drop_last"] = self.args.dataloader_drop_last + dataloader_params["worker_init_fn"] = partial( + seed_worker, + num_workers=self.args.dataloader_num_workers, + rank=self.args.process_index, + ) + if self.args.dataloader_num_workers > 0: + dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor + + base_dataloader = self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params)) + return _RepeatBatchDataLoader(base_dataloader, repeat_count=self.args.gradient_accumulation_steps) + + # ────────────────────────────────────────────────────────────────────── + # Buffering: on/off-policy mixing across gradient accumulation steps + # ────────────────────────────────────────────────────────────────────── + + @profiling_decorator + def _prepare_inputs(self, generation_batch: dict[str, torch.Tensor | Any]) -> dict[str, torch.Tensor | Any]: + if not self.model.training: + return generation_batch + + buffer_steps = self.args.gradient_accumulation_steps + if self._buffer_step % buffer_steps == 0 or self._buffered_inputs is None: + self._fill_buffer(generation_batch, buffer_steps) + + slice_idx = self._buffer_step % buffer_steps + inputs = self._buffered_inputs[slice_idx] + self._buffer_step += 1 + return inputs + + @profiling_decorator + def _fill_buffer(self, generation_batch: dict[str, torch.Tensor | Any], buffer_steps: int): + """Split batch into slices and decide which are on-policy (student-generated) vs off-policy.""" + slices = split_tensor_dict(generation_batch, buffer_steps) + + # Decide on-policy flags (synchronized across processes) + if self.accelerator.is_main_process: + on_policy_flags = [random.random() <= self.lmbda for _ in range(buffer_steps)] + else: + on_policy_flags = [False] * buffer_steps + on_policy_flags = broadcast_object_list(on_policy_flags, from_process=0) + + self._buffered_inputs = [None] * buffer_steps + self._buffered_on_policy_flags = on_policy_flags + self._buffered_text_logs = [None] * buffer_steps + + # Store off-policy slices directly + on_policy_indices = [] + for i, is_on_policy in enumerate(on_policy_flags): + if is_on_policy: + on_policy_indices.append(i) + else: + self._buffered_inputs[i] = slices[i] + + # Generate student completions for on-policy slices + if on_policy_indices: + self._generate_student_completions(slices, on_policy_indices) + + # Gather on-policy text logs once per optimizer step (all processes must participate) + if self.log_completions: + on_policy_prompts = [] + on_policy_completions = [] + for i in on_policy_indices: + if self._buffered_text_logs[i] is not None: + prompts, completions = self._buffered_text_logs[i] + on_policy_prompts.extend(prompts) + on_policy_completions.extend(completions) + self._textual_logs["prompt"].extend(gather_object(on_policy_prompts)) + self._textual_logs["completion"].extend(gather_object(on_policy_completions)) + + @profiling_decorator + def _generate_student_completions(self, slices: list[dict[str, torch.Tensor | Any]], on_policy_indices: list[int]): + """Generate completions from the student model for on-policy training.""" + if not self.use_vllm: + self._generate_with_model(slices, on_policy_indices) + return + + # Collect all prompts across on-policy slices, stripping left-padding so vLLM + # receives only real prompt token IDs (like GRPO trainer). + local_prompts = [] + local_slice_indices = [] + pad_token_id = self.processing_class.pad_token_id + for slice_idx in on_policy_indices: + prompt_mask = slices[slice_idx].get("prompt_attention_mask") + for i, prompt in enumerate(slices[slice_idx]["prompts"]): + if prompt_mask is not None: + prompt = prompt[prompt_mask[i].bool()] + elif pad_token_id is not None: + first_non_pad = (prompt != pad_token_id).nonzero(as_tuple=True)[0] + if len(first_non_pad) > 0: + prompt = prompt[first_non_pad[0] :] + local_prompts.append(prompt) + local_slice_indices.append(slice_idx) + + # Sync student weights to vLLM if needed + if ( + self.state.global_step != self._last_vllm_sync_step + and self.state.global_step % self.vllm_sync_frequency == 0 + ): + self.vllm_generation.sync_weights() + self._last_vllm_sync_step = self.state.global_step + + # Generate completions — pass token IDs directly, no text decoding + prompt_ids_list = [p.tolist() for p in local_prompts] + _, completion_ids, _, _ = self.vllm_generation.generate( + prompts=prompt_ids_list, images=None, num_generations=self.num_generations + ) + + # Process completions into the buffer + self._store_completions_in_buffer( + slices, on_policy_indices, local_slice_indices, local_prompts, completion_ids + ) + + def _generate_with_model(self, slices: list[dict[str, torch.Tensor | Any]], on_policy_indices: list[int]): + """Fallback generation using model.generate() (no vLLM).""" + with unwrap_model_for_generation( + self.model, self.accelerator, generation_kwargs=self.generation_kwargs + ) as unwrapped_model: + for slice_idx in on_policy_indices: + slice_inputs = slices[slice_idx] + generated_outputs = unwrapped_model.generate( + input_ids=slice_inputs["prompts"], + attention_mask=slice_inputs.get("prompt_attention_mask", None), + generation_config=self.generation_config, + return_dict_in_generate=True, + ) + generated_tokens = generated_outputs.sequences + batch_size = generated_tokens.size(0) + device = generated_tokens.device + pad_token_id = self.processing_class.pad_token_id + prompt_width = slice_inputs["prompts"].shape[1] + prompt_mask = slice_inputs.get("prompt_attention_mask") + if prompt_mask is not None: + prompt_token_lengths = prompt_mask.sum(dim=1) + else: + prompt_token_lengths = torch.full((batch_size,), prompt_width, dtype=torch.long, device=device) + completion_lengths = self._get_completion_lengths(generated_tokens, prompt_width) + new_attention_mask, new_labels = self._build_sequence_batch( + generated_tokens, prompt_width, prompt_token_lengths, completion_lengths + ) + + # Decode for logging + prompt_texts = [] + completion_texts = [] + for idx in range(batch_size): + prompt_tokens = slice_inputs["prompts"][idx] + if prompt_mask is not None: + prompt_tokens = prompt_tokens[prompt_mask[idx].bool()] + elif pad_token_id is not None: + prompt_tokens = prompt_tokens[prompt_tokens != pad_token_id] + prompt_texts.append( + self.processing_class.decode(prompt_tokens.tolist(), skip_special_tokens=False) + ) + length = prompt_width + completion_length = int(completion_lengths[idx].item()) + completion_texts.append( + self.processing_class.decode( + generated_tokens[idx, length : length + completion_length].tolist(), + skip_special_tokens=False, + ) + ) + + updated = dict(slice_inputs) + updated["input_ids"] = generated_tokens + updated["attention_mask"] = new_attention_mask + updated["labels"] = new_labels + + self._buffered_inputs[slice_idx] = updated + self._buffered_text_logs[slice_idx] = (prompt_texts, completion_texts) + + def _store_completions_in_buffer( + self, + slices: list[dict[str, torch.Tensor | Any]], + on_policy_indices: list[int], + local_slice_indices: list[int], + local_prompts: list[torch.Tensor], + completion_ids: list, + ): + """Process vLLM completions and store them in the buffer. + + Uses original prompt token IDs directly (no decode/re-encode roundtrip), following the same approach as + GRPOTrainer. + """ + device = self.accelerator.device + pad_token_id = self.processing_class.pad_token_id if self.processing_class.pad_token_id is not None else 0 + max_completion_length = self.generation_config.max_new_tokens + + # Group completions and prompt token IDs by slice + slice_completions = {idx: [] for idx in on_policy_indices} + slice_prompt_ids = {idx: [] for idx in on_policy_indices} + for i, slice_idx in enumerate(local_slice_indices): + slice_completions[slice_idx].append(completion_ids[i]) + slice_prompt_ids[slice_idx].append(local_prompts[i]) + + for slice_idx in on_policy_indices: + slice_inputs = slices[slice_idx] + prompt_id_tensors = slice_prompt_ids[slice_idx] + prompt_width = max(len(p) for p in prompt_id_tensors) + prompt_token_lengths = torch.tensor([len(p) for p in prompt_id_tensors], device=device, dtype=torch.long) + prompt_attention_mask = ( + torch.arange(prompt_width, device=device).unsqueeze(0) + >= (prompt_width - prompt_token_lengths).unsqueeze(1) + ).long() + + # Left-pad prompt token IDs to the longest prompt in this slice + prompt_ids = torch.stack( + [F.pad(p, (prompt_width - len(p), 0), value=pad_token_id) for p in prompt_id_tensors] + ).to(device) + + # Pad/truncate completions (right-pad to max_completion_length) + completion_tensors = [] + completion_ids_for_text = [] + completion_lengths = [] + for comp_ids in slice_completions[slice_idx]: + t = torch.tensor(comp_ids, device=device) + if len(t) > max_completion_length: + t = t[:max_completion_length] + completion_ids_for_text.append(t.tolist()) + completion_lengths.append(len(t)) + if len(t) < max_completion_length: + padding = torch.full((max_completion_length - len(t),), pad_token_id, device=device, dtype=t.dtype) + t = torch.cat([t, padding]) + completion_tensors.append(t) + + completion_ids_padded = torch.stack(completion_tensors) + new_input_ids = torch.cat([prompt_ids, completion_ids_padded], dim=1) + completion_lengths = torch.tensor(completion_lengths, device=device, dtype=torch.long) + new_attention_mask, new_labels = self._build_sequence_batch( + new_input_ids, prompt_width, prompt_token_lengths, completion_lengths + ) + + # Decode for logging only + prompt_texts = self.processing_class.batch_decode( + prompt_id_tensors, skip_special_tokens=False, clean_up_tokenization_spaces=False + ) + completion_texts = self.processing_class.batch_decode( + completion_ids_for_text, skip_special_tokens=False, clean_up_tokenization_spaces=False + ) + + updated = dict(slice_inputs) + updated["input_ids"] = new_input_ids + updated["attention_mask"] = new_attention_mask + updated["labels"] = new_labels + # Update prompts to match the new padding width so prompt_length is consistent + updated["prompts"] = prompt_ids + updated["prompt_attention_mask"] = prompt_attention_mask + + self._buffered_inputs[slice_idx] = updated + self._buffered_text_logs[slice_idx] = (prompt_texts, completion_texts) + + @staticmethod + def _build_sequence_batch( + new_input_ids: torch.Tensor, + prompt_width: int, + prompt_token_lengths: torch.Tensor, + completion_lengths: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Build attention mask and labels from prompt/completion lengths.""" + prompt_token_lengths = prompt_token_lengths.to(device=new_input_ids.device, dtype=torch.long) + completion_lengths = completion_lengths.to(device=new_input_ids.device, dtype=torch.long) + positions = torch.arange(new_input_ids.shape[1], device=new_input_ids.device).unsqueeze(0) + prompt_mask = (positions < prompt_width) & (positions >= (prompt_width - prompt_token_lengths).unsqueeze(1)) + completion_mask = (positions >= prompt_width) & (positions < (prompt_width + completion_lengths).unsqueeze(1)) + new_attention_mask = (prompt_mask | completion_mask).long() + + new_labels = torch.full_like(new_input_ids, -100) + new_labels[completion_mask] = new_input_ids[completion_mask] + + return new_attention_mask, new_labels + + # ────────────────────────────────────────────────────────────────────── + # Loss computation + # ────────────────────────────────────────────────────────────────────── + + @staticmethod + def _reduce_divergence_loss(jsd, labels=None, reduction="batchmean", num_items_in_batch=None): + """Reduce a per-token divergence tensor using the trainer's label mask semantics. + + When `num_items_in_batch` is provided (as under gradient accumulation), the divergence is reduced as `sum / + num_items_in_batch`, matching the gradient-accumulation-correct behavior of HF's default cross-entropy. + Otherwise it falls back to the local `reduction` (default `batchmean`). See issue #4719. + """ + mask = None + if labels is not None: + mask = labels != -100 + jsd = jsd[mask] + + if num_items_in_batch is not None: + # Normalize by the global number of valid tokens for gradient-accumulation-correct loss. + jsd_sum = jsd.sum() + if isinstance(num_items_in_batch, torch.Tensor): + num_items_in_batch = num_items_in_batch.to(jsd_sum.device) + return jsd_sum / num_items_in_batch + if reduction == "batchmean": + # clamp_min(1) avoids 0/0 -> nan when a sample has no unmasked positions + # (e.g. completion fully truncated). jsd[mask] is empty -> jsd.sum() == 0, + # so 0/1 == 0 with a valid grad path. + denom = mask.sum().clamp_min(1) if labels is not None else max(jsd.size(0), 1) + return jsd.sum() / denom + elif reduction == "sum": + return jsd.sum() + elif reduction == "mean": + return jsd.mean() + else: + return jsd + + @staticmethod + def generalized_jsd_loss( + student_logits, + teacher_logits, + labels=None, + beta=0.5, + temperature=1.0, + reduction="batchmean", + top_k=0, + add_tail=True, + num_items_in_batch=None, + ): + """ + Compute the generalized Jensen-Shannon Divergence loss for knowledge distillation. + + Args: + student_logits: Tensor of shape (batch_size, sequence_length, vocab_size). + teacher_logits: Tensor of shape (batch_size, sequence_length, vocab_size). + labels: Tensor of shape (batch_size, sequence_length) with -100 for positions to ignore. + beta: Interpolation coefficient. 0.0 = forward KL, 1.0 = reverse KL. + temperature: Softmax temperature. + reduction: 'batchmean', 'sum', 'mean', or 'none'. + top_k: Number of top tokens to restrict the loss to. The support set depends on beta: + beta=0 (forward KL) uses teacher's top-k, beta=1 (reverse KL) uses student's top-k, 0 0 and student_logits.size(-1) > top_k: + neg_inf = torch.full((), float("-inf"), dtype=student_logits.dtype, device=student_logits.device) + student_log_probs_full = F.log_softmax(student_logits, dim=-1) + teacher_log_probs_full = F.log_softmax(teacher_logits, dim=-1) + + if beta == 0: + # Forward KL: teacher-selected support + _, support = teacher_logits.topk(top_k, dim=-1) + support_mask = torch.ones_like(support, dtype=torch.bool) + elif beta == 1: + # Reverse KL: student-selected support + _, support = student_logits.topk(top_k, dim=-1) + support_mask = torch.ones_like(support, dtype=torch.bool) + else: + # JSD: union of both supports (concatenate + deduplicate) + _, student_top = student_logits.topk(top_k, dim=-1) + _, teacher_top = teacher_logits.topk(top_k, dim=-1) + support = torch.cat([teacher_top, student_top], dim=-1) + support_mask = torch.ones(support.shape, dtype=torch.bool, device=support.device) + for i in range(1, support.shape[-1]): + prev_matches = support[..., i : i + 1] == support[..., :i] + prev_valid = support_mask[..., :i] + support_mask[..., i] &= ~(prev_matches & prev_valid).any(dim=-1) + support = torch.where(support_mask, support, torch.zeros_like(support)) + + student_support_logps = student_log_probs_full.gather(-1, support) + teacher_support_logps = teacher_log_probs_full.gather(-1, support) + + # Mask invalid (duplicate) positions with -inf + student_topk_logps = torch.where(support_mask, student_support_logps, neg_inf) + teacher_topk_logps = torch.where(support_mask, teacher_support_logps, neg_inf) + + if add_tail: + # Add tail bucket: append log(1 - sum(exp(top_k_logps))) to preserve + # the remaining probability mass outside the top-k. This prevents trivial + # zero loss when top_k is small (especially top_k=1). + base_support_mask = support_mask + student_log_probs, support_mask = _add_tail_bucket(student_topk_logps, base_support_mask) + teacher_log_probs, _ = _add_tail_bucket(teacher_topk_logps, base_support_mask) + else: + student_log_probs = student_topk_logps - torch.logsumexp(student_topk_logps, dim=-1, keepdim=True) + teacher_log_probs = teacher_topk_logps - torch.logsumexp(teacher_topk_logps, dim=-1, keepdim=True) + else: + student_log_probs = F.log_softmax(student_logits, dim=-1) + teacher_log_probs = F.log_softmax(teacher_logits, dim=-1) + + jsd = _jsd_divergence(student_log_probs, teacher_log_probs, beta, support_mask) + return DistillationTrainer._reduce_divergence_loss( + jsd, labels=labels, reduction=reduction, num_items_in_batch=num_items_in_batch + ) + + def _get_reverse_kl_top_1_tokens( + self, student_scores: torch.Tensor, completion_tokens: torch.Tensor + ) -> torch.Tensor: + """Return the reverse-KL top-1 token IDs for the mixed top-1 loss path. + + Args: + student_scores: Any (B, T, V) tensor whose argmax selects the student's top token + (logits or log-probs — both are order-preserving). + completion_tokens: (B, T) actual token IDs in the completion. + """ + if self.reverse_kl_top_1_mode == "argmax": + return student_scores.argmax(dim=-1) + return completion_tokens + + def _compute_sparse_top_1_divergence_loss( + self, + student_log_probs: torch.Tensor, + teacher_top1_token_ids: torch.Tensor, + teacher_top1_logprobs: torch.Tensor, + reverse_token_ids: torch.Tensor, + reverse_teacher_logprobs: torch.Tensor, + labels: torch.Tensor, + num_items_in_batch=None, + ) -> torch.Tensor: + """Compute exact generalized JSD/KL on top-1 support for the mixed beta>0 path.""" + neg_inf = torch.full((), float("-inf"), dtype=student_log_probs.dtype, device=student_log_probs.device) + + if self.beta == 1: + support = reverse_token_ids.unsqueeze(-1) + support_mask = torch.ones_like(support, dtype=torch.bool) + teacher_support_logprobs = reverse_teacher_logprobs.unsqueeze(-1) + else: + teacher_support = teacher_top1_token_ids.unsqueeze(-1) + reverse_support = reverse_token_ids.unsqueeze(-1) + support = torch.cat([teacher_support, reverse_support], dim=-1) + support_mask = torch.ones_like(support, dtype=torch.bool) + support_mask[..., 1] = support[..., 1] != support[..., 0] + teacher_support_logprobs = torch.stack([teacher_top1_logprobs, reverse_teacher_logprobs], dim=-1) + support = torch.where(support_mask, support, torch.zeros_like(support)) + + student_support_logprobs = student_log_probs.gather(-1, support) + student_support_logprobs = torch.where(support_mask, student_support_logprobs, neg_inf) + teacher_support_logprobs = torch.where(support_mask, teacher_support_logprobs, neg_inf) + + if self.loss_add_tail: + base_support_mask = support_mask + student_sparse_log_probs, support_mask = _add_tail_bucket(student_support_logprobs, base_support_mask) + teacher_sparse_log_probs, _ = _add_tail_bucket(teacher_support_logprobs, base_support_mask) + else: + student_sparse_log_probs = student_support_logprobs - torch.logsumexp( + student_support_logprobs, dim=-1, keepdim=True + ) + teacher_sparse_log_probs = teacher_support_logprobs - torch.logsumexp( + teacher_support_logprobs, dim=-1, keepdim=True + ) + + jsd = _jsd_divergence(student_sparse_log_probs, teacher_sparse_log_probs, self.beta, support_mask) + return self._reduce_divergence_loss( + jsd, labels=labels, reduction="batchmean", num_items_in_batch=num_items_in_batch + ) + + def _compute_local_sparse_top_1_divergence_loss( + self, + student_logits: torch.Tensor, + teacher_logits: torch.Tensor, + completion_tokens: torch.Tensor, + labels: torch.Tensor, + num_items_in_batch=None, + ) -> torch.Tensor: + """Compute the mixed top-1 loss for a local teacher using gathered full-logit probabilities.""" + student_log_probs = F.log_softmax(student_logits / self.temperature, dim=-1) + teacher_log_probs = F.log_softmax(teacher_logits / self.temperature, dim=-1) + + teacher_top1_token_ids = teacher_logits.argmax(dim=-1) + teacher_top1_logprobs = teacher_log_probs.gather(dim=-1, index=teacher_top1_token_ids.unsqueeze(-1)).squeeze( + -1 + ) + reverse_token_ids = self._get_reverse_kl_top_1_tokens(student_logits, completion_tokens) + reverse_teacher_logprobs = teacher_log_probs.gather(dim=-1, index=reverse_token_ids.unsqueeze(-1)).squeeze(-1) + + return self._compute_sparse_top_1_divergence_loss( + student_log_probs=student_log_probs, + teacher_top1_token_ids=teacher_top1_token_ids, + teacher_top1_logprobs=teacher_top1_logprobs, + reverse_token_ids=reverse_token_ids, + reverse_teacher_logprobs=reverse_teacher_logprobs, + labels=labels, + num_items_in_batch=num_items_in_batch, + ) + + def _get_teacher_logits(self, inputs: dict[str, torch.Tensor | Any]) -> torch.Tensor: + """Get teacher logits — dispatches between local model and external server.""" + if self.teacher_model is not None: + self.teacher_model.eval() + with torch.no_grad(): + return self.teacher_model( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + ).logits + elif self.use_teacher_server: + raise NotImplementedError( + "Fetching full teacher logits with use_teacher_server=True is not supported. " + "Server-backed distillation only supports per-token logprobs via " + "`_get_teacher_token_logprobs_from_server`." + ) + else: + raise ValueError("No teacher model or teacher server configured.") + + def _get_teacher_token_logprobs_from_server( + self, + inputs: dict[str, torch.Tensor | Any], + aligned_prompt_length: int, + ) -> dict[str, torch.Tensor]: + """Fetch per-token teacher logprobs from an external vLLM server. + + Returns a dict with: + ``actual_logprobs`` – (batch, completion_length) teacher log-prob for the actual + token at each position (for reverse KL). + ``topk_logprobs`` – (batch, completion_length, K) teacher top-k sorted logprobs + (for forward KL). + ``topk_token_ids`` – (batch, completion_length, K) corresponding token IDs. + """ + import numpy as np + + input_ids = inputs["input_ids"] + batch_size = input_ids.shape[0] + sequences, prompt_lengths, completion_lengths = build_teacher_request_inputs( + input_ids, + inputs["attention_mask"], + prompt_attention_mask=inputs.get("prompt_attention_mask"), + labels=inputs.get("labels"), + ) + + # The pure forward server path can use the requested teacher top-k support. + # When beta > 0, config validation restricts the server-backed path to top-1. + requested_top_k = self.loss_top_k + result = self.teacher_client.get_sequence_logprobs( + sequences=sequences, + prompt_lengths=prompt_lengths, + top_logprobs=requested_top_k, + temperature=self.temperature, + ) + K = requested_top_k + + device = input_ids.device + labels = inputs.get("labels") + if labels is None: + raise ValueError("labels are required to align teacher-server logprobs with the student loss tensors.") + + # The student loss slices tensors in padded-sequence coordinates starting at `aligned_prompt_length`. + # Place each teacher completion into that same coordinate system by locating the first non-masked completion + # token in `labels`. This works for both left-padded off-policy batches and on-policy batches where + # completions are right-padded after a fixed-width prompt block. + completion_offsets = [] + label_mask = labels != -100 + for sample_mask, comp_len in zip(label_mask, completion_lengths, strict=True): + if comp_len == 0: + completion_offsets.append(0) + continue + completion_start = int(torch.nonzero(sample_mask, as_tuple=False)[0].item()) + completion_offsets.append(completion_start - aligned_prompt_length) + + # Size the output tensors to tightly fit the teacher logprobs. Using the full padded + # sequence length would include padding positions with -inf teacher logprobs, producing + # +inf in the forward pass and NaN gradients in the backward pass (0 * inf = NaN). + # Shorter samples in variable-length batches still need the -inf sentinel at the tail; + # downstream loss consumers (_compute_server_sparse_top_1_divergence_loss, + # _compute_server_forward_kl_loss) neutralise those positions before the divergence + # math runs. + completion_length = max( + (offset + len(lps) for offset, lps in zip(completion_offsets, result["logprobs"], strict=True)), + default=0, + ) + + # actual_logprobs: (B, T) — teacher logprob for the actual token + def _actual_to_tensor(key): + arr = np.full((batch_size, completion_length), float("-inf"), dtype=np.float32) + for i, (offset, seq_lps) in enumerate(zip(completion_offsets, result[key], strict=True)): + if seq_lps: + vals = np.array(seq_lps, dtype=np.float32) # (comp_len_i, 1) + arr[i, offset : offset + vals.shape[0]] = vals[:, 0] + return torch.from_numpy(arr).to(device) + + # topk: (B, T, K) + def _topk_to_tensor(key, k, np_dtype, fill): + arr = np.full((batch_size, completion_length, k), fill, dtype=np_dtype) + for i, (offset, seq_vals) in enumerate(zip(completion_offsets, result[key], strict=True)): + if seq_vals: + vals = np.array(seq_vals, dtype=np_dtype) # (comp_len_i, k) + arr[i, offset : offset + vals.shape[0], :] = vals + return torch.from_numpy(arr).to(device) + + return { + "actual_logprobs": _actual_to_tensor("actual_logprobs"), + "topk_logprobs": _topk_to_tensor("logprobs", K, np.float32, float("-inf")), + "topk_token_ids": _topk_to_tensor("logprob_token_ids", K, np.int64, 0), + } + + def _compute_server_sparse_top_1_divergence_loss( + self, + teacher_result: dict[str, torch.Tensor], + student_log_probs: torch.Tensor, + completion_tokens: torch.Tensor, + labels: torch.Tensor, + ) -> torch.Tensor: + """Compute exact sparse top-1 generalized JSD/KL from server-provided teacher logprobs. + + Args: + teacher_result: dict with ``actual_logprobs`` (B, T), ``topk_logprobs`` (B, T, K), + ``topk_token_ids`` (B, T, K). + student_log_probs: (B, T, V) student log-softmax over vocabulary. + completion_tokens: (B, T) actual token IDs in the completion. + labels: (B, T) with -100 for positions to ignore. + """ + topk_teacher_lps = teacher_result["topk_logprobs"] # (B, T, 1) + topk_token_ids = teacher_result["topk_token_ids"] # (B, T, 1) + actual_teacher_lps = teacher_result["actual_logprobs"] # (B, T) + required = labels != -100 + + missing_actual = required & ~torch.isfinite(actual_teacher_lps) + if missing_actual.any(): + missing_count = int(missing_actual.sum().item()) + total_required = int(required.sum().item()) + raise ValueError( + "Teacher server is missing actual-token logprobs for required reverse-KL positions: " + f"{missing_count}/{total_required}." + ) + if self.beta < 1: + teacher_top1_logprobs = topk_teacher_lps.squeeze(-1) + missing_top1 = required & ~torch.isfinite(teacher_top1_logprobs) + if missing_top1.any(): + missing_count = int(missing_top1.sum().item()) + total_required = int(required.sum().item()) + raise ValueError( + "Teacher server is missing top-1 logprobs for required forward-KL positions: " + f"{missing_count}/{total_required}." + ) + + # Replace -inf teacher logprobs at intra-batch padding (labels == -100) with 0 so + # reverse-KL's student_probs·(log_s - log_t) does not leak +inf into the backward pass. + pad_mask_2d = ~required + pad_mask_3d = pad_mask_2d.unsqueeze(-1) + topk_teacher_lps = torch.where(pad_mask_3d, 0.0, topk_teacher_lps) + actual_teacher_lps = torch.where(pad_mask_2d, 0.0, actual_teacher_lps) + + # Server path only supports "sampled" mode — config validation enforces this, but we guard + # explicitly so future relaxations of the config check don't silently change behaviour. + reverse_token_ids = self._get_reverse_kl_top_1_tokens(student_log_probs, completion_tokens) + # The server path normalizes locally (batchmean), not by num_items_in_batch: teacher logprobs may not cover + # every student completion token (the loss is summed over the trimmed teacher window), so the global token + # count would be the wrong denominator. Gradient-accumulation normalization for the server path is left as a + # follow-up. + return self._compute_sparse_top_1_divergence_loss( + student_log_probs=student_log_probs, + teacher_top1_token_ids=topk_token_ids.squeeze(-1), + teacher_top1_logprobs=topk_teacher_lps.squeeze(-1), + reverse_token_ids=reverse_token_ids, + reverse_teacher_logprobs=actual_teacher_lps, + labels=labels, + ) + + def _compute_server_forward_kl_loss( + self, + teacher_result: dict[str, torch.Tensor], + student_log_probs: torch.Tensor, + labels: torch.Tensor, + ) -> torch.Tensor: + """Compute sparse forward KL from server-provided teacher top-k logprobs (beta==0 path). + + Args: + teacher_result: dict with ``topk_logprobs`` (B, T, K) and ``topk_token_ids`` (B, T, K). + student_log_probs: (B, T, V) student log-softmax over vocabulary. + labels: (B, T) with -100 for positions to ignore. + """ + teacher_topk_logprobs = teacher_result["topk_logprobs"] + teacher_topk_token_ids = teacher_result["topk_token_ids"] + valid = teacher_topk_logprobs > float("-inf") + neg_inf = torch.full((), float("-inf"), dtype=student_log_probs.dtype, device=student_log_probs.device) + student_topk_logprobs = student_log_probs.gather(dim=-1, index=teacher_topk_token_ids) + student_topk_logprobs = torch.where(valid, student_topk_logprobs, neg_inf) + teacher_topk_logprobs = torch.where(valid, teacher_topk_logprobs, neg_inf) + + if self.loss_add_tail: + base_support_mask = valid + student_sparse_log_probs, support_mask = _add_tail_bucket(student_topk_logprobs, base_support_mask) + teacher_sparse_log_probs, _ = _add_tail_bucket(teacher_topk_logprobs, base_support_mask) + else: + support_mask = valid + student_sparse_log_probs = student_topk_logprobs - torch.logsumexp( + student_topk_logprobs, dim=-1, keepdim=True + ) + teacher_sparse_log_probs = teacher_topk_logprobs - torch.logsumexp( + teacher_topk_logprobs, dim=-1, keepdim=True + ) + + jsd = _jsd_divergence( + student_sparse_log_probs, + teacher_sparse_log_probs, + beta=0.0, + support_mask=support_mask, + ) + # See `_compute_server_sparse_top_1_divergence_loss`: the server path normalizes locally, not by + # num_items_in_batch, because the teacher window may not cover every student completion token. + return self._reduce_divergence_loss(jsd, labels=labels, reduction="batchmean") + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + self._raise_if_local_teacher_tokenizer_mismatch() + + if self.use_liger_loss: + loss = self._compute_liger_loss(model, inputs, num_items_in_batch=num_items_in_batch) + return (loss, None) if return_outputs else loss + + # Student forward pass + student_outputs = model( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + ) + prompt_length = self._compute_prompt_length(inputs) + labels = inputs["labels"][:, prompt_length:] + completion_tokens = inputs["input_ids"][:, prompt_length:] + + if self.use_teacher_server: + # Server path: token-level divergence using teacher logprobs. + # The server returns: + # actual_logprobs – (B, T) teacher log p(x_actual) (for reverse KL) + # topk_logprobs – (B, T, K) teacher top-k sorted logprobs (for forward KL) + # topk_token_ids – (B, T, K) corresponding token IDs + teacher_result = self._get_teacher_token_logprobs_from_server(inputs, prompt_length) + + student_logits = student_outputs.logits[:, prompt_length - 1 : -1, :] + student_log_probs = F.log_softmax(student_logits / self.temperature, dim=-1) + + comp_len = teacher_result["actual_logprobs"].shape[1] + completion_tokens = completion_tokens[:, :comp_len] + trimmed_labels = labels[:, :comp_len] + + if self.beta > 0: + loss = self._compute_server_sparse_top_1_divergence_loss( + teacher_result=teacher_result, + student_log_probs=student_log_probs[:, :comp_len, :], + completion_tokens=completion_tokens, + labels=trimmed_labels, + ) + else: + loss = self._compute_server_forward_kl_loss( + teacher_result=teacher_result, + student_log_probs=student_log_probs[:, :comp_len, :], + labels=trimmed_labels, + ) + else: + # Local teacher: exact full-vocabulary loss except for the shared mixed top-1 path. + teacher_logits = self._get_teacher_logits(inputs) + student_logits = student_outputs.logits[:, prompt_length - 1 : -1, :] + teacher_logits = teacher_logits[:, prompt_length - 1 : -1, :] + if self.beta > 0 and self.loss_top_k == 1: + loss = self._compute_local_sparse_top_1_divergence_loss( + student_logits=student_logits, + teacher_logits=teacher_logits, + completion_tokens=completion_tokens, + labels=labels, + num_items_in_batch=num_items_in_batch, + ) + else: + loss = self.generalized_jsd_loss( + student_logits=student_logits, + teacher_logits=teacher_logits, + labels=labels, + beta=self.beta, + temperature=self.temperature, + top_k=self.loss_top_k, + add_tail=self.loss_add_tail, + num_items_in_batch=num_items_in_batch, + ) + + return (loss, student_outputs) if return_outputs else loss + + def _liger_student_forward(self, student, inputs): + """Decoder-only forward used by the Liger JSD path (skips lm_head to save memory).""" + if hasattr(student, "get_decoder") and student.get_decoder() is not None: + decoder = student.get_decoder() + else: + decoder = getattr(student, getattr(student, "base_model_prefix", "model"), student) + return decoder( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + use_cache=False, + ) + + def _compute_liger_loss(self, model, inputs, num_items_in_batch=None): + """Memory-efficient JSD using Liger kernel (operates on hidden states, not full logits).""" + # Route through the DDP/FSDP wrapper via _forward_redirection so that + # DDP.forward() is called and prepare_for_backward() fires correctly. + unwrapped_student = self.accelerator.unwrap_model(model) + student_outputs = self._forward_redirection( + model, unwrapped_student, self._liger_student_forward, unwrapped_student, inputs + ) + + self.teacher_model.eval() + unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model) + if hasattr(unwrapped_teacher, "get_decoder") and unwrapped_teacher.get_decoder() is not None: + base_teacher = unwrapped_teacher.get_decoder() + else: + base_teacher = getattr( + unwrapped_teacher, getattr(unwrapped_teacher, "base_model_prefix", "model"), unwrapped_teacher + ) + with torch.no_grad(): + teacher_outputs = base_teacher( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + use_cache=False, + ) + + student_hidden = student_outputs.last_hidden_state[:, :-1] + teacher_hidden = teacher_outputs.last_hidden_state[:, :-1] + del student_outputs, teacher_outputs + + student_hidden = student_hidden.reshape(-1, student_hidden.shape[-1]) + teacher_hidden = teacher_hidden.reshape(-1, teacher_hidden.shape[-1]) + + labels_mask = inputs["labels"] != -100 + masked_input_ids = torch.where(labels_mask, inputs["input_ids"], torch.full_like(inputs["input_ids"], -100)) + true_labels = masked_input_ids[:, 1:].reshape(-1) + + student_head = unwrapped_student.get_output_embeddings() + teacher_head = unwrapped_teacher.get_output_embeddings() + + loss = self.liger_jsd_loss( + student_input=student_hidden, + student_weight=student_head.weight, + teacher_input=teacher_hidden, + teacher_weight=teacher_head.weight, + true_labels=true_labels, + student_bias=getattr(student_head, "bias", None), + teacher_bias=getattr(teacher_head, "bias", None), + ) + + # The Liger JSD loss normalizes by the local number of valid tokens. Under gradient accumulation we want + # the global normalization, so rescale by `num_valid_local / num_items_in_batch`. + if num_items_in_batch is not None: + num_valid_local = (true_labels != -100).sum().clamp_min(1) + if isinstance(num_items_in_batch, torch.Tensor): + num_items_in_batch = num_items_in_batch.to(loss.device) + loss = loss * num_valid_local / num_items_in_batch + + del student_hidden, teacher_hidden, true_labels + return loss + + def _get_liger_zero3_lm_head_gather_ctx(self, model: nn.Module): + """Context manager for gathering lm_head parameters under Liger + ZeRO-3.""" + if not self.use_liger_loss: + return nullcontext() + + deepspeed_plugin = self.accelerator.state.deepspeed_plugin + if deepspeed_plugin is None or deepspeed_plugin.zero_stage != 3: + return nullcontext() + + import deepspeed + + unwrapped_student = self.accelerator.unwrap_model(model) + unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model) + student_head = unwrapped_student.get_output_embeddings() + teacher_head = unwrapped_teacher.get_output_embeddings() + params = [student_head.weight, teacher_head.weight] + if student_head.bias is not None: + params.append(student_head.bias) + if teacher_head.bias is not None: + params.append(teacher_head.bias) + return deepspeed.zero.GatheredParameters(params, modifier_rank=None) + + # ────────────────────────────────────────────────────────────────────── + # Training step & Logging + # ────────────────────────────────────────────────────────────────────── + + @profiling_decorator + def training_step( + self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None + ) -> torch.Tensor: + """Training step with on/off-policy loss tracking and completion stats.""" + buffer_steps = self.args.gradient_accumulation_steps + + with self._get_liger_zero3_lm_head_gather_ctx(model): + loss = super().training_step(model, inputs, num_items_in_batch) + + slice_idx = (self._buffer_step - 1) % buffer_steps + + # Determine if this slice is on-policy + is_on_policy = False + if self._buffered_on_policy_flags is not None and slice_idx < len(self._buffered_on_policy_flags): + is_on_policy = self._buffered_on_policy_flags[slice_idx] + + # Track completion length stats — read from buffered inputs (which reflect on-policy generation) + actual_inputs = self._buffered_inputs[slice_idx] if self._buffered_inputs is not None else inputs + labels = actual_inputs.get("labels") + if labels is not None: + completion_lengths = (labels != -100).sum(dim=1).float() + gathered_lengths = self.accelerator.gather(completion_lengths) + mode = "train" + prefix = "on_policy" if is_on_policy else "off_policy" + self._metrics[mode][f"completions/{prefix}_mean_length"].append(gathered_lengths.mean().item()) + self._metrics[mode][f"completions/{prefix}_max_length"].append(gathered_lengths.max().item()) + self._metrics[mode][f"completions/{prefix}_min_length"].append(gathered_lengths.min().item()) + + # Log fraction of completions that hit max_completion_length (truncated) + max_comp_len = getattr(self.generation_config, "max_new_tokens", None) + if is_on_policy and max_comp_len is not None: + truncated_frac = (gathered_lengths >= max_comp_len).float().mean().item() + self._metrics[mode]["completions/truncated_fraction"].append(truncated_frac) + + # Track loss per policy type + loss_scalar = float(loss.detach()) + step_equiv = 1.0 / self.args.gradient_accumulation_steps + if is_on_policy: + self._on_policy_loss_total += loss_scalar + self._on_policy_step_equiv += step_equiv + else: + self._off_policy_loss_total += loss_scalar + self._off_policy_step_equiv += step_equiv + + return loss + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} + + if mode == "train": + # Aggregate on/off-policy losses across distributed processes + device = self.accelerator.device if hasattr(self.accelerator, "device") else torch.device("cpu") + vec = torch.tensor( + [ + self._on_policy_loss_total, + self._off_policy_loss_total, + self._on_policy_step_equiv, + self._off_policy_step_equiv, + ], + dtype=torch.float64, + device=device, + ) + + if ( + getattr(self.accelerator, "distributed_type", DistributedType.NO) != DistributedType.NO + and dist.is_available() + and dist.is_initialized() + ): + dist.all_reduce(vec, op=dist.ReduceOp.SUM) + + on_sum, off_sum, on_eq, off_eq = vec.tolist() + if on_eq > 0: + logs["on_policy_loss"] = round(on_sum / on_eq, 4) + if off_eq > 0: + logs["off_policy_loss"] = round(off_sum / off_eq, 4) + + self._on_policy_loss_total = self._off_policy_loss_total = 0.0 + self._on_policy_step_equiv = self._off_policy_step_equiv = 0.0 + + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + # Log completions to console, wandb, and trackio + should_log_completions = ( + self.log_completions + and self.state.global_step > 0 + and self.state.global_step % self.log_completions_steps == 0 + ) + + if should_log_completions and self.accelerator.is_main_process: + prompts = list(self._textual_logs["prompt"]) + completions = list(self._textual_logs["completion"]) + + if prompts: + _print_completions_sample(prompts, completions, self.state.global_step, self.num_completions_to_print) + + logging_backends = [] + if self.args.report_to and "wandb" in self.args.report_to and wandb.run is not None: + logging_backends.append(wandb) + if self.args.report_to and "trackio" in self.args.report_to: + logging_backends.append(trackio) + + if logging_backends: + import pandas as pd + + table_data = { + "step": [str(self.state.global_step)] * len(prompts), + "prompt": prompts, + "completion": completions, + } + df = pd.DataFrame(table_data) + if self.num_completions_to_print and len(df) > self.num_completions_to_print: + df = df.sample(n=self.num_completions_to_print, random_state=42) + + for logging_backend in logging_backends: + logging_backend.log({"completions": logging_backend.Table(dataframe=df)}) + + # Clear text logs on all processes after the logging interval + if should_log_completions: + self._textual_logs["prompt"].clear() + self._textual_logs["completion"].clear() diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/dppo/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/dppo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0ce3ffeae4fc9c790f3249ba48a958567c66d35f --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/dppo/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from .dppo_config import DPPOConfig +from .dppo_trainer import DPPOTrainer diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/dppo/dppo_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/dppo/dppo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..92736aac144ad648aeb4b52973535744330963c6 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/dppo/dppo_config.py @@ -0,0 +1,115 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Literal + +from ...trainer.grpo_config import GRPOConfig + + +@dataclass +class DPPOConfig(GRPOConfig): + """ + Configuration class for DPPOTrainer. + + DPPO (Divergence Proximal Policy Optimization) replaces PPO/GRPO's heuristic ratio-clipping with a principled trust + region based on direct policy divergence estimates. + + Paper: "Rethinking the Trust Region in LLM Reinforcement Learning" (arXiv:2602.04879) + + Args: + divergence_type (`Literal["binary_tv", "binary_kl", "topk_tv", "topk_kl"]`, *optional*, defaults to `"binary_tv"`): + Divergence approximation used for the trust-region mask. Binary variants use only per-token log-probs; + top-K variants require storing top-K token IDs and log-probs during rollout generation plus full logits + during training. + + divergence_topk (`int`, *optional*, defaults to `20`): + K for top-K divergence approximations. Only used when `divergence_type` is `"topk_tv"` or `"topk_kl"`. + + clip_ratio_c (`float`, *optional*, defaults to `20.0`): + Upper bound on the importance-sampling ratio for stability. The IS ratio is clamped to [0, clip_ratio_c]. + + epsilon (`float`, inherited from GRPOConfig, default overridden to `0.15`): + Divergence threshold δ_low. Tokens whose divergence exceeds this when the policy moves in the + advantage-decreasing direction are masked. The paper recommends 0.15 for TV divergence and 0.05 for KL + divergence. + + epsilon_high (`float`, inherited from GRPOConfig, default overridden to `0.15`): + Divergence threshold δ_high. Tokens whose divergence exceeds this when the policy moves in the + advantage-increasing direction are masked. The paper recommends 0.15 for TV divergence and 0.05 for KL + divergence. + """ + + divergence_type: Literal["binary_tv", "binary_kl", "topk_tv", "topk_kl"] = field( + default="binary_tv", + metadata={ + "help": "Divergence approximation used for the trust-region mask. Binary variants use only per-token " + "log-probs; top-K variants require storing top-K token IDs and log-probs during rollout generation plus " + "full logits during training." + }, + ) + divergence_topk: int = field( + default=20, + metadata={ + "help": "K for top-K divergence approximations. Only used when `divergence_type` is `'topk_tv'` or " + "`'topk_kl'`." + }, + ) + clip_ratio_c: float = field( + default=20.0, + metadata={ + "help": "Upper bound on the importance-sampling ratio for stability. The IS ratio is clamped to " + "[0, clip_ratio_c]." + }, + ) + epsilon: float = field( + default=0.15, + metadata={ + "help": "Divergence threshold δ_low. Tokens whose divergence exceeds this when the policy moves in the " + "advantage-decreasing direction are masked. The paper recommends 0.15 for TV divergence and 0.05 for KL " + "divergence." + }, + ) + epsilon_high: float = field( + default=0.15, + metadata={ + "help": "Divergence threshold δ_high. Tokens whose divergence exceeds this when the policy moves in the " + "advantage-increasing direction are masked. The paper recommends 0.15 for TV divergence and 0.05 for KL " + "divergence." + }, + ) + + def __post_init__(self): + super().__post_init__() + + if self.divergence_type not in ("binary_tv", "binary_kl", "topk_tv", "topk_kl"): + raise ValueError( + f"divergence_type must be one of 'binary_tv', 'binary_kl', 'topk_tv', 'topk_kl', " + f"got {self.divergence_type!r}" + ) + + if self.divergence_topk < 1: + raise ValueError(f"divergence_topk must be >= 1, got {self.divergence_topk}") + + if self.clip_ratio_c <= 0: + raise ValueError(f"clip_ratio_c must be > 0, got {self.clip_ratio_c}") + + if self.loss_type != "dapo": + raise ValueError(f"loss_type {self.loss_type} is not supported for DPPO") + + if self.top_entropy_quantile != 1.0: + raise ValueError("top_entropy_quantile is not supported for DPPO") + + if self.off_policy_mask_threshold is not None: + raise ValueError("off_policy_mask_threshold is not supported for DPPO") diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/dppo/dppo_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/dppo/dppo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..8b4ed4d5efdc9eb2398b54157b2ac800132bbcf2 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/dppo/dppo_trainer.py @@ -0,0 +1,1396 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import asyncio +import copy +import math +import textwrap +from collections.abc import Callable +from contextlib import nullcontext +from copy import copy as shallow_copy +from typing import Any + +import numpy as np +import torch +import transformers +from accelerate.utils import gather_object +from datasets import Dataset, IterableDataset +from packaging.version import Version +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from transformers import ( + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + Trainer, + TrainerCallback, +) +from transformers.utils import is_peft_available + +from ...chat_template_utils import parse_response +from ...data_utils import ( + apply_chat_template, + is_conversational, + prepare_multimodal_messages, +) +from ...extras.profiling import profiling_context, profiling_decorator +from ...models import unwrap_model_for_generation +from ...models.utils import disable_gradient_checkpointing +from ...trainer.grpo_trainer import EnvironmentFactory, GRPOTrainer, RewardFunc, RolloutFunc +from ...trainer.utils import ( + entropy_from_logits, + nanstd, + pad, + selective_log_softmax, + use_adapter, +) +from .dppo_config import DPPOConfig + + +if is_peft_available(): + from peft import PeftConfig, PeftModel + +SAFETY_CLAMP_MAX = 20 + + +def _strip_padding(tensor: torch.Tensor, mask: torch.Tensor) -> list[list]: + """Remove padding from a batched tensor using a mask, returning a ragged list-of-lists.""" + return [row[m].tolist() for row, m in zip(tensor, mask.bool(), strict=True)] + + +class DPPOTrainer(GRPOTrainer): + """ + Trainer for Divergence Proximal Policy Optimization (DPPO). + + DPPO replaces PPO/GRPO's heuristic ratio-clipping with a principled trust region based on direct policy divergence + estimates. PPO-style clipping masks tokens based on probability ratio π/μ, which over-penalizes low-probability + tokens and under-penalizes high-probability tokens. In contrast, DPPO masks based on direct approximation of policy + divergence (e.g TV or KL) ensuring updates stay within a theoretically grounded trust region. + + + Four divergence approximations are supported: + - `binary_tv`: Absolute probability difference |π(a) - μ(a)| (simplest) + - `binary_kl`: Bernoulli KL divergence between old and new token probabilities + - `topk_tv`: Total variation over the top-K tokens of the distribution + - `topk_kl`: KL divergence over the top-K tokens of the distribution + + Args: + model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]): + Model to be trained. Can be either: + + - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using `.from_pretrained` (where `` is derived from the model + config) with the keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported. + - A [`~peft.PeftModel`] object. Only causal language models are supported. + reward_funcs (`RewardFunc | list[RewardFunc]`): + Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward + functions with the prompts and completions and sum the rewards. Can be either: + + - A single reward function, such as: + - A string: The *model ID* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using [`~transformers.AutoModelForSequenceClassification.from_pretrained`] with `num_labels=1` and the + keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object: Only sequence classification models are supported. + - A custom reward function: The function is provided with the prompts and the generated completions, + plus any additional columns in the dataset. It should return a list of rewards. Custom reward + functions can be either synchronous or asynchronous and can also return `None` when the reward is + not applicable to those samples. This is useful for multi-task training where different reward + functions apply to different types of samples. When a reward function returns `None` for a sample, + that reward function is excluded from the reward calculation for that sample. For more details, see + [Using a custom reward + function](#using-a-custom-reward-function). + + The trainer's state is also passed to the reward function. The trainer's state is an instance of + [`~transformers.TrainerState`] and can be accessed by accessing the `trainer_state` argument to the + reward function's signature. + - A list of reward functions, where each item can independently be any of the above types. Mixing different + types within the list (e.g., a string model ID and a custom reward function) is allowed. + args ([`DPPOConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset is + ignored. The format of the samples can be either: + + - [Standard](dataset_formats#standard): Each sample contains plain text. + - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role + and content). + eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`): + Dataset to use for evaluation. It must meet the same requirements as `train_dataset`. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. The padding side must be set to "left". If `None`, the + processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A + padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token, + `tokenizer.eos_token` will be used as the default. + reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*): + Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either: + + - A single processing class: Used when `reward_funcs` contains only one reward function. + - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`. + If set to `None`, or if an element of the list corresponding to a [`~transformers.PreTrainedModel`] is + `None`, the tokenizer for the model is automatically loaded using + [`~transformers.AutoTokenizer.from_pretrained`]. For elements in `reward_funcs` that are custom reward + functions (not [`~transformers.PreTrainedModel`]), the corresponding entries in `reward_processing_classes` + are ignored. + callbacks (list of [`~transformers.TrainerCallback`], *optional*): + List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed + in [here](https://huggingface.co/docs/transformers/main_classes/callback). + + If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`] + method. + optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`): + A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your + model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration used to wrap the model. If `None`, the model is not wrapped. + tools (list of `Callable`, *optional*): + A list of callable tool functions (sync or async) that the model can invoke during generation. Each tool + should be a standard Python function with properly type-hinted arguments and return values, and a + Google-style docstring describing its purpose, arguments, and return value. For more details, see: + https://huggingface.co/docs/transformers/en/chat_extras#passing-tools. The model uses the function's name, + type hints, and docstring to determine how to call it. Ensure that the model's chat template supports tool + use and that it has been fine-tuned for tool calling. + rollout_func (`RolloutFunc`, *optional*): + Function to use for generating completions. It receives the list of prompts allocated to the current + process and the trainer instance. It must return a dict with `"prompt_ids"`, `"completion_ids"`, and + `"logprobs"` fields. Any other fields are forwarded to the reward functions. This feature is experimental + and may change or be removed at any time without prior notice. + environment_factory (`EnvironmentFactory`, *optional*): + A callable that creates and returns an environment instance. The environment class should define methods + that can be invoked as tools during generation. Each method should comply with the same requirements as the + `tools` described above. If `environment_factory` is provided, an instance of the environment is created + for each generation in the batch, allowing for parallel and independent interactions. The environment must + also implement a callable `reset` method that can be used to reset state between generations. The `reset` + method should return either `None` or a string: when it returns a string, that string is appended to the + last user message before generation. This feature is experimental and may change or be removed at any time + without prior notice. + """ + + _tag_names = ["trl", "dppo"] + _name = "DPPO" + _paper = { + "title": "Rethinking the Trust Region in LLM Reinforcement Learning", + "id": "2602.04879", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{qi2026rethinking, + title = {{Rethinking the Trust Region in LLM Reinforcement Learning}}, + author = {Qi, Penghui and Zhou, Xiangxin and Liu, Zichen and Pang, Tianyu and Du, Chao and Lin, Min and Lee, Wee Sun}, + journal = {arXiv preprint arXiv:2602.04879}, + year = {2026} + }"""), + } + + def __init__( + self, + model: "str | PreTrainedModel | PeftModel", + reward_funcs: RewardFunc | list[RewardFunc], + args: DPPOConfig | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + peft_config: "PeftConfig | None" = None, + tools: list[Callable] | None = None, + rollout_func: RolloutFunc | None = None, + environment_factory: EnvironmentFactory | None = None, + ): + if args is None: + model_name = model if isinstance(model, str) else model.config._name_or_path + model_name = model_name.split("/")[-1] + args = DPPOConfig(f"{model_name}-DPPO") + + self.divergence_type = args.divergence_type + self.divergence_topk = args.divergence_topk + self.clip_ratio_c = args.clip_ratio_c + + super().__init__( + model=model, + reward_funcs=reward_funcs, + args=args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + reward_processing_classes=reward_processing_classes, + callbacks=callbacks, + optimizers=optimizers, + peft_config=peft_config, + tools=tools, + rollout_func=rollout_func, + environment_factory=environment_factory, + ) + + if self.divergence_type in ["topk_tv", "topk_kl"] and self.use_vllm: + self.vllm_generation.logprobs = self.divergence_topk + + def _tokenize_prompts(self, prompts: list): + """Tokenize prompts and extract images/multimodal fields for generation.""" + if is_conversational({"prompt": prompts[0]}): + images = [] + has_images = False + for prompt in prompts: + prompt_images = [] + for message in prompt: + if isinstance(message["content"], list): + for part in message["content"]: + if part["type"] == "image": + prompt_images.append(part["image"]) + has_images = True + images.append(prompt_images if prompt_images else None) + images = images if has_images else None + + # Workaround for a bug in transformers 5.3.0 where some processors (e.g. Qwen2.5-VL) crash on + # batched unpadded input (transformers#44514). + # Fixed in transformers 5.4.0 (transformers#44563). + needs_padding_workaround = Version("5.3.0") <= Version(transformers.__version__) < Version("5.4.0") + tokenized = self.processing_class.apply_chat_template( + conversation=prompts, + tools=self.tools or None, # `or None`: Llama bug: it renders tool boilerplate for tools=[] + chat_template=self.chat_template, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + **({"padding": True} if needs_padding_workaround else {}), + **self.chat_template_kwargs, + ) + if needs_padding_workaround: + # Unpad input_ids: remove padding tokens using attention_mask to get per-sequence lists + prompt_ids = [ + [tok for tok, m in zip(ids, mask, strict=True) if m] + for ids, mask in zip(tokenized["input_ids"], tokenized["attention_mask"], strict=True) + ] + else: + prompt_ids = tokenized["input_ids"] + multimodal_fields = {k: v for k, v in tokenized.items() if k not in ("input_ids", "attention_mask")} + else: + prompt_ids = self.processing_class(text=prompts)["input_ids"] + images = None + multimodal_fields = {} + return prompt_ids, images, multimodal_fields + + def _generate_single_turn(self, prompt_ids, images, multimodal_fields): + """Generate completions, always extracting sampled token logprobs. + + Returns: + 5-tuple of (prompt_ids, completion_ids, logprobs, topk_logprobs, topk_token_ids). topk_logprobs and + topk_token_ids are None when divergence_type is not topk. + """ + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + needs_topk = self.divergence_type in ["topk_tv", "topk_kl"] + K = self.divergence_topk + + if self.use_vllm: + if self.state.global_step != self._last_loaded_step: + with profiling_context(self, "sync_weights"): + self.vllm_generation.sync_weights() + self._last_loaded_step = self.state.global_step + + num_generations = self.num_generations if mode == "train" else self.num_generations_eval + prompt_ids, completion_ids, logprobs, logprob_token_ids = self.vllm_generation.generate( + prompts=prompt_ids, + images=images, + num_generations=num_generations, + profiler=profiling_context(self, "vLLM.generate"), + ) + + if needs_topk: + # vLLM returns up to K+1 entries sorted by rank (most probable first). + # The sampled token is always included but may be at any position. + # Per the paper, A'_t = TopK(μ, K) ∪ {a_t}. We keep exactly K slots: if the + # sampled token a_t is not in the top-K, it replaces the K-th ranked entry. + topk_logprobs = [] + topk_token_ids = [] + sampled_logprobs = [] + for seq_lps, seq_tids, seq_cids in zip(logprobs, logprob_token_ids, completion_ids, strict=True): + seq_topk_lps, seq_topk_tids, seq_sampled = [], [], [] + for step_lps, step_tids, sampled_tid in zip(seq_lps, seq_tids, seq_cids, strict=True): + idx = step_tids.index(sampled_tid) + seq_sampled.append(step_lps[idx]) + # Take top-K entries, then ensure sampled token is present + tk_lps = step_lps[:K] + tk_tids = step_tids[:K] + if sampled_tid not in tk_tids: + tk_lps[-1] = step_lps[idx] + tk_tids[-1] = sampled_tid + seq_topk_lps.append(tk_lps) + seq_topk_tids.append(tk_tids) + topk_logprobs.append(seq_topk_lps) + topk_token_ids.append(seq_topk_tids) + sampled_logprobs.append(seq_sampled) + else: + sampled_logprobs = [[step_lps[0] for step_lps in seq_lps] for seq_lps in logprobs] + topk_logprobs = None + topk_token_ids = None + + return prompt_ids, completion_ids, sampled_logprobs, topk_logprobs, topk_token_ids + else: + prompt_tensors = [torch.tensor(ids) for ids in prompt_ids] + padded_ids = pad(prompt_tensors, padding_value=self._tokenizer.pad_token_id, padding_side="left") + attention_mask = pad([torch.ones_like(t) for t in prompt_tensors], padding_value=0, padding_side="left") + generate_inputs = {"input_ids": padded_ids, "attention_mask": attention_mask} + for key, value in multimodal_fields.items(): + if isinstance(value, torch.Tensor): + generate_inputs[key] = value + elif isinstance(value, list) and value and isinstance(value[0], list): + generate_inputs[key] = pad([torch.tensor(x) for x in value], padding_value=0, padding_side="left") + else: + generate_inputs[key] = torch.tensor(np.array(value)) + generate_inputs = Trainer._prepare_inputs(self, generate_inputs) + + gen_config = shallow_copy(self.generation_config) + gen_config.output_logits = True + gen_config.return_dict_in_generate = True + + with ( + profiling_context(self, "transformers.generate"), + unwrap_model_for_generation( + self.model_wrapped, + self.accelerator, + gather_deepspeed3_params=self.args.ds3_gather_for_generation, + generation_kwargs=self.generation_kwargs, + ) as unwrapped_model, + torch.no_grad(), + FSDP.summon_full_params(self.model_wrapped, recurse=False) if self.is_fsdp_enabled else nullcontext(), + ): + gen_output = unwrapped_model.generate(**generate_inputs, generation_config=gen_config) + + prompt_ids_tensor, prompt_mask = generate_inputs["input_ids"], generate_inputs["attention_mask"] + prompt_length = prompt_ids_tensor.size(1) + completion_ids = gen_output.sequences[:, prompt_length:] + + sampled_chunks = [] + topk_logps_chunks = [] if needs_topk else None + topk_ids_chunks = [] if needs_topk else None + + for t, logits_t in enumerate(gen_output.logits): + # logits_t: (B, V) + logits_t = logits_t / self.temperature + + # exact sampled-token logprob without allocating (B, V) log_softmax output + logZ_t = torch.logsumexp(logits_t, dim=-1, keepdim=True) + sampled_ids_t = completion_ids[:, t : t + 1] + sampled_lp_t = logits_t.gather(-1, sampled_ids_t) - logZ_t + sampled_chunks.append(sampled_lp_t.cpu()) + + if needs_topk: + topk_logits_t, topk_ids_t = torch.topk(logits_t, k=K, dim=-1) # (B, K), (B, K) + topk_lp_t = topk_logits_t - logZ_t + + # Ensure sampled token is included in A'_t = TopK ∪ {a_t} + missing = ~(topk_ids_t == sampled_ids_t).any(dim=-1) + if missing.any(): + topk_ids_t = topk_ids_t.clone() + topk_lp_t = topk_lp_t.clone() + topk_ids_t[missing, -1] = sampled_ids_t[missing, 0] + topk_lp_t[missing, -1] = sampled_lp_t[missing, 0] + + topk_ids_chunks.append(topk_ids_t.cpu()) + topk_logps_chunks.append(topk_lp_t.cpu()) + + # Mask everything after the first EOS token + is_eos = completion_ids == self._tokenizer.eos_token_id + has_eos = is_eos.any(dim=1) + eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device) + eos_idx[has_eos] = is_eos.int().argmax(dim=1)[has_eos] + sequence_indices = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1) + completion_mask = (sequence_indices <= eos_idx.unsqueeze(1)).int() + prompt_mask_cpu = prompt_mask.bool().cpu() + completion_mask_cpu = completion_mask.bool().cpu() + + prompt_ids_out = _strip_padding(prompt_ids_tensor.cpu(), prompt_mask_cpu) + completion_ids_out = _strip_padding(completion_ids.cpu(), completion_mask_cpu) + logprobs_out = _strip_padding(torch.cat(sampled_chunks, dim=1), completion_mask_cpu) + if needs_topk: + topk_logprobs = _strip_padding(torch.stack(topk_logps_chunks, dim=1), completion_mask_cpu) + topk_token_ids = _strip_padding(torch.stack(topk_ids_chunks, dim=1), completion_mask_cpu) + else: + topk_logprobs = None + topk_token_ids = None + + return prompt_ids_out, completion_ids_out, logprobs_out, topk_logprobs, topk_token_ids + + def _tool_call_loop( + self, prompts, prompt_ids, completion_ids, completions, logprobs, topk_logprobs, topk_token_ids + ): + """Tool execution loop that also threads top-K logprob data alongside logprobs. + + Mirrors GRPOTrainer._tool_call_loop but additionally concatenates topk_logprobs and topk_token_ids the same way + logprobs is concatenated: real data for model-generated tokens, zero-padding for tool-result tokens. When topk + data is None (binary divergence), behaves identically to the parent. + """ + K = self.divergence_topk + has_topk = topk_logprobs is not None + + tool_calls = [completion[0].get("tool_calls") for completion in completions] + idxs_with_tool = [idx for idx, tool_call in enumerate(tool_calls) if tool_call] + tool_calls = [tool_calls[idx] for idx in idxs_with_tool] + tool_mask = [[1] * len(ids) for ids in completion_ids] + tool_call_count = 0 + tool_failure_count = 0 + iteration_num = 0 + while idxs_with_tool and iteration_num < self.max_tool_calling_iterations: + prompt_completion_tools = [prompts[i] for i in idxs_with_tool] + + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + tool_call_list = tool_calls[idx] + prompt_completion_tool = prompt_completion_tools[idx] + sync_tool_dict = self._sync_tool_dicts[idx_with_tool] + async_tool_dict = self._async_tool_dicts[idx_with_tool] + prompt_completion_tool.append(completions[idx_with_tool][-1]) + async_coros = [] + tool_call_results = [] + for tool_call in tool_call_list: + tool_call_count += 1 + if tool_call["type"] == "function": + function = tool_call["function"] + name = function["name"] + try: + if name in sync_tool_dict: + tool_call_results.append((name, sync_tool_dict[name](**function["arguments"]))) + elif name in async_tool_dict: + async_coros.append((name, async_tool_dict[name](**function["arguments"]))) + else: + raise ValueError(f"Tool {name} not found.") + except Exception as err: + tool_failure_count += 1 + tool_call_results.append((name, {"error": str(err)})) + else: + tool_failure_count += 1 + name = tool_call.get("name", "unknown") + tool_call_results.append((name, {"error": f"Unsupported tool call type: {tool_call['type']}"})) + + if async_coros: + + async def _run_async_tools(async_coros): + coros = [coro for _, coro in async_coros] + results = await asyncio.gather(*coros, return_exceptions=True) + return [(name, result) for (name, _), result in zip(async_coros, results, strict=False)] + + async_results = asyncio.run_coroutine_threadsafe( + _run_async_tools(async_coros), self.async_loop + ).result() + + for name, result in async_results: + if isinstance(result, Exception): + tool_failure_count += 1 + tool_call_results.append((name, {"error": str(result)})) + else: + tool_call_results.append((name, result)) + + for name, result in tool_call_results: + tool_message = {"role": "tool", "name": name, "content": str(result)} + prompt_completion_tool.append(tool_message) + completions[idx_with_tool].append(tool_message) + + # Tokenize and filter samples whose length exceeds max allowed length + pct_ids = self.processing_class.apply_chat_template( + prompt_completion_tools, + tools=self.tools or None, # `or None`: Llama bug: it renders tool boilerplate for tools=[] + chat_template=self.chat_template, + add_generation_prompt=True, + tokenize=True, + return_dict=False, + **self.chat_template_kwargs, + ) + if self.use_vllm and self.vllm_mode == "colocate": + max_model_len = self.vllm_generation.llm.llm_engine.model_config.max_model_len + elif not self.use_vllm: + max_model_len = self.model.config.max_position_embeddings + else: + raise NotImplementedError( + f"Unsupported mode detected: use_vllm={self.use_vllm}, vllm_mode={self.vllm_mode}" + ) + overlong = [len(pct) >= max_model_len for pct in pct_ids] + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + if overlong[idx]: + prompt_length = len(prompt_ids[idx_with_tool]) + ct = pct_ids[idx][prompt_length : prompt_length + self.max_completion_length] + completion_ids[idx_with_tool] = ct + tool_mask[idx_with_tool] += [1] * (len(ct) - len(tool_mask[idx_with_tool])) + if logprobs is not None: + logprobs[idx_with_tool] += [0.0] * (len(ct) - len(logprobs[idx_with_tool])) + if has_topk: + topk_logprobs[idx_with_tool] += [[0.0] * K] * (len(ct) - len(topk_logprobs[idx_with_tool])) + topk_token_ids[idx_with_tool] += [[0] * K] * (len(ct) - len(topk_token_ids[idx_with_tool])) + + idxs_with_tool = [idx for idx, o in zip(idxs_with_tool, overlong, strict=True) if not o] + prompt_completion_tools = [pct for pct, o in zip(prompt_completion_tools, overlong, strict=True) if not o] + if not idxs_with_tool: + break + + # Generate new completions after tool execution + pct_prompt_ids, pct_images, pct_multimodal_fields = self._tokenize_prompts(prompt_completion_tools) + ( + prompt_completion_tool_ids, + post_tool_ids, + post_tool_logprobs, + post_tool_topk_logprobs, + post_tool_topk_token_ids, + ) = self._generate_single_turn(pct_prompt_ids, pct_images, pct_multimodal_fields) + + # Sanity check: chat template must be prefix-preserving + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + pct = prompt_completion_tool_ids[idx] + if prompt_ids[idx_with_tool] != pct[: len(prompt_ids[idx_with_tool])]: + raise ValueError( + "The chat template is not prefix-preserving. Please update it to use a prefix-preserving " + "format." + ) + + # Truncate so that pct[len(prompt_ids[idx]):] + post_tool does not exceed max_completion_length + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + prompt_len = len(prompt_ids[idx_with_tool]) + completion_tool_ids = prompt_completion_tool_ids[idx][prompt_len:] + excess_length = len(completion_tool_ids) + len(post_tool_ids[idx]) - self.max_completion_length + if excess_length > 0: + post_tool_ids[idx] = post_tool_ids[idx][:-excess_length] + if logprobs is not None: + post_tool_logprobs[idx] = post_tool_logprobs[idx][:-excess_length] + if has_topk and post_tool_topk_logprobs is not None: + post_tool_topk_logprobs[idx] = post_tool_topk_logprobs[idx][:-excess_length] + post_tool_topk_token_ids[idx] = post_tool_topk_token_ids[idx][:-excess_length] + excess_length = len(completion_tool_ids) + len(post_tool_ids[idx]) - self.max_completion_length + if excess_length > 0: + prompt_completion_tool_ids[idx] = prompt_completion_tool_ids[idx][:-excess_length] + + # Update tool_mask and logprobs: tool result tokens get 0/0.0, post-tool model tokens get 1/real values + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + prompt_completion_tool_length = len(prompt_completion_tool_ids[idx]) + prompt_length = len(prompt_ids[idx_with_tool]) + completion_length = len(completion_ids[idx_with_tool]) + post_tool_length = len(post_tool_ids[idx]) + tool_length = prompt_completion_tool_length - prompt_length - completion_length + tool_mask[idx_with_tool] += [0] * tool_length + [1] * post_tool_length + if logprobs is not None: + logprobs[idx_with_tool] += [0.0] * tool_length + post_tool_logprobs[idx] + if has_topk: + topk_pad = [[0.0] * K] * tool_length + tid_pad = [[0] * K] * tool_length + post_topk_lp = post_tool_topk_logprobs[idx] if post_tool_topk_logprobs is not None else [] + post_topk_tid = post_tool_topk_token_ids[idx] if post_tool_topk_token_ids is not None else [] + topk_logprobs[idx_with_tool] += topk_pad + post_topk_lp + topk_token_ids[idx_with_tool] += tid_pad + post_topk_tid + + # Update completion_ids with the new completions (after tool execution) + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + prompt_length = len(prompt_ids[idx_with_tool]) + pct = prompt_completion_tool_ids[idx] + completion_ids[idx_with_tool] = pct[prompt_length:] + post_tool_ids[idx] + + # Decode post-tool completions + post_tool_completions = [parse_response(self._tokenizer, ids) if ids else {} for ids in post_tool_ids] + + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + if post_tool_completions[idx]: + completions[idx_with_tool].append(post_tool_completions[idx]) + + # Check for further tool calls + tool_calls = [completion.get("tool_calls") for completion in post_tool_completions] + idxs_with_tool = [idx for idx, tool_call in zip(idxs_with_tool, tool_calls, strict=True) if tool_call] + tool_calls = [tool_call for tool_call in tool_calls if tool_call] + iteration_num += 1 + + return ( + tool_mask, + completions, + completion_ids, + logprobs, + topk_logprobs, + topk_token_ids, + tool_call_count, + tool_failure_count, + ) + + def _generate(self, prompts: list): + """Generate completions, handling tool calls, and thread top-K logprob data through the full pipeline. + + Returns: + 9-tuple of (prompt_ids, completion_ids, tool_mask, completions, total_completion_tokens, logprobs, + topk_logprobs, topk_token_ids, extra_fields). + """ + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + needs_topk = self.divergence_type in ["topk_tv", "topk_kl"] + + # Copy the prompts to avoid modifying the original list + prompts = copy.deepcopy(prompts) + + if self.rollout_func is not None: + # Keep vLLM weights in sync for custom rollouts that rely on vLLM utilities. + if self.use_vllm and self.state.global_step != self._last_loaded_step: + with profiling_context(self, "sync_weights"): + self.vllm_generation.sync_weights() + self._last_loaded_step = self.state.global_step + + # Pass prompts to rollout_func preserving structured messages. + # Chat templating must happen inside rollout_func, at the backend boundary, so that + # multimodal content (images, typed content blocks) is not lost before rollout logic runs. + output = self.rollout_func(prompts, self) + required_keys = {"prompt_ids", "completion_ids", "logprobs"} + missing_keys = required_keys - output.keys() + if missing_keys: + missing_keys_list = sorted(missing_keys) + raise ValueError(f"rollout_func must return keys {missing_keys_list} in its output dict.") + extra_fields = {k: v for k, v in output.items() if k not in required_keys} + prompt_ids = output["prompt_ids"] + completion_ids = output["completion_ids"] + logprobs = output["logprobs"] + topk_logprobs = extra_fields.pop("topk_logprobs", None) + topk_token_ids = extra_fields.pop("topk_token_ids", None) + if needs_topk and (topk_logprobs is None or topk_token_ids is None): + raise ValueError( + "rollout_func must return keys ['topk_logprobs', 'topk_token_ids'] when divergence_type is " + f"{self.divergence_type!r}." + ) + else: + prompt_ids, images, multimodal_fields = self._tokenize_prompts(prompts) + prompt_ids, completion_ids, logprobs, topk_logprobs, topk_token_ids = self._generate_single_turn( + prompt_ids, images, multimodal_fields + ) + extra_fields = {} + + # Decode completions. It's important to use `parse_response` when possible, because it handles tool calls. + if is_conversational({"prompt": prompts[0]}): + if ( + Version(transformers.__version__) >= Version("5.0.0") # parse_response added in v5 + and hasattr(self._tokenizer, "response_schema") # attribute not set by default for now + and self._tokenizer.response_schema is not None # only works if the tokenizer has a schema + ): + completions = [[parse_response(self._tokenizer, ids)] for ids in completion_ids] + else: + contents = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + completions = [[{"role": "assistant", "content": content}] for content in contents] + else: + completions = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + + # Extract tool calls from the completions and (possibly) execute them + if self.tools: + ( + tool_mask, + completions, + completion_ids, + logprobs, + topk_logprobs, + topk_token_ids, + tool_call_count, + tool_failure_count, + ) = self._tool_call_loop( + prompts, prompt_ids, completion_ids, completions, logprobs, topk_logprobs, topk_token_ids + ) + else: + tool_mask = extra_fields.pop("env_mask", None) + + # Get completion length per sequence, used for logging + prompt_lengths = torch.tensor([len(ids) for ids in prompt_ids], device=device) + if tool_mask is not None: + completion_lengths = torch.tensor([sum(mask) for mask in tool_mask], device=device) + else: + completion_lengths = torch.tensor([len(ids) for ids in completion_ids], device=device) + agg_prompt_lengths = self.accelerator.gather(prompt_lengths) + agg_completion_lengths = self.accelerator.gather(completion_lengths) + total_prompt_tokens = agg_prompt_lengths.sum() + total_completion_tokens = agg_completion_lengths.sum() + + if mode == "train": + self.state.num_input_tokens_seen += (total_prompt_tokens + total_completion_tokens).item() + self._metrics[mode]["num_tokens"] = [self.state.num_input_tokens_seen] + + self._metrics[mode]["completions/mean_length"].append(agg_completion_lengths.float().mean().item()) + self._metrics[mode]["completions/min_length"].append(agg_completion_lengths.float().min().item()) + self._metrics[mode]["completions/max_length"].append(agg_completion_lengths.float().max().item()) + + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids], device=device) + agg_is_truncated = self.accelerator.gather(is_truncated) + self._metrics[mode]["completions/clipped_ratio"].append(agg_is_truncated.float().mean().item()) + term_completion_lengths = agg_completion_lengths[~agg_is_truncated] + if len(term_completion_lengths) == 0: + term_completion_lengths = torch.zeros(1, device=device) + self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_lengths.float().mean().item()) + self._metrics[mode]["completions/min_terminated_length"].append(term_completion_lengths.float().min().item()) + self._metrics[mode]["completions/max_terminated_length"].append(term_completion_lengths.float().max().item()) + + if self.tools: + agg_tool_call_count = self.accelerator.gather(torch.tensor(tool_call_count, device=device)).sum() + tool_call_frequency = (agg_tool_call_count / len(agg_prompt_lengths)).item() + self._metrics[mode]["tools/call_frequency"].append(tool_call_frequency) + agg_tool_failure_count = self.accelerator.gather(torch.tensor(tool_failure_count, device=device)).sum() + failure_frequency = ( + (agg_tool_failure_count / agg_tool_call_count).item() if agg_tool_call_count > 0 else 0.0 + ) + self._metrics[mode]["tools/failure_frequency"].append(failure_frequency) + + return ( + prompt_ids, + completion_ids, + tool_mask, + completions, + total_completion_tokens, + logprobs, + topk_logprobs, + topk_token_ids, + extra_fields, + ) + + @profiling_decorator + def _get_per_token_logps_with_topk( + self, + model, + input_ids, + attention_mask, + logits_to_keep, + topk_token_ids, + batch_size=None, + compute_entropy=False, + pixel_values=None, + image_grid_thw=None, + num_images=None, + pixel_attention_mask=None, + image_sizes=None, + token_type_ids=None, + mm_token_type_ids=None, + ) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor]: + """Compute per-token log-probs, (optionally) entropies, and top-K log-probs in one forward pass. + + Evaluates the current policy's log-probs at the rollout's top-K token IDs from the same forward pass used for + per_token_logps, avoiding an extra model call. + + Args: + topk_token_ids: Rollout policy's top-K token IDs, shape (B, T, K). The current policy's + log-probs are evaluated at these positions. + + Returns: + Tuple of (per_token_logps, entropies, current_topk_logps). + """ + batch_size = batch_size or input_ids.size(0) + all_logps = [] + all_entropies = [] + all_topk_logps = [] + + for start in range(0, input_ids.size(0), batch_size): + end = start + batch_size + input_ids_batch = input_ids[start:end] + attention_mask_batch = attention_mask[start:end] + + model_inputs = {"input_ids": input_ids_batch, "attention_mask": attention_mask_batch} + if image_grid_thw is not None and pixel_values is not None: + rows_per_image = image_grid_thw.prod(dim=-1) + rows_per_sample = torch.split(rows_per_image, num_images) + rows_per_sample = torch.stack([s.sum() for s in rows_per_sample]) + cum_rows = torch.cat([torch.tensor([0], device=rows_per_sample.device), rows_per_sample.cumsum(0)]) + row_start, row_end = cum_rows[start].item(), cum_rows[end].item() + model_inputs["pixel_values"] = pixel_values[row_start:row_end] + cum_imgs = torch.tensor([0] + num_images).cumsum(0) + img_start, img_end = cum_imgs[start], cum_imgs[end] + model_inputs["image_grid_thw"] = image_grid_thw[img_start:img_end] + elif pixel_values is not None: + model_inputs["pixel_values"] = pixel_values[start:end] + if pixel_attention_mask is not None: + model_inputs["pixel_attention_mask"] = pixel_attention_mask[start:end] + if image_sizes is not None: + model_inputs["image_sizes"] = image_sizes[start:end] + if token_type_ids is not None: + model_inputs["token_type_ids"] = token_type_ids[start:end] + if mm_token_type_ids is not None: + model_inputs["mm_token_type_ids"] = mm_token_type_ids[start:end] + + if "logits_to_keep" in self.model_kwarg_keys: + model_inputs["logits_to_keep"] = logits_to_keep + 1 + + model_inputs["use_cache"] = False + + logits = model(**model_inputs).logits + logits = logits[:, :-1, :] + logits = logits[:, -logits_to_keep:, :] + logits = logits / self.temperature + + completion_ids = input_ids_batch[:, -logits_to_keep:] + logps = selective_log_softmax(logits, completion_ids) + all_logps.append(logps) + + if compute_entropy: + with torch.no_grad(): + entropies = entropy_from_logits(logits) + all_entropies.append(entropies) + + with torch.no_grad(): + topk_logps = selective_log_softmax(logits, topk_token_ids[start:end]) + all_topk_logps.append(topk_logps) + + logps = torch.cat(all_logps, dim=0) + entropies = torch.cat(all_entropies, dim=0) if compute_entropy else None + topk_logps = torch.cat(all_topk_logps, dim=0) + return logps, entropies, topk_logps + + def _generate_and_score_completions( + self, inputs: list[dict[str, torch.Tensor | Any]] + ) -> dict[str, torch.Tensor | Any]: + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + + prompts = [x["prompt"] for x in inputs] + + if self.environments: + for prompt, environment, reset_kwargs in zip(prompts, self.environments, inputs, strict=True): + observation = environment.reset(**reset_kwargs) + if observation is None: + continue + prompt[-1]["content"] += observation + + if "images" in inputs[0]: + images = [example.get("images") for example in inputs] + elif "image" in inputs[0]: + images = [[example.get("image")] if example.get("image") is not None else None for example in inputs] + else: + images = None + # Transformers requires at least one image in the batch, otherwise it throws an error + if images is not None and all(img_list == [] for img_list in images): + images = None + + # If the prompts are conversational and the inputs contain images, we need to convert the prompts from + # [{"role": "user", "content": "What color is the sky?"}] to + # [{"role": "user", "content": [{"type": "image", "image": }, {"type": "text", "text": "What color is the sky?"}]}] + if images is not None: + if not is_conversational(inputs[0]): + raise ValueError( + "Multimodal training requires conversational prompts. It looks like the dataset contains " + "non-conversational inputs, likely because a chat template was applied before passing the dataset " + "to the trainer. Please provide the raw conversational prompts and let the trainer apply the chat " + "template internally." + ) + prompts = [ + prepare_multimodal_messages(prompt, images=image_list) + for prompt, image_list in zip(prompts, images, strict=True) + ] + + ( + prompt_ids_list, + completion_ids_list, + tool_mask_list, + completions, + num_items_in_batch, + sampling_per_token_logps_list, + topk_logprobs_list, + topk_token_ids_list, + extra_fields, + ) = self._generate(prompts) + + # Convert lists of token IDs to padded tensors + prompt_ids = [torch.tensor(ids) for ids in prompt_ids_list] + prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids] + prompt_ids = pad( + prompt_ids, + padding_value=self._tokenizer.pad_token_id, + padding_side="left", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + prompt_mask = pad( + prompt_mask, padding_value=0, padding_side="left", pad_to_multiple_of=self.pad_to_multiple_of + ).to(device=device) + completion_ids = [torch.tensor(ids) for ids in completion_ids_list] + completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids] + completion_ids = pad( + completion_ids, + padding_value=self._tokenizer.pad_token_id, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + completion_mask = pad( + completion_mask, padding_value=0, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of + ).to(device=device) + sampling_per_token_logps = [torch.tensor(logps) for logps in sampling_per_token_logps_list] + sampling_per_token_logps = pad( + sampling_per_token_logps, + padding_value=0.0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + if tool_mask_list is not None: + tool_mask = [torch.tensor(mask) for mask in tool_mask_list] + tool_mask = pad( + tool_mask, padding_value=1, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of + ).to(device=device) + else: + tool_mask = None + if topk_logprobs_list is not None: + sampling_topk_logps = [torch.tensor(lp) for lp in topk_logprobs_list] + sampling_topk_logps = pad( + sampling_topk_logps, + padding_value=0.0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + sampling_topk_token_ids = [torch.tensor(tid, dtype=torch.long) for tid in topk_token_ids_list] + sampling_topk_token_ids = pad( + sampling_topk_token_ids, + padding_value=0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + else: + sampling_topk_logps = None + sampling_topk_token_ids = None + + # If mask_truncated_completions is enabled, zero out truncated completions for attention and loss masking + if self.mask_truncated_completions: + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device) + # Mask completion_mask for attention masking + completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int() + # Also mask tool_mask for consistency in multi-turn training + if tool_mask is not None: + tool_mask = tool_mask * (~is_truncated).unsqueeze(1).int() + + # Concatenate prompt_mask with completion_mask for logit computation + prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) # (B, P+C) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P+C) + + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + batch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size + + num_images = [len(img_list) for img_list in images] if images is not None else None + + # Get forward_kwargs for models with multimodal inputs + if images is not None: + prompts_text = [ + apply_chat_template( + {"prompt": prompt}, self.processing_class, tools=self.tools, **self.chat_template_kwargs + )["prompt"] + for prompt in prompts + ] + prompt_inputs = self.processing_class(images=images, text=prompts_text, padding=True, return_tensors="pt") + prompt_inputs = Trainer._prepare_inputs(self, prompt_inputs) + forward_kwargs = {k: v for k, v in prompt_inputs.items() if k not in ["input_ids", "attention_mask"]} + else: + forward_kwargs = {} + + # If token_type_ids are used, extend them with zeros for the completion part + if "token_type_ids" in forward_kwargs: + token_type_ids = forward_kwargs["token_type_ids"] + if self.pad_to_multiple_of is not None: + padding_size = prompt_ids.size(1) - token_type_ids.size(1) + if padding_size > 0: + token_type_ids = torch.cat( + [token_type_ids.new_zeros((token_type_ids.size(0), padding_size)), token_type_ids], dim=1 + ) + forward_kwargs["token_type_ids"] = torch.cat( + [token_type_ids, token_type_ids.new_zeros(completion_ids.shape)], dim=1 + ) + # If mm_token_type_ids are used, extend them with zeros for the completion part + if "mm_token_type_ids" in forward_kwargs: + mm_token_type_ids = forward_kwargs["mm_token_type_ids"] + if self.pad_to_multiple_of is not None: + padding_size = prompt_ids.size(1) - mm_token_type_ids.size(1) + if padding_size > 0: + mm_token_type_ids = torch.cat( + [mm_token_type_ids.new_zeros((mm_token_type_ids.size(0), padding_size)), mm_token_type_ids], + dim=1, + ) + forward_kwargs["mm_token_type_ids"] = torch.cat( + [mm_token_type_ids, mm_token_type_ids.new_zeros(completion_ids.shape)], dim=1 + ) + + # When gradient checkpointing is enabled with use_reentrant=True (non default), calling the model inside a + # torch.no_grad() block triggers a harmless PyTorch warning ("None of the inputs have requires_grad=True"). + # Temporarily disable checkpointing to avoid this warning during inference. + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + # Compute the per-token log probabilities for the reference model + if self.beta != 0.0: + if self.ref_model is not None: + ref_per_token_logps, _, _ = self._get_per_token_logps_and_entropies( + self.ref_model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size=batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes + ) + else: + # When training a PEFT adapter, how we obtain the reference depends on the setup: + # - New adapter: disabling adapters yields the base model. + # - Re-training an existing adapter: an initial copy is loaded under the name "ref". + model = self.accelerator.unwrap_model(self.model) + with use_adapter(model, adapter_name="ref" if "ref" in model.peft_config else None): + ref_per_token_logps, _, _ = self._get_per_token_logps_and_entropies( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size=batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes + ) + else: + ref_per_token_logps = None + + # Decode + prompts_text = self.processing_class.batch_decode(prompt_ids, skip_special_tokens=True) + completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + + # Merge extra_fields from rollout_func into inputs for reward functions + if extra_fields: + for i, inp in enumerate(inputs): + for key, values in extra_fields.items(): + if isinstance(values, list) and i < len(values): + inp[key] = values[i] + elif not isinstance(values, list): + inp[key] = values + + # Calculate rewards for each reward function. rewards_per_func aggregates rewards across all processes. This is + # important because rewards will be normalized per group, and completions are distributed. We will later slice + # rewards_per_func to extract each process's subset. + rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list) + num_generations = self.num_generations if mode == "train" else self.num_generations_eval + + if self.multi_objective_aggregation == "sum_then_normalize": + # Apply weights to each reward function's output and sum + rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1) + mean_grouped_rewards = rewards.view(-1, num_generations).mean(dim=1) + mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(num_generations, dim=0) + if self.scale_rewards in ["group", "none"]: + # If self.scale_rewards = "none", we'll only use std_rewards to check for zero std for logging + if num_generations > 1: + std_rewards = rewards.view(-1, num_generations).std(dim=1) + std_rewards = std_rewards.repeat_interleave(num_generations, dim=0) + else: # doesn't occur during training, but could occur in eval when num_generations_eval=1 + std_rewards = torch.zeros_like(rewards) + elif self.scale_rewards == "batch": + # Compute global std + if rewards.numel() > 1: + std_rewards = rewards.std().expand_as(rewards) + else: # doesn't occur during training, but could occur in eval when num_generations_eval=batch_size=1 + std_rewards = torch.zeros_like(rewards) + else: + raise ValueError( + f"Invalid value for scale_rewards: {self.scale_rewards}. Must be one of 'batch', 'group', or 'none'." + ) + + advantages = rewards - mean_grouped_rewards + if self.scale_rewards != "none": + advantages = advantages / (std_rewards + 1e-4) + is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards)) # for logging + + elif self.multi_objective_aggregation == "normalize_then_sum": + grouped = rewards_per_func.view(-1, num_generations, len(self.reward_funcs)) + mean_k = torch.nanmean(grouped, dim=1, keepdim=True) + std_k = nanstd(grouped, dim=1, keepdim=True) if num_generations > 1 else torch.zeros_like(mean_k) + reward_k = (grouped - mean_k) / (std_k + 1e-4) + reward_k = reward_k.view(-1, len(self.reward_funcs)) + rewards = (reward_k * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1) + std_rewards = rewards.std().expand_as(rewards) if rewards.numel() > 1 else torch.zeros_like(rewards) + advantages = (rewards - rewards.mean()) / (std_rewards + 1e-4) + is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards)) # for logging + + else: + raise ValueError( + f"Invalid multi_objective_aggregation: {self.multi_objective_aggregation}. Must be " + "'sum_then_normalize' or 'normalize_then_sum'." + ) + + # Slice to keep only the local part of the data + process_slice = slice( + self.accelerator.process_index * len(prompts), + (self.accelerator.process_index + 1) * len(prompts), + ) + all_process_advantages = advantages.clone() # keep the aggregated advantages for logging + advantages = advantages[process_slice] + + # Calculate mean reward per function, but only for samples where the function was applied (non-NaN values) + for i, reward_func_name in enumerate(self.reward_func_names): + mean_rewards = torch.nanmean(rewards_per_func[:, i]).item() + self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards) + std_func_rewards = nanstd(rewards_per_func[:, i]).item() + self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_func_rewards) + rewards = (rewards_per_func * self.reward_weights.to(rewards_per_func.device).unsqueeze(0)).nansum(dim=1) + self._metrics[mode]["reward"].append(rewards.mean().item()) + self._metrics[mode]["reward_std"].append(rewards.std().item()) + self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item()) + + # Log prompt and completion texts + self._logs["prompt"].extend(gather_object(prompts_text)) + self._logs["completion"].extend(gather_object(completions_text)) + for i, name in enumerate(self.reward_func_names): + self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist()) + self._logs["advantages"].extend(all_process_advantages.tolist()) + + # Flush user-logged extra columns (from log_extra), gathering across processes. + # Keys must be sorted so that all ranks call gather_object in the same order, otherwise values + # get mis-attributed across columns (dict insertion order may differ between processes). + for column in sorted(self._pending_extra_logs): + self._logs["extra"][column].extend(gather_object(self._pending_extra_logs[column])) + self._pending_extra_logs.clear() + + # Flush user-logged metrics (from log_metric), averaging across processes. + # Keys must be sorted so that all ranks call accelerator.gather in the same order, otherwise values + # get mis-attributed across metrics (dict insertion order may differ between processes). + for name in sorted(self._pending_metrics): + values = self._pending_metrics[name] + local_mean = sum(values) / len(values) + global_mean = self.accelerator.gather(torch.tensor(local_mean, device=device)).mean().item() + self._metrics[mode][name].append(global_mean) + self._pending_metrics.clear() + + if images is not None: + self._logs["images"].extend(gather_object(images)) + + output = { + "prompt_ids": prompt_ids, + "prompt_mask": prompt_mask, + "completion_ids": completion_ids, + "completion_mask": completion_mask, + "advantages": advantages, + "num_items_in_batch": num_items_in_batch, + "sampling_per_token_logps": sampling_per_token_logps, + } + if ref_per_token_logps is not None: + output["ref_per_token_logps"] = ref_per_token_logps + if "pixel_values" in forward_kwargs: + output["pixel_values"] = forward_kwargs["pixel_values"] + if "image_grid_thw" in forward_kwargs: + output["image_grid_thw"] = forward_kwargs["image_grid_thw"] + if "pixel_attention_mask" in forward_kwargs: + output["pixel_attention_mask"] = forward_kwargs["pixel_attention_mask"] + if "image_sizes" in forward_kwargs: + output["image_sizes"] = forward_kwargs["image_sizes"] + if "token_type_ids" in forward_kwargs: + output["token_type_ids"] = forward_kwargs["token_type_ids"] + if "mm_token_type_ids" in forward_kwargs: + output["mm_token_type_ids"] = forward_kwargs["mm_token_type_ids"] + if images is not None: + output["num_images"] = num_images + if tool_mask is not None: + output["tool_mask"] = tool_mask + if sampling_topk_logps is not None: + output["sampling_topk_logps"] = sampling_topk_logps + if sampling_topk_token_ids is not None: + output["sampling_topk_token_ids"] = sampling_topk_token_ids + return output + + @torch.no_grad() + def _compute_divergence_mask( + self, + per_token_logps, + sampling_per_token_logps, + advantages, + completion_mask, + current_topk_logps=None, + sampling_topk_logps=None, + ): + """ + Compute a per-token trust-region mask based on the configured divergence type. Tokens where the policy has + diverged too far from the sampling distribution (in a direction that would increase the loss) are masked out. + + Args: + per_token_logps (`torch.Tensor`): + Log-probabilities of the current policy at the sampled tokens, shape `(B, T)`. + sampling_per_token_logps (`torch.Tensor`): + Log-probabilities of the sampling (rollout) policy at the sampled tokens, shape `(B, T)`. + advantages (`torch.Tensor`): + Per-token or per-sequence advantage estimates, broadcastable to `(B, T)`. + completion_mask (`torch.Tensor`): + Binary mask of shape `(B, T)` where `1` indicates valid completion tokens and `0` padding. + current_topk_logps (`torch.Tensor` or `None`): + Log-probabilities of the current policy at the rollout's top-K token IDs, shape `(B, T, K)`. Required + when `divergence_type` is `"topk_tv"` or `"topk_kl"`. + sampling_topk_logps (`torch.Tensor` or `None`): + Log-probabilities of the sampling policy at the rollout's top-K token IDs, shape `(B, T, K)`. Required + when `divergence_type` is `"topk_tv"` or `"topk_kl"`. + + Returns: + `torch.Tensor`: + Float mask of shape `(B, T)` where `1.0` indicates tokens to keep and `0.0` tokens to mask out. + """ + prob = torch.exp(per_token_logps) + sampling_prob = torch.exp(sampling_per_token_logps) + + delta_low = self.epsilon_low + delta_high = self.epsilon_high + + if self.divergence_type == "binary_tv": + # TV = |π - μ| + divergence = (prob - sampling_prob).abs() + # Mask tokens where divergence > threshold AND policy moves away from trust region + invalid_pos = (divergence > delta_high) & (prob > sampling_prob) + invalid_neg = (divergence > delta_low) & (prob < sampling_prob) + mask = torch.where(advantages > 0, ~invalid_pos, ~invalid_neg) + + elif self.divergence_type == "binary_kl": + # Bernoulli KL: D = μ log(μ/π) + (1-μ) log((1-μ)/(1-π)) + kl = sampling_prob * (sampling_per_token_logps - per_token_logps) + (1 - sampling_prob) * ( + torch.log1p(-sampling_prob.clamp(max=1 - 1e-7)) - torch.log1p(-prob.clamp(max=1 - 1e-7)) + ) + + invalid_pos = (kl > delta_high) & (prob > sampling_prob) + invalid_neg = (kl > delta_low) & (prob < sampling_prob) + mask = torch.where(advantages > 0, ~invalid_pos, ~invalid_neg) + + elif self.divergence_type in ("topk_tv", "topk_kl"): + current_topk_probs = torch.exp(current_topk_logps.float()) + rollout_topk_probs = torch.exp(sampling_topk_logps.float()) + + # Aggregate remaining probability mass outside top-K into a single rest bucket. + rollout_rest = (1.0 - rollout_topk_probs.sum(dim=-1)).clamp(min=1e-12) + current_rest = (1.0 - current_topk_probs.sum(dim=-1)).clamp(min=1e-12) + + if self.divergence_type == "topk_tv": + topk_tv = (current_topk_probs - rollout_topk_probs).abs().sum(dim=-1) + rest_tv = (current_rest - rollout_rest).abs() + divergence = (topk_tv + rest_tv) / 2.0 + else: + topk_kl = (rollout_topk_probs * (sampling_topk_logps - current_topk_logps)).sum(dim=-1) + rest_kl = rollout_rest * (rollout_rest.log() - current_rest.log()) + divergence = topk_kl + rest_kl + + invalid_pos = (divergence > delta_high) & (prob > sampling_prob) + invalid_neg = (divergence > delta_low) & (prob < sampling_prob) + mask = torch.where(advantages > 0, ~invalid_pos, ~invalid_neg) + + else: + raise ValueError(f"Unknown divergence_type: {self.divergence_type}") + + return mask.float() * completion_mask + + def _compute_loss(self, model, inputs): + # Compute per-token log probabilities for the model + prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"] + completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"] + input_ids = torch.cat([prompt_ids, completion_ids], dim=1) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) + mask = completion_mask if "tool_mask" not in inputs else completion_mask * inputs["tool_mask"] + + forward_kwargs = { + "pixel_values": inputs.get("pixel_values"), + "image_grid_thw": inputs.get("image_grid_thw"), + "num_images": inputs.get("num_images"), + "pixel_attention_mask": inputs.get("pixel_attention_mask"), + "image_sizes": inputs.get("image_sizes"), + "token_type_ids": inputs.get("token_type_ids"), + "mm_token_type_ids": inputs.get("mm_token_type_ids"), + } + + sampling_topk_token_ids = inputs.get("sampling_topk_token_ids") + if self.divergence_type.startswith("topk_") and sampling_topk_token_ids is not None: + per_token_logps, entropies, current_topk_logps = self._get_per_token_logps_with_topk( + model, + input_ids, + attention_mask, + logits_to_keep, + topk_token_ids=sampling_topk_token_ids, + compute_entropy=True, + **forward_kwargs, + ) + else: + per_token_logps, entropies, _ = self._get_per_token_logps_and_entropies( + model, + input_ids, + attention_mask, + logits_to_keep, + compute_entropy=True, + **forward_kwargs, + ) + current_topk_logps = None + + sampling_per_token_logps = inputs["sampling_per_token_logps"] + sampling_topk_logps = inputs.get("sampling_topk_logps") + + advantages = inputs["advantages"] + if advantages.dim() == 1: + advantages = advantages.unsqueeze(1) + + # DPPO: compute IS ratio (clamped, detached) and divergence mask + log_ratio = per_token_logps - sampling_per_token_logps + ratio = torch.exp(log_ratio.clamp(max=math.log(self.clip_ratio_c))).detach() + divergence_mask = self._compute_divergence_mask( + per_token_logps, + sampling_per_token_logps, + advantages, + mask, + current_topk_logps=current_topk_logps, + sampling_topk_logps=sampling_topk_logps, + ) + + # DPPO loss: -advantages * ratio * mask * log_prob + per_token_loss = -advantages * ratio * divergence_mask * per_token_logps + + # KL divergence with reference model + if self.beta != 0.0: + ref_per_token_logps = inputs["ref_per_token_logps"] + per_token_kl = ( + torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1 + ) + per_token_loss = per_token_loss + self.beta * per_token_kl + + mode = "train" if self.model.training else "eval" + normalizer = inputs["num_items_in_batch"] / self.accelerator.num_processes + loss = (per_token_loss * mask).sum() / normalizer + + # Log metrics + completion_token_count = mask.sum().clamp(min=1.0) + + def masked_batch_mean(x): + if x.shape[1] == 1: + return x.mean() + return (x * mask).sum() / completion_token_count + + if self.beta != 0.0: + mean_kl = masked_batch_mean(per_token_kl) + self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item()) + + mean_entropy = masked_batch_mean(entropies) + self._metrics[mode]["entropy"].append(self.accelerator.gather(mean_entropy).nanmean().item()) + + prob_diff = (torch.exp(per_token_logps) - torch.exp(sampling_per_token_logps)).abs() + self._metrics[mode]["prob_diff/mean"].append( + self.accelerator.gather(masked_batch_mean(prob_diff)).nanmean().item() + ) + per_seq_max = prob_diff.masked_fill(mask == 0, float("-inf")).max(dim=1).values + per_seq_min = prob_diff.masked_fill(mask == 0, float("inf")).min(dim=1).values + self._metrics[mode]["prob_diff/max"].append(self.accelerator.gather(per_seq_max).max().item()) + self._metrics[mode]["prob_diff/min"].append(self.accelerator.gather(per_seq_min).min().item()) + + self._metrics[mode]["advantages/mean"].append(advantages.mean().item()) + self._metrics[mode]["advantages/std"].append(advantages.std().item()) + + # Log divergence mask statistics (analogous to clip_ratio in GRPO) + is_masked = (divergence_mask == 0) & (mask > 0) + is_masked_pos = is_masked & (advantages > 0) + is_masked_neg = is_masked & (advantages < 0) + + mask_ratio_pos = masked_batch_mean(is_masked_pos.float()) + mask_ratio_neg = masked_batch_mean(is_masked_neg.float()) + mask_ratio = masked_batch_mean(is_masked.float()) + + gathered_mask_ratio_neg = self.accelerator.gather(mask_ratio_neg) + self._metrics[mode]["mask_ratio/negative_adv_mean"].append(gathered_mask_ratio_neg.nanmean().item()) + gathered_mask_ratio_pos = self.accelerator.gather(mask_ratio_pos) + self._metrics[mode]["mask_ratio/positive_adv_mean"].append(gathered_mask_ratio_pos.nanmean().item()) + gathered_mask_ratio = self.accelerator.gather(mask_ratio) + self._metrics[mode]["mask_ratio/overall_mean"].append(gathered_mask_ratio.nanmean().item()) + + return loss diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gfpo/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gfpo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f91462a911daaff39038ef4cb53f18ffc845bea8 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gfpo/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .gfpo_config import GFPOConfig +from .gfpo_trainer import GFPOTrainer diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gfpo/gfpo_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gfpo/gfpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..ae529987306eadc276115e425f4509e6dd7f1e1c --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gfpo/gfpo_config.py @@ -0,0 +1,35 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field + +from ...trainer.grpo_config import GRPOConfig as _GRPOConfig + + +@dataclass +class GFPOConfig(_GRPOConfig): + num_remains_in_group: int | None = field( + default=None, + metadata={ + "help": "number inputs remains after group filter function, `'num_remains_in_group'` must be >=2 if given." + }, + ) + + def __post_init__(self): + super().__post_init__() + + if self.num_remains_in_group is not None and self.num_remains_in_group >= self.num_generations: + raise ValueError( + f"Number remains in Group {self.num_remains_in_group} must be less than num_generations : {self.num_generations}." + ) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gfpo/gfpo_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gfpo/gfpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..8cbaf1c5d77a67ca6d2e1381dfafc591143d464b --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gfpo/gfpo_trainer.py @@ -0,0 +1,464 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +from collections.abc import Callable +from typing import Any + +import torch +from accelerate.utils import gather_object + +from ...data_utils import apply_chat_template, is_conversational, prepare_multimodal_messages +from ...models.utils import disable_gradient_checkpointing +from ...trainer.grpo_trainer import GRPOTrainer as _GRPOTrainer +from ...trainer.utils import nanmax, nanmin, nanstd, pad + + +logger = logging.getLogger(__name__) + +GroupFilterFunc = Callable[[list[list[Any]], list[list[Any]]], list[list[float]]] + + +class GFPOTrainer(_GRPOTrainer): + def __init__( + self, + model, + reward_funcs, + args=None, + train_dataset=None, + eval_dataset=None, + processing_class=None, + reward_processing_classes=None, + group_filter_func=None, + callbacks=None, + optimizers=(None, None), + peft_config=None, + ): + super().__init__( + model=model, + reward_funcs=reward_funcs, + args=args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + reward_processing_classes=reward_processing_classes, + callbacks=callbacks, + optimizers=optimizers, + peft_config=peft_config, + ) + self.group_filter_func = group_filter_func + self.num_remains_in_group = args.num_remains_in_group + if self.group_filter_func is None and self.num_remains_in_group is not None: + raise ValueError( + f"Group filter function must not be None when num_remains_in_group ({self.num_remains_in_group}) is given." + ) + if self.group_filter_func is not None and self.num_remains_in_group is None: + logger.warning("Group filter function is not activated since num_remains_in_group is not set") + + def _generate_and_score_completions(self, inputs): + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + + prompts = [x["prompt"] for x in inputs] + + if "images" in inputs[0]: + images = [example.get("images") for example in inputs] + elif "image" in inputs[0]: + images = [[example.get("image")] if example.get("image") is not None else None for example in inputs] + else: + images = None + # Transformers requires at least one image in the batch, otherwise it throws an error + if images is not None and all(img_list == [] for img_list in images): + images = None + + # If the prompts are conversational and the inputs contain images, we need to convert the prompts from + # [{"role": "user", "content": "What color is the sky?"}] to + # [{"role": "user", "content": [{"type": "image", "image": }, {"type": "text", "text": "What color is the sky?"}]}] + if images is not None: + if not is_conversational(inputs[0]): + raise ValueError( + "Multimodal training requires conversational prompts. It looks like the dataset contains " + "non-conversational inputs, likely because a chat template was applied before passing the dataset " + "to the trainer. Please provide the raw conversational prompts and let the trainer apply the chat " + "template internally." + ) + prompts = [ + prepare_multimodal_messages(prompt, images=image_list) + for prompt, image_list in zip(prompts, images, strict=True) + ] + + dataset_images = images # preserve dataset images before _generate may overwrite + ( + prompt_ids_list, + completion_ids_list, + tool_mask_list, + completions, + num_items_in_batch, + sampling_per_token_logps_list, + extra_fields, + images, + tool_images, + ) = self._generate(prompts) + if images is None: + images = dataset_images # restore dataset images (rollout_func path returns None) + + # Convert lists of token IDs to padded tensors + prompt_ids = [torch.tensor(ids) for ids in prompt_ids_list] + prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids] + prompt_ids = pad( + prompt_ids, + padding_value=self._tokenizer.pad_token_id, + padding_side="left", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + prompt_mask = pad( + prompt_mask, + padding_value=0, + padding_side="left", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + completion_ids = [torch.tensor(ids) for ids in completion_ids_list] + completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids] + completion_ids = pad( + completion_ids, + padding_value=self._tokenizer.pad_token_id, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + completion_mask = pad( + completion_mask, + padding_value=0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + if sampling_per_token_logps_list is not None: + sampling_per_token_logps = [torch.tensor(logps) for logps in sampling_per_token_logps_list] + sampling_per_token_logps = pad( + sampling_per_token_logps, + padding_value=0.0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + else: + sampling_per_token_logps = None + + # If mask_truncated_completions is enabled, zero out truncated completions in completion_mask + if self.mask_truncated_completions: + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device) + completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int() + + # Concatenate prompt_mask with completion_mask for logit computation + prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) # (B, P+C) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P+C) + + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + batch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size + + num_images = [len(img_list) if img_list else 0 for img_list in images] if images is not None else None + + # Get forward_kwargs for models with multimodal inputs + if images is not None: + prompts_text = [ + apply_chat_template({"prompt": prompt}, self.processing_class)["prompt"] for prompt in prompts + ] + prompt_inputs = self.processing_class(images=images, text=prompts_text, padding=True, return_tensors="pt") + prompt_inputs = super()._prepare_inputs(prompt_inputs) + forward_kwargs = {k: v for k, v in prompt_inputs.items() if k not in ["input_ids", "attention_mask"]} + else: + forward_kwargs = {} + + # If token_type_ids are used, extend them with zeros for the completion part + if "token_type_ids" in forward_kwargs: + token_type_ids = forward_kwargs["token_type_ids"] + if self.pad_to_multiple_of is not None: + # Needed only with pad_to_multiple_of: otherwise prompt_ids and token_type_ids must have equal len + padding_size = prompt_ids.size(1) - token_type_ids.size(1) + if padding_size > 0: + token_type_ids = torch.cat( + [token_type_ids.new_zeros((token_type_ids.size(0), padding_size)), token_type_ids], dim=1 + ) + forward_kwargs["token_type_ids"] = torch.cat( + [token_type_ids, token_type_ids.new_zeros(completion_ids.shape)], dim=1 + ) + # If mm_token_type_ids are used, extend them with zeros for the completion part + if "mm_token_type_ids" in forward_kwargs: + mm_token_type_ids = forward_kwargs["mm_token_type_ids"] + if self.pad_to_multiple_of is not None: + # Needed only with pad_to_multiple_of: otherwise prompt_ids and mm_token_type_ids must have equal len + padding_size = prompt_ids.size(1) - mm_token_type_ids.size(1) + if padding_size > 0: + mm_token_type_ids = torch.cat( + [mm_token_type_ids.new_zeros((mm_token_type_ids.size(0), padding_size)), mm_token_type_ids], + dim=1, + ) + forward_kwargs["mm_token_type_ids"] = torch.cat( + [mm_token_type_ids, mm_token_type_ids.new_zeros(completion_ids.shape)], dim=1 + ) + + # When gradient checkpointing is enabled with use_reentrant=True (non default), calling the model inside a + # torch.no_grad() block triggers a harmless PyTorch warning ("None of the inputs have requires_grad=True"). + # Temporarily disable checkpointing to avoid this warning during inference. + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + # If the generation and optimization steps are misaligned—i.e., if generation does not occur at the end of + # a full optimizer step (when gradient_accumulation_steps is not a multiple of generate_every)—then the + # samples may come from an earlier version of the model. In that case, we need to track old_per_token_logps + # for importance sampling. If the steps are aligned, importance sampling isn't necessary and we set + # old_per_token_logps to None. + # When using vLLM, we always compute old_per_token_logps for importance sampling, it was shown that the + # distribution mismatch between vLLM and the training model can be large and harm the training. + generate_every = self.args.steps_per_generation * self.num_iterations # generation frequency + if self.args.gradient_accumulation_steps % generate_every != 0 or ( + self.use_vllm and self.vllm_importance_sampling_correction + ): + old_per_token_logps, _, _ = self._get_per_token_logps_and_entropies( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes + ) + else: + old_per_token_logps = None + + # Compute the importance sampling ratio when using vLLM, to correct for potential distribution mismatch + if self.use_vllm and self.vllm_importance_sampling_correction: + importance_sampling_ratio = torch.exp(old_per_token_logps - sampling_per_token_logps) + importance_sampling_ratio = torch.clamp( + importance_sampling_ratio, + min=self.vllm_importance_sampling_clip_min, + max=self.vllm_importance_sampling_clip_max, + ) + + # Compute the per-token log probabilities for the reference model + if self.beta != 0.0: + if self.ref_model is not None: + ref_per_token_logps, _, _ = self._get_per_token_logps_and_entropies( + self.ref_model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size=batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes + ) + else: + with self.accelerator.unwrap_model(self.model).disable_adapter(): + ref_per_token_logps, _, _ = self._get_per_token_logps_and_entropies( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size=batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes + ) + else: + ref_per_token_logps = None + + # Decode + prompts_text = self.processing_class.batch_decode(prompt_ids, skip_special_tokens=True) + completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + if is_conversational(inputs[0]): + completions = [] + for prompt, completion in zip(prompts, completions_text, strict=True): + bootstrap = prompt.pop()["content"] if prompt[-1]["role"] == "assistant" else "" + if isinstance(bootstrap, list): # for VLM, the format might be [{"type": "text", "text": "..."}] + assert len(bootstrap) == 1 and bootstrap[0]["type"] == "text" + bootstrap = bootstrap[0]["text"] + completions.append([{"role": "assistant", "content": bootstrap + completion}]) + else: + completions = completions_text + + # Calculate rewards for each reward function. rewards_per_func aggregates rewards across all processes. This is + # important because rewards will be normalized per group, and completions are distributed. We will later slice + # rewards_per_func to extract each process's subset. + rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list) + + # Apply weights to each reward function's output and sum + rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1) + + num_in_group = self.num_generations + num_inputs_in_device = len(prompts) + + if self.num_remains_in_group is not None and mode == "train": + num_in_group = self.num_remains_in_group + + all_completions = gather_object(completions) + + group_filter_scores = self.group_filter_func( + group_completions=[ + all_completions[i : i + 1 * self.num_generations] + for i in range(len(all_completions) // self.num_generations) + ], + group_rewards=rewards.view(-1, self.num_generations).tolist(), + ) + group_filter_scores = torch.tensor(group_filter_scores, device=device) + + _, group_local_indices = torch.topk(group_filter_scores, self.num_remains_in_group, dim=-1) + group_row_offsets = torch.arange(0, len(all_completions), self.num_generations, device=device).unsqueeze(1) + group_global_indices = group_row_offsets + group_local_indices + group_global_indices = group_global_indices.flatten() + + rewards = rewards[group_global_indices] + rewards_per_func = rewards_per_func[group_global_indices, :] + + num_inputs_in_device = int(len(prompts) / self.num_generations * self.num_remains_in_group) + + # Compute grouped-wise rewards + mean_grouped_rewards = rewards.view(-1, num_in_group).mean(dim=1) + + # Normalize the rewards to compute the advantages + mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(num_in_group, dim=0) + advantages = rewards - mean_grouped_rewards + + if self.scale_rewards in ["group", "none"]: + # If self.scale_rewards = "none", we'll still log group level std + std_rewards = rewards.view(-1, num_in_group).std(dim=1) + std_rewards = std_rewards.repeat_interleave(num_in_group, dim=0) + elif self.scale_rewards == "batch": + # Compute global std + std_rewards = rewards.std().expand_as(rewards) + else: + raise ValueError( + f"Invalid value for scale_rewards: {self.scale_rewards}. Must be one of 'batch', 'group', or 'none'." + ) + + is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards)) + if self.scale_rewards != "none": + advantages = advantages / (std_rewards + 1e-4) + + # Slice to keep only the local part of the data + process_slice = slice( + self.accelerator.process_index * num_inputs_in_device, + (self.accelerator.process_index + 1) * num_inputs_in_device, + ) + all_process_advantages = advantages.clone() # keep the aggregated advantages for logging + advantages = advantages[process_slice] + + if self.num_remains_in_group is not None and mode == "train": + local_input_indices_to_keep = group_global_indices[process_slice] - self.accelerator.process_index * len( + prompts + ) # step is length of prompts + + prompt_ids = prompt_ids[local_input_indices_to_keep] + prompt_mask = prompt_mask[local_input_indices_to_keep] + completion_ids = completion_ids[local_input_indices_to_keep] + completion_mask = completion_mask[local_input_indices_to_keep] + attention_mask = attention_mask[local_input_indices_to_keep] + completion_lengths = completion_mask.sum(1) + agg_completion_lengths = self.accelerator.gather(completion_lengths) + num_items_in_batch = agg_completion_lengths.sum() + + if sampling_per_token_logps is not None: + sampling_per_token_logps = sampling_per_token_logps[local_input_indices_to_keep] + if old_per_token_logps is not None: + old_per_token_logps = old_per_token_logps[local_input_indices_to_keep] + if ref_per_token_logps is not None: + ref_per_token_logps = ref_per_token_logps[local_input_indices_to_keep] + if self.use_vllm and self.vllm_importance_sampling_correction: + importance_sampling_ratio = importance_sampling_ratio[local_input_indices_to_keep] + + # Calculate mean reward per function, but only for samples where the function was applied (non-NaN values) + for i, reward_func_name in enumerate(self.reward_func_names): + mean_rewards = torch.nanmean(rewards_per_func[:, i]).item() + self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards) + std_func_rewards = nanstd(rewards_per_func[:, i]).item() + self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_func_rewards) + rewards = (rewards_per_func * self.reward_weights.to(rewards_per_func.device).unsqueeze(0)).nansum(dim=1) + self._metrics[mode]["reward"].append(rewards.mean().item()) + self._metrics[mode]["reward_std"].append(rewards.std().item()) + self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item()) + + # Log prompt and completion texts + all_prompts_text = gather_object(prompts_text) + all_completions_text = gather_object(completions_text) + all_images = gather_object(images) if images is not None else None + if self.num_remains_in_group is not None and mode == "train": + group_global_indices_list = group_global_indices.tolist() + all_prompts_text = [all_prompts_text[i] for i in group_global_indices_list] + all_completions_text = [all_completions_text[i] for i in group_global_indices_list] + if images is not None: + all_images = [all_images[i] for i in group_global_indices_list] + + self._logs["prompt"].extend(all_prompts_text) + self._logs["completion"].extend(all_completions_text) + for i, name in enumerate(self.reward_func_names): + self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist()) + self._logs["advantages"].extend(all_process_advantages.tolist()) + + if images is not None: + self._logs["images"].extend(all_images) + + if self.use_vllm and self.vllm_importance_sampling_correction: + delta = torch.abs(old_per_token_logps - sampling_per_token_logps) + delta = delta[completion_mask.bool()] + mean_delta = torch.mean(delta) if delta.numel() > 0 else torch.tensor(0.0, device=device) + max_delta = torch.max(delta) if delta.numel() > 0 else torch.tensor(0.0, device=device) + self._metrics[mode]["sampling/sampling_logp_difference/mean"].append( + self.accelerator.gather(mean_delta).mean().item() + ) + self._metrics[mode]["sampling/sampling_logp_difference/max"].append( + self.accelerator.gather(max_delta).max().item() + ) + + flat_is_ratio = importance_sampling_ratio[completion_mask.bool()] + min_importance_sampling_ratio = ( + torch.min(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device) + ) + mean_importance_sampling_ratio = ( + torch.mean(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device) + ) + max_importance_sampling_ratio = ( + torch.max(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device) + ) + self._metrics[mode]["sampling/importance_sampling_ratio/min"].append( + nanmin(self.accelerator.gather(min_importance_sampling_ratio)).item() + ) + self._metrics[mode]["sampling/importance_sampling_ratio/mean"].append( + self.accelerator.gather(mean_importance_sampling_ratio).nanmean().item() + ) + self._metrics[mode]["sampling/importance_sampling_ratio/max"].append( + nanmax(self.accelerator.gather(max_importance_sampling_ratio)).item() + ) + + output = { + "prompt_ids": prompt_ids, + "prompt_mask": prompt_mask, + "completion_ids": completion_ids, + "completion_mask": completion_mask, + "advantages": advantages, + "num_items_in_batch": num_items_in_batch, + } + if old_per_token_logps is not None: + output["old_per_token_logps"] = old_per_token_logps + if self.use_vllm and self.vllm_importance_sampling_correction: + output["importance_sampling_ratio"] = importance_sampling_ratio + if ref_per_token_logps is not None: + output["ref_per_token_logps"] = ref_per_token_logps + if "pixel_values" in forward_kwargs: + output["pixel_values"] = forward_kwargs["pixel_values"] + if "image_grid_thw" in forward_kwargs: + output["image_grid_thw"] = forward_kwargs["image_grid_thw"] + if "pixel_attention_mask" in forward_kwargs: + output["pixel_attention_mask"] = forward_kwargs["pixel_attention_mask"] + if "image_sizes" in forward_kwargs: + output["image_sizes"] = forward_kwargs["image_sizes"] + if "token_type_ids" in forward_kwargs: + output["token_type_ids"] = forward_kwargs["token_type_ids"] + if images is not None: + output["num_images"] = num_images + return output diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gkd/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gkd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d49fe68a623fbca5fdc6cd4581464ac65d892fa9 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gkd/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .gkd_config import GKDConfig +from .gkd_trainer import GKDTrainer + + +__all__ = ["GKDConfig", "GKDTrainer"] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gkd/gkd_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gkd/gkd_config.py new file mode 100644 index 0000000000000000000000000000000000000000..4ea10761c45228f10c8acb42ce7cb48eba5eede8 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gkd/gkd_config.py @@ -0,0 +1,110 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.sft_config import SFTConfig + + +@dataclass +class GKDConfig(SFTConfig): + """ + Configuration class for [`experimental.gkd.GKDTrainer`]. + + This class includes only the parameters that are specific to GKD training. For a full list of training arguments, + please refer to the [`~transformers.TrainingArguments`] and [`SFTConfig`] documentation. + + Args: + temperature (`float`, *optional*, defaults to `0.9`): + Temperature for sampling. The higher the temperature, the more random the completions. + lmbda (`float`, *optional*, defaults to `0.5`): + Lambda parameter that controls the student data fraction (i.e., the proportion of on-policy + student-generated outputs). + beta (`float`, *optional*, defaults to `0.5`): + Interpolation coefficient between `0.0` and `1.0` of the Generalized Jensen-Shannon Divergence loss. When + beta is `0.0`, the loss is the KL divergence. When beta is `1.0`, the loss is the Inverse KL Divergence. + max_new_tokens (`int`, *optional*, defaults to `128`): + Maximum number of tokens to generate per completion. + teacher_model_name_or_path (`str`, *optional*): + Model name or path of the teacher model. If `None`, the teacher model will be the same as the model being + trained. + teacher_model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the teacher model + from a string. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. + seq_kd (`bool`, *optional*, defaults to `False`): + Seq_kd parameter that controls whether to perform Sequence-Level KD (can be viewed as supervised FT on + teacher-generated output). + """ + + _VALID_DICT_FIELDS = SFTConfig._VALID_DICT_FIELDS + ["teacher_model_init_kwargs"] + + temperature: float = field( + default=0.9, + metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."}, + ) + lmbda: float = field( + default=0.5, + metadata={ + "help": "Lambda parameter that controls the student data fraction (i.e., the proportion of on-policy " + "student-generated outputs)." + }, + ) + beta: float = field( + default=0.5, + metadata={ + "help": "Interpolation coefficient between `0.0` and `1.0` of the Generalized Jensen-Shannon Divergence " + "loss. When beta is `0.0`, the loss is the KL divergence. When beta is `1.0`, the loss is the Inverse KL " + "Divergence." + }, + ) + max_new_tokens: int = field( + default=128, + metadata={"help": "Maximum number of tokens to generate per completion."}, + ) + teacher_model_name_or_path: str | None = field( + default=None, + metadata={ + "help": "Model name or path of the teacher model. If `None`, the teacher model will be the same as the " + "model being trained." + }, + ) + teacher_model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the " + "teacher model from a string." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropouts in `model`."}, + ) + seq_kd: bool = field( + default=False, + metadata={ + "help": "Seq_kd parameter that controls whether to perform Sequence-Level KD (can be viewed as supervised " + "FT on teacher-generated output)." + }, + ) + + def __post_init__(self): + super().__post_init__() + # check lmbda and beta are in the range [0, 1] + if self.lmbda < 0.0 or self.lmbda > 1.0: + raise ValueError("lmbda must be in the range [0.0, 1.0].") + if self.beta < 0.0 or self.beta > 1.0: + raise ValueError("beta must be in the range [0.0, 1.0].") diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gkd/gkd_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gkd/gkd_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..802fac9623170ab96965c76690af9708f8ec2e87 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gkd/gkd_trainer.py @@ -0,0 +1,505 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import random +import textwrap +from collections.abc import Callable +from typing import Any + +import torch +import torch.nn as nn +import torch.nn.functional as F +from datasets import Dataset +from transformers import ( + AutoModelForCausalLM, + BaseImageProcessor, + DataCollator, + FeatureExtractionMixin, + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, +) +from transformers.trainer_utils import EvalPrediction +from transformers.utils import ModelOutput, is_liger_kernel_available, is_peft_available + +from ...models import prepare_deepspeed +from ...models.utils import _ForwardRedirection, unwrap_model_for_generation +from ...trainer.sft_trainer import SFTTrainer +from ...trainer.utils import disable_dropout_in_model +from ..utils import DataCollatorForChatML, empty_cache +from .gkd_config import GKDConfig + + +if is_peft_available(): + from peft import PeftConfig + +if is_liger_kernel_available(): + from liger_kernel.chunked_loss import LigerFusedLinearJSDLoss + + +class GKDTrainer(SFTTrainer): + """Trainer for Generalized Knowledge Distillation (GKD) of language models. + + For details on GKD, see the paper: [On-Policy Distillation of Language Models: Learning from Self-Generated + Mistakes](https://huggingface.co/papers/2306.13649). + + Args: + model ([`~transformers.PreTrainedModel`] or `torch.nn.Module` or `str`, *optional*): + Model to be trained, or the string identifier of the model to be instantiated from a pretrained model. + teacher_model ([`~transformers.PreTrainedModel`] or `torch.nn.Module` or `str`, *optional*): + Teacher model for knowledge distillation, or the string identifier of the model to be instantiated from a + pretrained model. + args ([`experimental.gkd.GKDConfig`], *optional*): + Training arguments. + data_collator ([`~transformers.DataCollator`], *optional*): + Data collator to batch samples from the dataset. It defaults to a + [`experimental.utils.DataCollatorForChatML`] using the `processing_class`. + train_dataset ([`~datasets.Dataset`], *optional*): + Dataset for training. + eval_dataset ([`~datasets.Dataset`] or `dict` of [`~datasets.Dataset`], *optional*): + Dataset for evaluation. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*): + Class to process the data. + compute_metrics (`Callable`, *optional*): + Function to compute metrics at evaluation. Must take in an [`~transformers.EvalPrediction`] and return a + dictionary string to float. + callbacks (`list` of [`~transformers.TrainerCallback`], *optional*): + Callbacks to use during training. + optimizers (`tuple` of `torch.optim.Optimizer` and `torch.optim.lr_scheduler.LambdaLR`, *optional*, defaults to `(None, None)`): + Tuple containing the optimizer and the learning rate scheduler to use for training. + preprocess_logits_for_metrics (`Callable`, *optional*): + Function to preprocess the logits before computing the metrics. Must take in the `logits` and `labels` and + return the logits to be used for metrics computation. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration to use PEFT for training. If `None`, PEFT is not used. If provided, the `model` will be + wrapped with the specified PEFT adapter. + formatting_func (`Callable`, *optional*): + Function to format the dataset. Must take in an example and return an example. + """ + + _tag_names = ["trl", "gkd"] + _name = "GKD" + _paper = { + "title": "On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes", + "id": "2306.13649", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @inproceedings{agarwal2024on-policy, + title = {{On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes}}, + author = {Rishabh Agarwal and Nino Vieillard and Yongchao Zhou and Piotr Stanczyk and Sabela Ramos Garea and Matthieu Geist and Olivier Bachem}, + year = 2024, + booktitle = {The Twelfth International Conference on Learning Representations, {ICLR} 2024, Vienna, Austria, May 7-11, 2024}, + publisher = {OpenReview.net}, + url = {https://openreview.net/forum?id=3zKtaqxLhW}, + }"""), + } + + def __init__( + self, + model: PreTrainedModel | nn.Module | str | None = None, + teacher_model: PreTrainedModel | nn.Module | str = None, + args: GKDConfig | None = None, + data_collator: DataCollator | None = None, # type: ignore + train_dataset: Dataset | None = None, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + processing_class: PreTrainedTokenizerBase + | BaseImageProcessor + | FeatureExtractionMixin + | ProcessorMixin + | None = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + peft_config: "PeftConfig | None" = None, + formatting_func: Callable | None = None, + ): + # Ensure Trainer does not drop non-signature columns used by the collator (e.g., "prompts") + args.remove_unused_columns = False + # Respect a user-provided data_collator; otherwise, provide a ChatML collator that + if data_collator is None: + data_collator = DataCollatorForChatML(tokenizer=processing_class, max_length=args.max_length) + + # Ensure SFTTrainer does not pre-process the dataset when using a ChatML collator, + # so that raw conversational fields (e.g., "messages") remain available to the collator. + if args.dataset_kwargs is None: + args.dataset_kwargs = {"skip_prepare_dataset": True} + else: + args.dataset_kwargs["skip_prepare_dataset"] = True + + # Liger fused GKD loss (JSD) + self.use_liger_gkd_loss = False + if args.use_liger_kernel: + # Match the non-Liger path: pure JSD (no hard CE component) and no temperature + # scaling, since `generalized_jsd_loss` is called without a `temperature` argument. + self.liger_jsd_loss = LigerFusedLinearJSDLoss( + beta=args.beta, + ignore_index=-100, + compiled=False, + weight_hard_loss=0.0, + weight_soft_loss=1.0, + ) + self.use_liger_gkd_loss = True + self._forward_redirection = _ForwardRedirection() + + super().__init__( + model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + peft_config=peft_config, + formatting_func=formatting_func, + ) + + if args.teacher_model_init_kwargs is None: + teacher_model_init_kwargs = {} + elif not isinstance(teacher_model, str): + raise ValueError( + "You passed teacher_model_init_kwargs to the GKDConfig, but your teacher_model is already instantiated." + ) + else: + teacher_model_init_kwargs = args.teacher_model_init_kwargs + teacher_model_init_kwargs["dtype"] = ( + teacher_model_init_kwargs["dtype"] + if teacher_model_init_kwargs["dtype"] in ["auto", None] + else getattr(torch, teacher_model_init_kwargs["dtype"]) + ) + + if isinstance(teacher_model, str): + teacher_model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + teacher_model = AutoModelForCausalLM.from_pretrained(teacher_model, **teacher_model_init_kwargs) + + # Disable dropout in the model + if args.disable_dropout: + disable_dropout_in_model(self.model) + + if self.is_deepspeed_enabled: + self.teacher_model = prepare_deepspeed(teacher_model, self.accelerator) + else: + self.teacher_model = self.accelerator.prepare_model(teacher_model, evaluation_mode=True) + + self.lmbda = args.lmbda + self.beta = args.beta + self.temperature = args.temperature + self.seq_kd = args.seq_kd + + generation_kwargs = { + "max_new_tokens": args.max_new_tokens, + "temperature": args.temperature, + "do_sample": True, + "top_k": 0, + "use_cache": False if args.gradient_checkpointing else True, + "pad_token_id": self.processing_class.pad_token_id, + } + self.generation_config = GenerationConfig(**generation_kwargs) + # Keep training-specific generation kwargs to overwrite model's original generation config + self.generation_kwargs = generation_kwargs + # Set custom EOS tokens if they are specified by the model's generation + # config. This is important for models with the Llama 3 chat template, + # which use special tokens <|eot_id|> and <|eom_id|> to mark the end of + # turns or messages. + if ( + hasattr(self.model.generation_config, "eos_token_id") + and self.model.generation_config.eos_token_id is not None + ): + self.generation_config.eos_token_id = self.model.generation_config.eos_token_id + + @staticmethod + def generalized_jsd_loss( + student_logits, + teacher_logits, + labels=None, + beta=0.5, + temperature=1.0, + reduction="batchmean", + num_items_in_batch=None, + ): + """ + Compute the generalized Jensen-Shannon Divergence loss for knowledge distillation using F.kl_div. See Eq. (1) + of https://huggingface.co/papers/2306.13649 for the definition. + + Args: + student_logits: + Tensor of shape (batch_size, sequence_length, vocab_size) + teacher_logits: + Tensor of shape (batch_size, sequence_length, vocab_size) + labels: + Tensor of shape (batch_size, sequence_length) with -100 for padding tokens to ignore when computing + loss + beta: + Interpolation coefficient between 0 and 1 (default: 0.5) + temperature: + Softmax temperature (default: 1.0) + reduction: + Specifies the reduction to apply to the output (default: 'batchmean') + + Returns: + loss: Scalar tensor with the generalized JSD loss + """ + + # Apply temperature scaling + student_logits = student_logits / temperature + teacher_logits = teacher_logits / temperature + + # Compute log probabilities for student and probabilities for teacher + student_log_probs = F.log_softmax(student_logits, dim=-1) + teacher_log_probs = F.log_softmax(teacher_logits, dim=-1) + + if beta == 0: + jsd = F.kl_div(student_log_probs, teacher_log_probs, reduction="none", log_target=True) + elif beta == 1: + jsd = F.kl_div(teacher_log_probs, student_log_probs, reduction="none", log_target=True) + else: + # Compute the log of the mixture distribution + # log(a + b) = log(exp(log(a)) + exp(log(b))) -> for mixture + beta = torch.tensor(beta, dtype=student_log_probs.dtype, device=student_log_probs.device) + mixture_log_probs = torch.logsumexp( + torch.stack([student_log_probs + torch.log1p(-beta), teacher_log_probs + torch.log(beta)]), + dim=0, + ) + + # Compute KL divergences using F.kl_div + # PyTorch differs from the standard mathematical definition, so the order of the probability distributions is swapped compared to that defined in the paper. + kl_teacher = F.kl_div(mixture_log_probs, teacher_log_probs, reduction="none", log_target=True) + kl_student = F.kl_div(mixture_log_probs, student_log_probs, reduction="none", log_target=True) + + # Compute the Generalized Jensen-Shannon Divergence + jsd = beta * kl_teacher + (1 - beta) * kl_student + + # Masking + if labels is not None: + mask = labels != -100 + jsd = jsd[mask] + + # Apply reduction + if num_items_in_batch is not None: + # Normalize by the global number of valid tokens for gradient-accumulation-correct loss (see issue #4719). + jsd_sum = jsd.sum() + if isinstance(num_items_in_batch, torch.Tensor): + num_items_in_batch = num_items_in_batch.to(jsd_sum.device) + return jsd_sum / num_items_in_batch + if reduction == "batchmean": + # clamp_min(1) avoids 0/0 -> nan when a sample has no unmasked positions + # (e.g. completion fully truncated). jsd[mask] is empty -> jsd.sum() == 0, + # so 0/1 == 0 with a valid grad path. + denom = mask.sum().clamp_min(1) if labels is not None else max(jsd.size(0), 1) + return jsd.sum() / denom + elif reduction == "sum": + return jsd.sum() + elif reduction == "mean": + return jsd.mean() + else: + return jsd + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + if self.use_liger_gkd_loss: + # Forward only through the base models (avoid lm_head to save memory). + # Route through the DDP/FSDP wrapper via _forward_redirection so that + # DDP.forward() is called and prepare_for_backward() fires correctly. + unwrapped_student = self.accelerator.unwrap_model(model) + student_outputs = self._forward_redirection( + model, unwrapped_student, self._liger_student_forward, unwrapped_student, inputs + ) + + self.teacher_model.eval() + unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model) + if hasattr(unwrapped_teacher, "get_decoder") and unwrapped_teacher.get_decoder() is not None: + base_teacher = unwrapped_teacher.get_decoder() + else: + base_teacher = getattr( + unwrapped_teacher, getattr(unwrapped_teacher, "base_model_prefix", "model"), unwrapped_teacher + ) + with torch.no_grad(): + teacher_outputs = base_teacher( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + use_cache=False, + ) + + # hidden states (shifted) + student_hidden = student_outputs.last_hidden_state[:, :-1] + teacher_hidden = teacher_outputs.last_hidden_state[:, :-1] + + # Release teacher outputs; keep student_outputs for return_outputs + del teacher_outputs + + # labels mask and labels (shifted) + labels_mask = inputs["labels"] != -100 + masked_input_ids = torch.where( + labels_mask, inputs["input_ids"], torch.full_like(inputs["input_ids"], -100) + ) + true_labels = masked_input_ids[:, 1:].contiguous() + + # Release intermediate tensors + del labels_mask, masked_input_ids + + # heads + student_head = unwrapped_student.get_output_embeddings() + teacher_head = unwrapped_teacher.get_output_embeddings() + + # liger fused jsd loss + loss = self.liger_jsd_loss( + student_input=student_hidden, + student_weight=student_head.weight, + teacher_input=teacher_hidden, + teacher_weight=teacher_head.weight, + true_labels=true_labels, + student_bias=getattr(student_head, "bias", None), + teacher_bias=getattr(teacher_head, "bias", None), + ) + + # The Liger JSD loss normalizes by the local number of valid tokens. Under gradient accumulation we want + # the global normalization, so rescale by `num_valid_local / num_items_in_batch`. + if num_items_in_batch is not None: + num_valid_local = (true_labels != -100).sum().clamp_min(1) + if isinstance(num_items_in_batch, torch.Tensor): + num_items_in_batch = num_items_in_batch.to(loss.device) + loss = loss * num_valid_local / num_items_in_batch + + # Release hidden states after loss computation + del student_hidden, teacher_hidden, true_labels + empty_cache() + if return_outputs: + return (loss, ModelOutput(logits=None, last_hidden_state=student_outputs.last_hidden_state)) + else: + return loss + else: + # compute student output + student_outputs = model( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + ) + + # compute teacher output in eval mode + self.teacher_model.eval() + with torch.no_grad(): + teacher_outputs = self.teacher_model( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + ) + + # Standard causal shift: logits at position i predict the token at i + 1. The `labels != -100` mask + # inside `generalized_jsd_loss` already excludes prompt (and padding) positions, so we do not slice by + # prompt length. Slicing by `inputs["prompts"].shape[1]` (the batch-max prompt width) would drop real + # completion tokens for samples whose prompt is shorter than the batch maximum, since `labels` is padded + # to the full-sequence width independently of `prompts`. + shifted_student_logits = student_outputs.logits[:, :-1, :] + shifted_teacher_logits = teacher_outputs.logits[:, :-1, :] + shifted_labels = inputs["labels"][:, 1:] + + # compute loss + loss = self.generalized_jsd_loss( + student_logits=shifted_student_logits, + teacher_logits=shifted_teacher_logits, + labels=shifted_labels, + beta=self.beta, + num_items_in_batch=num_items_in_batch, + ) + + # empty cache + empty_cache() + + # Return loss + return (loss, student_outputs) if return_outputs else loss + + def _liger_student_forward(self, student, inputs): + """Decoder-only forward used by the Liger JSD path (skips lm_head to save memory).""" + if hasattr(student, "get_decoder") and student.get_decoder() is not None: + decoder = student.get_decoder() + else: + decoder = getattr(student, getattr(student, "base_model_prefix", "model"), student) + return decoder( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + use_cache=False, + ) + + @staticmethod + def generate_on_policy_outputs(model, inputs, generation_config, pad_token_id=None): + # Generate output with respect to the prompt-only + generated_outputs = model.generate( + input_ids=inputs["prompts"], + attention_mask=inputs.get("prompt_attention_mask", None), + generation_config=generation_config, + return_dict_in_generate=True, + ) + + # Get the generated token IDs + generated_tokens = generated_outputs.sequences + # Calculate new attention mask + new_attention_mask = torch.ones_like(generated_tokens) + new_labels = generated_tokens.clone() + + # If there's pad_token_id, set attention mask to 0 for padding tokens + if pad_token_id is not None: + new_labels[new_labels == pad_token_id] = -100 + new_attention_mask[generated_tokens == pad_token_id] = 0 + + # Mask the prompt so only the generated completion contributes to the loss. `generate` echoes + # the prompt back as the first `prompt_length` columns, so masking them with -100 matches the + # collator convention (`labels[:len(prompt)] = -100`) that `compute_loss` relies on. + prompt_length = inputs["prompts"].shape[1] + new_labels[:, :prompt_length] = -100 + + return generated_tokens, new_attention_mask, new_labels + + def training_step( + self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None + ) -> torch.Tensor: + """ + Perform a training step for the Generalized Knowledge Distillation (GKD) model. + + This method implements the on-policy learning approach described in the GKD paper. With probability + `self.lmbda`, it generates new responses using the student model, which are then used for training instead of + the original inputs. + """ + if random.random() <= self.lmbda: + with ( + unwrap_model_for_generation( + model, + self.accelerator, + generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762 + ) as unwrapped_model + ): + new_input_ids, new_attention_mask, new_labels = self.generate_on_policy_outputs( + unwrapped_model, inputs, self.generation_config, self.processing_class.pad_token_id + ) + inputs["input_ids"] = new_input_ids + inputs["attention_mask"] = new_attention_mask + inputs["labels"] = new_labels + elif self.seq_kd: + with ( + unwrap_model_for_generation( + self.teacher_model, + self.accelerator, + generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762 + ) as unwrapped_model + ): + new_input_ids, new_attention_mask, new_labels = self.generate_on_policy_outputs( + unwrapped_model, inputs, self.generation_config, self.processing_class.pad_token_id + ) + inputs["input_ids"] = new_input_ids + inputs["attention_mask"] = new_attention_mask + inputs["labels"] = new_labels + + loss = super().training_step(model, inputs, num_items_in_batch) + return loss diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gmpo/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gmpo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d97a396205fd4bbeae2719fbda347230bace374d --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gmpo/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .gmpo_config import GMPOConfig +from .gmpo_trainer import GMPOTrainer diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gmpo/gmpo_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gmpo/gmpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..8eb06749e2c98258b9ee66fe6ccbb10d8dcc13a3 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gmpo/gmpo_config.py @@ -0,0 +1,47 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field + +from ...trainer.grpo_config import GRPOConfig + + +@dataclass +class GMPOConfig(GRPOConfig): + # docstyle-ignore + r""" + Configuration class for the [`GMPOTrainer`]. + + [`GMPOConfig`] inherits every parameter from [`GRPOConfig`]; it only changes the meaning and default of the + clipping range. In GMPO, clipping is applied to the per-token *log*-importance ratios (i.e. in log space) before + the geometric mean is taken, so `epsilon` and `epsilon_high` are expressed in log space: the effective ratio + clipping range is `(exp(-epsilon), exp(epsilon_high))`. The [GMPO paper](https://huggingface.co/papers/2507.20673) + recommends a markedly wider range than GRPO/DAPO, `(exp(-0.4), exp(0.4))`, to encourage exploration. + + Parameters: + epsilon (`float`, *optional*, defaults to `0.4`): + Lower-bound clipping value, expressed in log space. The lower bound of the per-token importance ratio is + `exp(-epsilon)`. + epsilon_high (`float`, *optional*): + Upper-bound clipping value, expressed in log space. If `None`, it defaults to the value of `epsilon`. The + upper bound of the per-token importance ratio is `exp(epsilon_high)`. + """ + + epsilon: float = field( + default=0.4, + metadata={ + "help": "Lower-bound clipping value, expressed in log space. The lower bound of the per-token importance " + "ratio is exp(-epsilon). GMPO recommends 0.4." + }, + ) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gmpo/gmpo_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gmpo/gmpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..806da1cb57872c53f1d83c2eba6b7c53a73998f7 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gmpo/gmpo_trainer.py @@ -0,0 +1,152 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch + +from ...trainer.grpo_trainer import GRPOTrainer +from ...trainer.utils import get_config_model_id, nanmax, nanmin +from .gmpo_config import GMPOConfig + + +class GMPOTrainer(GRPOTrainer): + """ + Trainer for Geometric-Mean Policy Optimization (GMPO). + + GMPO (https://huggingface.co/papers/2507.20673) is a GRPO variant that maximizes the *geometric* mean of the + token-level importance ratios instead of the arithmetic mean. Because the geometric mean is far less sensitive to + outlier ratios, the policy update is more stable and a much wider clipping range can be used. + + The only change w.r.t. [`GRPOTrainer`] is `_compute_loss`. Everything else (generation, reward computation, weight + syncing, metric logging) is inherited unchanged + """ + + _tag_names = ["trl", "gmpo"] + + def __init__(self, model, reward_funcs, args=None, **kwargs): + if args is None: + model_name = model if isinstance(model, str) else get_config_model_id(model.config) + args = GMPOConfig(f"{model_name.split('/')[-1]}-GMPO") + + super().__init__(model, reward_funcs, args=args, **kwargs) + + def _compute_loss(self, model, inputs): + # Compute the per-token log probabilities for the model + prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"] + completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"] + input_ids = torch.cat([prompt_ids, completion_ids], dim=1) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + mask = completion_mask if "tool_mask" not in inputs else completion_mask * inputs["tool_mask"] + + # Compute the per_token_logps and the entropy at each position in the completion + per_token_logps, entropies, _ = self._get_per_token_logps_and_entropies( + model, + input_ids, + attention_mask, + logits_to_keep, + compute_entropy=True, + pixel_values=inputs.get("pixel_values"), + image_grid_thw=inputs.get("image_grid_thw"), + num_images=inputs.get("num_images"), + pixel_attention_mask=inputs.get("pixel_attention_mask"), + image_sizes=inputs.get("image_sizes"), + token_type_ids=inputs.get("token_type_ids"), + mm_token_type_ids=inputs.get("mm_token_type_ids"), + image_position_ids=inputs.get("image_position_ids"), + ) + + if self.top_entropy_quantile < 1.0: + entropy_mask = self.get_high_entropy_mask(entropies, mask, 1 - self.top_entropy_quantile) + else: + entropy_mask = None + + advantages = inputs["advantages"] + # When num_iterations == 1 and steps_per_generation <= gradient_accumulation_steps, + # old_per_token_logps == per_token_logps, so we skip its computation and use per_token_logps.detach() instead. + old_per_token_logps = inputs.get("old_per_token_logps") + old_per_token_logps = per_token_logps.detach() if old_per_token_logps is None else old_per_token_logps + + # GMPO Objective + # Per-token log importance ratio + log_ratio = per_token_logps - old_per_token_logps + + # Token-level clipping, performed in *log space* for numerical stability. The clip range in + # ratio space is (exp(-epsilon_low), exp(epsilon_high)); the paper recommends exp(±0.4), markedly wider than + # GRPO/DAPO, to encourage exploration. + clamped_log_ratio = torch.clamp(log_ratio, min=-self.epsilon_low, max=self.epsilon_high) + + # sign-aware, one-sided clipping = PPO's trust-region "min" trick written in log-spaces: + advantages_col = advantages.unsqueeze(1) + clipped_log_ratio = torch.where( + advantages_col > 0, + torch.minimum(log_ratio, clamped_log_ratio), + torch.maximum(log_ratio, clamped_log_ratio), + ) + + # Optionally drop low-entropy tokens from the geometric mean + seq_mask = mask * entropy_mask if entropy_mask is not None else mask + + # Geometric mean of the clipped token ratios = exp(mean of clipped log-ratios over valid tokens). The 1/|o_i| + # exponent is the geometric-mean normalization; the paper's ablation shows it is essential. + log_importance_weights = (clipped_log_ratio * seq_mask).sum(-1) / seq_mask.sum(-1).clamp(min=1.0) # (B,) + coef = torch.exp(log_importance_weights) # (B,) sequence-level (geometric-mean) importance weight + + per_sequence_loss = -coef * advantages # (B,) + + # KL regularization toward the reference model (optional; sequence-averaged to match GMPO's sequence-level + # objective). Disabled by default (beta == 0) + if self.beta != 0.0: + ref_per_token_logps = inputs["ref_per_token_logps"] + per_token_kl = ( + torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1 + ) + seq_kl = (per_token_kl * mask).sum(-1) / mask.sum(-1).clamp(min=1.0) # (B,) + per_sequence_loss = per_sequence_loss + self.beta * seq_kl + + # GMPO aggregates with a plain mean over sequences, per token-norm + # already lives inside the geometric mean. + mode = "train" if self.model.training else "eval" + loss = per_sequence_loss.mean() + normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval + loss = loss / normalizer + + # logging + completion_token_count = mask.sum().clamp(min=1.0) + + if self.beta != 0.0: + mean_kl = (per_token_kl * mask).sum() / completion_token_count + self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item()) + + mean_entropy = (entropies * mask).sum() / completion_token_count + self._metrics[mode]["entropy"].append(self.accelerator.gather(mean_entropy).nanmean().item()) + + # Fraction of the tokens pushed into the clipped region, in log-space. + is_high_clipped = (log_ratio > self.epsilon_high) & (advantages_col > 0) + is_low_clipped = (log_ratio < -self.epsilon_low) & (advantages_col < 0) + is_region_clipped = is_high_clipped | is_low_clipped + + low_clip = (is_low_clipped.float() * mask).sum() / completion_token_count + high_clip = (is_high_clipped.float() * mask).sum() / completion_token_count + clip_ratio = (is_region_clipped.float() * mask).sum() / completion_token_count + + gathered_low_clip = self.accelerator.gather(low_clip) + self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item()) + self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item()) + gathered_high_clip = self.accelerator.gather(high_clip) + self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item()) + self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item()) + gathered_clip_ratio = self.accelerator.gather(clip_ratio) + self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item()) + + return loss diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gold/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gold/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9c2a8c1149130a77081ed794d02c7d7629d265bb --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gold/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .gold_config import GOLDConfig +from .gold_trainer import GOLDTrainer + + +__all__ = ["GOLDConfig", "GOLDTrainer"] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gold/gold_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gold/gold_config.py new file mode 100644 index 0000000000000000000000000000000000000000..54d235ae4734075999deb0425a225fc8258555f4 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gold/gold_config.py @@ -0,0 +1,503 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.sft_config import SFTConfig + + +@dataclass +class GOLDConfig(SFTConfig): + # docstyle-ignore + r""" + Configuration class for [`GOLDTrainer`]. + + This class includes only the parameters that are specific to GOLD training. For a full list of training arguments, + please refer to the [`~transformers.TrainingArguments`] and [`SFTConfig`] documentation. + + Args: + > Parameters that control generation and the training loop + + temperature (`float`, *optional*, defaults to `0.9`): + Temperature for sampling. The higher the temperature, the more random the completions. + top_p (`float`, *optional*, defaults to `0.95`): + If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to + `top_p` or higher are kept for generation. + top_k (`int`, *optional*, defaults to `0`): + Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is + disabled and all tokens are considered. + lmbda (`float`, *optional*, defaults to `0.5`): + Lambda parameter that controls the student data fraction (i.e., the proportion of on-policy + student-generated outputs). + beta (`float`, *optional*, defaults to `0.5`): + Interpolation coefficient between `0.0` and `1.0` of the Generalized Jensen-Shannon Divergence loss. When + beta is `0.0`, the loss is the KL divergence. When beta is `1.0`, the loss is the Inverse KL Divergence. + max_completion_length (`int`, *optional*, defaults to `128`): + Maximum number of tokens to generate per completion. + teacher_model_name_or_path (`str`, *optional*): + Model name or path of the teacher model. If `None`, the teacher model will be the same as the model being + trained. + teacher_model_revision (`str` or `None`, *optional*, defaults to `None`): + Model revision of the teacher model (e.g., branch name, tag, or commit hash). If `None`, the default + revision is used. + teacher_model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the teacher model + from a string. + teacher_tokenizer_name_or_path (`str`, *optional*): + Tokenizer name or path for the teacher model. If None when using ULD loss, will use the same tokenizer as + the student model (not recommended for cross-tokenizer distillation). + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. + seq_kd (`bool`, *optional*, defaults to `False`): + Seq_kd parameter that controls whether to perform Sequence-Level KD (can be viewed as supervised FT on + teacher-generated output). + num_generations (`int`, *optional*, defaults to `1`): + Number of generations per prompt. Each prompt is repeated this many times in the generation batch. + generation_batch_size (`int` or `None`, *optional*, defaults to `None`): + Number of unique prompts per worker per optimizer step. If `None`, it is computed from + `(per_device_train_batch_size * gradient_accumulation_steps) // num_generations`. + > Parameters that control the ULD loss + + use_uld_loss (`bool`, *optional*, defaults to `False`): + Whether to use Universal Logit Distillation (ULD) loss instead of Generalized Jensen-Shannon Divergence + loss. + use_extended_uld (`bool`, *optional*, defaults to `True`): + Whether to enable extended ULD alignment that uses tokenizers to align and merge token probabilities + across student and teacher tokenizations. When `True`, the trainer will compute token mappings and merge + probabilities for split tokens; when `False`, ULD will use simple positional truncation like in the + original ULD paper. + uld_use_hybrid_loss (`bool`, *optional*, defaults to `False`): + Whether to use a hybrid loss that combines ULD loss and JSD loss. When `True`, the final loss is a + combination of JSD for known token mappings and ULD for unknown token mappings. + uld_hybrid_matched_weight (`float` or `None`, *optional*): + Weight for the matched token loss component when using hybrid ULD + JSD loss. This weight scales the JSD + loss computed over tokens that have a direct mapping between student and teacher tokenizations. If `None`, + uses adaptive weighting based on vocabulary overlap. Must be set together with + `uld_hybrid_unmatched_weight` (both `None` or both `float`). + uld_hybrid_unmatched_weight (`float` or `None`, *optional*): + Weight for the unmatched token loss component when using hybrid ULD + JSD loss. This weight scales the ULD + loss computed over tokens that do not have a direct mapping between student and teacher tokenizations. If + `None`, uses adaptive weighting based on vocabulary overlap. Must be set together with + `uld_hybrid_matched_weight` (both `None` or both `float`). + uld_crossentropy_weight (`float`, *optional*, defaults to `0.0`): + Weight for the cross-entropy loss component in ULD loss. If 0, only ULD distillation loss is used. + uld_distillation_weight (`float`, *optional*, defaults to `1.0`): + Weight for the distillation loss component in ULD loss. + uld_student_temperature (`float`, *optional*, defaults to `1.0`): + Temperature for student logits in ULD loss computation. + uld_teacher_temperature (`float`, *optional*, defaults to `1.0`): + Temperature for teacher logits in ULD loss computation. + uld_skip_student_eos (`bool`, *optional*, defaults to `True`): + Whether to skip EOS token for student in ULD loss computation. + uld_skip_teacher_eos (`bool`, *optional*, defaults to `True`): + Whether to skip EOS token for teacher in ULD loss computation. + > Parameters that control vLLM integration + + use_vllm (`bool`, *optional*, defaults to `False`): + Whether to use vLLM for generating completions from the student model. Requires `vllm` to be installed. + vllm_mode (`str`, *optional*, defaults to `"colocate"`): + Mode for student vLLM integration. Either `"server"` (connect to a running TRL vLLM server) or `"colocate"` + (run vLLM in the same process). + vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`): + Host of the vLLM server for the student model (if `vllm_mode="server"`). + vllm_server_port (`int`, *optional*, defaults to `8001`): + Port of the vLLM server for the student model (if `vllm_mode="server"`). + vllm_server_timeout (`float`, *optional*, defaults to `240.0`): + Timeout for connecting to the student vLLM server (if `vllm_mode="server"`). + vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.9`): + GPU memory utilization for the colocated student vLLM engine (if `vllm_mode="colocate"`). It is recommended + to set this to a low value if the student and teacher models share the same GPU. + vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`): + Tensor parallel size for the colocated student vLLM engine (if `vllm_mode="colocate"`). + vllm_structured_outputs_regex (`str`, *optional*): + Regex for vLLM structured outputs for the student model. + vllm_server_base_url (`str`, *optional*): + Base URL for the vLLM server (e.g., `"http://localhost:8001"`). If provided, `vllm_server_host` and + `vllm_server_port` are ignored. + vllm_group_port (`int`, *optional*, defaults to `51216`): + Port for the vLLM weight-update group (NCCL communicator). Unless the port is occupied, there is no need to + change it. + vllm_max_model_length (`int`, *optional*): + Maximum model sequence length for the colocated vLLM engine when `vllm_mode="colocate"`. Defaults to the + model's maximum context length. + vllm_model_impl (`str`, *optional*, defaults to `"vllm"`): + Model implementation backend to use in vLLM. Use `"vllm"` (default) or `"transformers"`. + vllm_sync_frequency (`int`, *optional*, defaults to `1`): + Frequency (in training steps) to synchronize student model weights to vLLM engine. Set to 1 to sync after + every step. + vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`): + Enable vLLM sleep mode to offload student weights/cache during the optimizer step. Keeps GPU memory usage + low, but waking the engine adds host–device transfer latency. + + > Parameters that control logging + + log_completions (`bool`, *optional*, defaults to `False`): + Whether to log a sample of (prompt, completion) pairs every `logging_steps` steps. If `rich` is installed, + it prints the sample. If `wandb` logging is enabled, it logs it to `wandb`. + log_completions_steps (`int`, *optional*, defaults to `100`): + Number of steps between logging (prompt, completion) pairs. Only used if `log_completions` is set to + `True`. + num_completions_to_print (`int` or `None`, *optional*): + Number of completions to print with `rich`. If `None`, all completions are logged. + wandb_log_unique_prompts (`bool`, *optional*, defaults to `True`): + Whether to log the unique prompts to wandb. This will create a new run for each unique prompt. + callbacks (`list[str]`, *optional*, defaults to `[]`): + The callbacks to run during training. + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `learning_rate`: Defaults to `1e-7` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = SFTConfig._VALID_DICT_FIELDS + ["teacher_model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=1e-7, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + # GOLD-specific parameters + temperature: float = field( + default=0.9, + metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."}, + ) + top_p: float = field( + default=0.95, + metadata={ + "help": "If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to " + "`top_p` or higher are kept for generation." + }, + ) + top_k: int = field( + default=0, + metadata={ + "help": "Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, " + "top-k-filtering is disabled and all tokens are considered." + }, + ) + lmbda: float = field( + default=0.5, + metadata={ + "help": "Lambda parameter that controls the student data fraction (i.e., the proportion of on-policy " + "student-generated outputs)." + }, + ) + beta: float = field( + default=0.5, + metadata={ + "help": "Interpolation coefficient between `0.0` and `1.0` of the Generalized Jensen-Shannon Divergence " + "loss. When beta is `0.0`, the loss is the KL divergence. When beta is `1.0`, the loss is the Inverse KL " + "Divergence." + }, + ) + max_completion_length: int = field( + default=128, + metadata={"help": "Maximum number of tokens to generate per completion."}, + ) + teacher_model_name_or_path: str | None = field( + default=None, + metadata={ + "help": "Model name or path of the teacher model. If `None`, the teacher model will be the same as the " + "model being trained." + }, + ) + teacher_model_revision: str | None = field( + default=None, + metadata={ + "help": "Model revision of the teacher model (e.g., branch name, tag, or commit hash). If `None`, the " + "default revision is used." + }, + ) + teacher_model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the " + "teacher model from a string." + }, + ) + teacher_tokenizer_name_or_path: str | None = field( + default=None, + metadata={ + "help": "Tokenizer name or path for the teacher model. If None when using ULD loss, will use the same " + "tokenizer as the student model (not recommended for cross-tokenizer distillation)." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropouts in `model`."}, + ) + seq_kd: bool = field( + default=False, + metadata={ + "help": "Seq_kd parameter that controls whether to perform Sequence-Level KD (can be viewed as supervised " + "FT on teacher-generated output)." + }, + ) + num_generations: int = field( + default=1, + metadata={ + "help": "Number of generations per prompt. Increasing this will decrease the number of unique prompts per optimization step." + }, + ) + generation_batch_size: int | None = field( + default=None, + metadata={ + "help": "Number of unique prompts per worker per optimizer step. " + "If None, computed from (per_device_train_batch_size * gradient_accumulation_steps) // num_generations." + }, + ) + + # ULD Loss parameters + use_uld_loss: bool = field( + default=False, + metadata={ + "help": "Whether to use Universal Logit Distillation (ULD) loss instead of Generalized Jensen-Shannon Divergence loss." + }, + ) + use_extended_uld: bool = field( + default=True, + metadata={ + "help": ( + "Whether to enable extended ULD alignment that uses tokenizers to align and merge token " + "probabilities across student and teacher tokenizations. When True, the trainer will compute " + "token mappings and merge probabilities for split tokens; when False, ULD will use simple " + "positional truncation like in the original ULD paper." + ) + }, + ) + uld_use_hybrid_loss: bool = field( + default=False, + metadata={ + "help": ( + "Whether to use a hybrid loss that combines ULD loss and JSD loss. When True, the final loss is a " + "a combination of JSD for known token mappings and ULD for unknown token mappings." + ) + }, + ) + uld_hybrid_matched_weight: float | None = field( + default=None, + metadata={ + "help": ( + "Weight for the matched token loss component when using hybrid ULD + JSD loss. This weight scales " + "the JSD loss computed over tokens that have a direct mapping between student and teacher " + "tokenizations. If None, uses adaptive weighting based on vocabulary overlap. Must be set together " + "with uld_hybrid_unmatched_weight (both None or both float)." + ) + }, + ) + uld_hybrid_unmatched_weight: float | None = field( + default=None, + metadata={ + "help": ( + "Weight for the unmatched token loss component when using hybrid ULD + JSD loss. This weight scales " + "the ULD loss computed over tokens that do not have a direct mapping between student and teacher " + "tokenizations. If None, uses adaptive weighting based on vocabulary overlap. Must be set together " + "with uld_hybrid_matched_weight (both None or both float)." + ) + }, + ) + uld_crossentropy_weight: float = field( + default=0.0, + metadata={"help": "Weight for the cross-entropy loss component in ULD loss."}, + ) + uld_distillation_weight: float = field( + default=1.0, + metadata={"help": "Weight for the distillation loss component in ULD loss."}, + ) + uld_student_temperature: float = field( + default=1.0, + metadata={"help": "Temperature for student logits in ULD loss computation."}, + ) + uld_teacher_temperature: float = field( + default=1.0, + metadata={"help": "Temperature for teacher logits in ULD loss computation."}, + ) + + uld_skip_student_eos: bool = field( + default=True, + metadata={"help": "Whether to skip EOS token for student in ULD loss computation."}, + ) + uld_skip_teacher_eos: bool = field( + default=True, + metadata={"help": "Whether to skip EOS token for teacher in ULD loss computation."}, + ) + + # vLLM parameters + use_vllm: bool = field( + default=False, + metadata={"help": "Whether to use vLLM for generating completions. Requires `vllm` to be installed."}, + ) + vllm_mode: str = field( + default="colocate", + metadata={ + "help": 'Mode for vLLM integration. Either "server" (connect to a running TRL vLLM server) or "colocate" (run vLLM in the same process).' + }, + ) + vllm_server_base_url: str | None = field( + default=None, + metadata={ + "help": 'Base URL for the vLLM server (e.g., "http://localhost:8001"). If provided, vllm_server_host and vllm_server_port are ignored.' + }, + ) + vllm_server_host: str = field( + default="0.0.0.0", + metadata={"help": 'Host of the vLLM server when `vllm_mode="server"`.'}, + ) + vllm_server_port: int = field( + default=8001, + metadata={"help": 'Port of the vLLM server when `vllm_mode="server"`.'}, + ) + vllm_server_timeout: float = field( + default=240.0, + metadata={"help": 'Timeout (in seconds) for connecting to the vLLM server when `vllm_mode="server"`.'}, + ) + vllm_group_port: int = field( + default=51216, + metadata={"help": "Port for the vLLM weight-update group (NCCL communicator)."}, + ) + vllm_gpu_memory_utilization: float = field( + default=0.9, + metadata={ + "help": 'GPU memory utilization for the colocated vLLM engine when `vllm_mode="colocate"`. Lower values reduce contention when sharing a device with the student/teacher models.' + }, + ) + vllm_tensor_parallel_size: int = field( + default=1, + metadata={"help": 'Tensor parallel size for the colocated vLLM engine when `vllm_mode="colocate"`.'}, + ) + vllm_max_model_length: int | None = field( + default=None, + metadata={ + "help": 'Maximum model sequence length for the colocated vLLM engine when `vllm_mode="colocate"`. Defaults to the model\'s maximum context length.' + }, + ) + vllm_model_impl: str = field( + default="vllm", + metadata={"help": 'Model implementation backend to use in vLLM. Use "vllm" (default) or "transformers".'}, + ) + vllm_structured_outputs_regex: str | None = field( + default=None, + metadata={"help": "Regex pattern used for vLLM structured outputs (optional)."}, + ) + vllm_sync_frequency: int = field( + default=1, + metadata={ + "help": "Frequency (in training steps) to synchronize model weights to the vLLM engine. Set to 1 to sync after every step." + }, + ) + vllm_enable_sleep_mode: bool = field( + default=False, + metadata={ + "help": "Enable vLLM sleep mode to offload student weights/cache during the optimizer step. Keeps GPU " + "memory usage low, but waking the engine adds host–device transfer latency." + }, + ) + # Parameters that control the logging + log_completions: bool = field( + default=False, + metadata={ + "help": "Whether to log a sample of (prompt, completion) pairs every `logging_steps` steps. If `rich` is " + "installed, it prints the sample. If `wandb` logging is enabled, it logs it to `wandb`." + }, + ) + log_completions_steps: int = field( + default=100, + metadata={ + "help": "Number of steps between logging (prompt, completion) pairs. Only used if `log_completions` is " + "set to `True`." + }, + ) + num_completions_to_print: int | None = field( + default=None, + metadata={"help": "Number of completions to print with `rich`. If `None`, all completions are logged."}, + ) + wandb_log_unique_prompts: bool = field( + default=True, + metadata={ + "help": ("Whether to log the unique prompts to wandb. This will create a new run for each unique prompt.") + }, + ) + callbacks: list[str] = field( + default_factory=lambda: [], + metadata={"help": "The callbacks to run during training."}, + ) + + def __post_init__(self): + super().__post_init__() + + # check lmbda and beta are in the range [0, 1] + if self.lmbda < 0.0 or self.lmbda > 1.0: + raise ValueError("lmbda must be in the range [0.0, 1.0].") + if self.beta < 0.0 or self.beta > 1.0: + raise ValueError("beta must be in the range [0.0, 1.0].") + + # Validate that max_length is sufficient for max_completion_length + if self.max_length is not None and self.max_completion_length >= self.max_length: + raise ValueError( + f"max_completion_length ({self.max_completion_length}) must be smaller than max_length ({self.max_length}) " + f"to leave room for the prompt. Consider increasing max_length or reducing max_completion_length." + ) + + if self.num_generations < 1: + raise ValueError(f"num_generations must be at least 1, got {self.num_generations}.") + local_sequence_batch_size = self.per_device_train_batch_size * self.gradient_accumulation_steps + if self.generation_batch_size is None: + self.generation_batch_size = local_sequence_batch_size // self.num_generations + if self.generation_batch_size < 1: + raise ValueError( + f"generation_batch_size must be at least 1. Got generation_batch_size={self.generation_batch_size}." + ) + if self.generation_batch_size * self.num_generations != local_sequence_batch_size: + raise ValueError( + "generation_batch_size and num_generations must exactly partition the local optimizer-step batch. " + "Expected generation_batch_size * num_generations == per_device_train_batch_size * " + f"gradient_accumulation_steps, got {self.generation_batch_size} * {self.num_generations} != " + f"{self.per_device_train_batch_size} * {self.gradient_accumulation_steps}." + ) + if self.num_generations > 1 and self.lmbda < 1.0: + warnings.warn( + f"num_generations={self.num_generations} with lmbda={self.lmbda} means off-policy batches include " + f"{self.num_generations} copies of each sample; consider lmbda=1.0 when num_generations > 1.", + UserWarning, + stacklevel=2, + ) + + # Validate ULD parameters + if self.use_uld_loss: + if self.uld_crossentropy_weight < 0.0: + raise ValueError("uld_crossentropy_weight must be non-negative.") + if self.uld_distillation_weight < 0.0: + raise ValueError("uld_distillation_weight must be non-negative.") + if self.uld_student_temperature <= 0.0: + raise ValueError("uld_student_temperature must be positive.") + if self.uld_teacher_temperature <= 0.0: + raise ValueError("uld_teacher_temperature must be positive.") + + # Validate hybrid loss weights - both must be None or both must be set + if self.uld_use_hybrid_loss: + if (self.uld_hybrid_matched_weight is None) != (self.uld_hybrid_unmatched_weight is None): + raise ValueError( + "uld_hybrid_matched_weight and uld_hybrid_unmatched_weight must both be None (for adaptive " + "weighting) or both be set to numeric values. Got uld_hybrid_matched_weight=" + f"{self.uld_hybrid_matched_weight} and uld_hybrid_unmatched_weight=" + f"{self.uld_hybrid_unmatched_weight}." + ) + if self.uld_hybrid_matched_weight is not None: + if self.uld_hybrid_matched_weight < 0.0: + raise ValueError("uld_hybrid_matched_weight must be non-negative.") + if self.uld_hybrid_unmatched_weight < 0.0: + raise ValueError("uld_hybrid_unmatched_weight must be non-negative.") diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gold/gold_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gold/gold_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..8c66fdfbcd82682616752b0a233be8c44f215596 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gold/gold_trainer.py @@ -0,0 +1,2043 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import random +import textwrap +from collections import defaultdict, deque +from collections.abc import Callable +from contextlib import nullcontext +from functools import partial +from itertools import takewhile +from typing import Any, Optional + +import torch +import torch.distributed as dist +import torch.nn as nn +import torch.nn.functional as F +from accelerate import PartialState +from accelerate.utils import DistributedType, broadcast_object_list, gather_object +from datasets import Dataset, IterableDataset +from torch.utils.data import DataLoader +from transformers import AutoTokenizer, TrainerCallback +from transformers.data.data_collator import DataCollator +from transformers.feature_extraction_utils import FeatureExtractionMixin +from transformers.generation.configuration_utils import GenerationConfig +from transformers.image_processing_utils import BaseImageProcessor +from transformers.integrations.integration_utils import is_wandb_available +from transformers.modeling_utils import PreTrainedModel +from transformers.processing_utils import ProcessorMixin +from transformers.tokenization_utils_base import PreTrainedTokenizerBase +from transformers.trainer_utils import EvalPrediction, seed_worker +from transformers.utils import is_datasets_available, is_liger_kernel_available, is_peft_available, is_rich_available + +from ...data_utils import is_conversational, maybe_convert_to_chatml, pack_dataset +from ...extras.profiling import profiling_decorator +from ...generation.vllm_generation import VLLMGeneration +from ...import_utils import is_vllm_available +from ...models import prepare_deepspeed +from ...models.utils import _ForwardRedirection, unwrap_model_for_generation +from ...trainer.sft_trainer import SFTTrainer +from ...trainer.utils import ( + RepeatSampler, + create_model_from_path, + disable_dropout_in_model, + pad, + split_tensor_dict, +) +from ..utils import ( + DataCollatorForChatML, + empty_cache, + encode_with_byte_offsets, + pad_byte_offsets, + piece_byte_len, +) +from .gold_config import GOLDConfig + + +if is_peft_available(): + from peft import PeftConfig + +if is_wandb_available(): + import wandb + + +if is_liger_kernel_available(): + from liger_kernel.chunked_loss import LigerFusedLinearJSDLoss + +if is_rich_available(): + from rich.console import Console + from rich.panel import Panel + from rich.table import Table + from rich.text import Text + + +def print_prompt_completions_sample_uld( + prompts: list[str], + completions: list[str], + step: int, + num_samples: int = None, +) -> None: + """ + Print out a sample of model completions to the console. + + This function creates a nicely formatted table showing prompt-completion pairs, useful for monitoring model outputs + during training. It requires the `rich` library to be installed. + + Args: + prompts (`list[str]`): + List of prompts. + completions (`list[str]`): + List of completions corresponding to the prompts. + step (`int`): + Current training step number, used in the output title. + num_samples (`int` or `None`, *optional*, defaults to `None`): + Number of random samples to display. If `None` (default), all items will be displayed. + + Example: + ```python + >>> from trl.experimental.gold.gold_trainer import print_prompt_completions_sample_uld + + >>> prompts = ["The sky is", "The sun is"] + >>> completions = [" blue.", " in the sky."] + >>> print_prompt_completions_sample_uld(prompts, completions, 42) + ╭─────────── Step 42 ───────────╮ + │ ┏━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓ │ + │ ┃ Prompt ┃ Completion ┃ │ + │ ┡━━━━━━━━━━━━╇━━━━━━━━━━━━━━┩ │ + │ │ The sky is │ blue. │ │ + │ ├────────────┼──────────────┤ │ + │ │ The sun is │ in the sky. │ │ + │ └────────────┴──────────────┘ │ + ╰───────────────────────────────╯ + ``` + """ + if not is_rich_available(): + raise ImportError( + "The function `print_prompt_completions_sample_uld` requires the `rich` library. Please install it with " + "`pip install rich`." + ) + console = Console() + table = Table(show_header=True, header_style="bold white", expand=True) + + # Add columns + table.add_column("Prompt", style="bright_yellow") + table.add_column("Completion", style="bright_green") + + # Some basic input validation + if num_samples is not None: + if num_samples >= len(prompts): + num_samples = None + elif num_samples <= 0: + return + + # Subsample data if num_samples is specified + if num_samples is not None: + indices = random.sample(range(len(prompts)), num_samples) + prompts = [prompts[i] for i in indices] + completions = [completions[i] for i in indices] + + for i in range(len(prompts)): + table.add_row(Text(prompts[i]), Text(completions[i])) + table.add_section() # Adds a separator between rows + + panel = Panel(table, expand=False, title=f"Step {step}", border_style="bold white") + console.print(panel) + + +def build_teacher_inputs_from_texts( + tokenizer: PreTrainedTokenizerBase, + prompt_texts: list[str], + completion_texts: list[str], +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Tokenize teacher prompts/completions and produce tensors ready for GOLD loss. + + Returns ``(input_ids, labels, attention_mask, byte_offsets)``. ``byte_offsets`` is a ``[batch, seq, 2]`` tensor of + UTF-8 byte ``(start, end)`` for each token: prompt and padding positions are filled with ``(0, 0)``; completion + tokens carry offsets relative to the corresponding ``completion_text``; the appended EOS gets ``(content_len, + content_len)``. Byte offsets are derived from the fast tokenizer's char offsets via ``encode_with_byte_offsets``. + """ + + pad_token_id = tokenizer.pad_token_id + eos_token_id = tokenizer.eos_token_id + backend = tokenizer.backend_tokenizer + + prompt_token_ids = tokenizer(prompt_texts, add_special_tokens=True)["input_ids"] + completion_encs = encode_with_byte_offsets(backend, completion_texts, add_special_tokens=False) + + sequences: list[torch.Tensor] = [] + attention_masks: list[torch.Tensor] = [] + labels_list: list[torch.Tensor] = [] + offsets_list: list[list[tuple[int, int]]] = [] + + for prompt_ids, (enc_ids, enc_offs), completion_text in zip( + prompt_token_ids, completion_encs, completion_texts, strict=True + ): + # Remove trailing EOS from prompt so completions can extend cleanly + if eos_token_id is not None and prompt_ids and prompt_ids[-1] == eos_token_id: + prompt_ids = prompt_ids[:-1] + + completion_ids = list(enc_ids) + completion_offs = list(enc_offs) + content_len = len(completion_text.encode("utf-8")) + + sequence = list(prompt_ids) + completion_ids + offsets = [(0, 0)] * len(prompt_ids) + completion_offs + if eos_token_id is not None: + sequence.append(eos_token_id) + offsets.append((content_len, content_len)) + + seq_tensor = torch.tensor(sequence, dtype=torch.long) + sequences.append(seq_tensor) + attention_masks.append(torch.ones_like(seq_tensor)) + offsets_list.append(offsets) + + labels = seq_tensor.clone() + labels[: len(prompt_ids)] = -100 + if pad_token_id is not None: + labels[labels == pad_token_id] = -100 + labels_list.append(labels) + + teacher_input_ids = pad( + sequences, + padding_side="right", + padding_value=pad_token_id if pad_token_id is not None else 0, + ) + teacher_attention_mask = pad(attention_masks, padding_side="right", padding_value=0).bool() + teacher_labels = pad(labels_list, padding_side="right", padding_value=-100) + + if eos_token_id is not None: + for row in range(teacher_attention_mask.size(0)): + valid = ( + teacher_input_ids[row] != pad_token_id + if pad_token_id is not None + else teacher_attention_mask[row].bool() + ) + if valid.any(): + last_idx = valid.nonzero(as_tuple=True)[0][-1] + teacher_attention_mask[row, last_idx + 1 :] = False + + target_len = teacher_input_ids.size(1) + teacher_byte_offsets = torch.stack( + [pad_byte_offsets(offs, target_len, padding_side="right") for offs in offsets_list], + dim=0, + ) + + return teacher_input_ids, teacher_labels, teacher_attention_mask, teacher_byte_offsets + + +class ULDLoss(nn.Module): + """ + Universal Logit Distillation Loss. + """ + + def __init__(self, config: GOLDConfig, student_tokenizer=None, teacher_tokenizer=None, device=None): + super().__init__() + self.device = device + self.crossentropy_weight = config.uld_crossentropy_weight + self.distillation_weight = config.uld_distillation_weight + self.student_temperature = config.uld_student_temperature + self.teacher_temperature = config.uld_teacher_temperature + self.skip_student_eos = config.uld_skip_student_eos + self.skip_teacher_eos = config.uld_skip_teacher_eos + self.use_extended_uld = config.use_extended_uld + self.ignore_index = -100 + + # Add tokenizers for enhanced alignment + self.student_tokenizer = student_tokenizer + self.teacher_tokenizer = teacher_tokenizer + + # Hybrid ULD configuration + self.use_hybrid_loss = getattr(config, "uld_use_hybrid_loss", False) + self.hybrid_matched_weight = getattr(config, "uld_hybrid_matched_weight", None) + self.hybrid_unmatched_weight = getattr(config, "uld_hybrid_unmatched_weight", None) + self.beta = getattr(config, "beta", 1.0) # For JSD loss in hybrid matched tokens + + # Initialize vocabulary mapping for hybrid loss + self._vocab_mapping = None + self._teacher_matched_ids = None + self._student_matched_ids = None + if self.use_hybrid_loss and student_tokenizer is not None and teacher_tokenizer is not None: + self._initialize_vocabulary_mapping() + + def __call__( + self, + student_logits, + teacher_logits, + student_labels, + teacher_labels, + student_input_ids, + teacher_input_ids, + student_byte_offsets=None, + teacher_byte_offsets=None, + ): + """ + Compute ULD loss with GKD trainer interface. + + Args: + student_logits: Student model logits [batch_size, seq_len, vocab_size] + teacher_logits: Teacher model logits [batch_size, seq_len, vocab_size] + student_labels: Student target labels [batch_size, seq_len] + teacher_labels: Teacher target labels [batch_size, seq_len] + student_input_ids: Student input token IDs [batch_size, seq_len] + teacher_input_ids: Teacher input token IDs [batch_size, seq_len] + student_byte_offsets: Per-token UTF-8 byte offsets ``[batch, seq, 2]`` + from the data collator (relative to the rendered chat-template message). Required. + teacher_byte_offsets: Per-sample list of completion-relative byte + offsets (one list per batch item) from ``build_teacher_inputs_from_texts``. Required. + + Returns: + Total loss (cross-entropy + distillation) + """ + # Compute cross-entropy loss for student + if self.crossentropy_weight > 0: + shift_logits = student_logits[..., :-1, :].contiguous() + shift_labels = student_labels[..., 1:].contiguous() + loss_fct = nn.CrossEntropyLoss(ignore_index=self.ignore_index) + crossentropy_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)) + crossentropy_loss = self.crossentropy_weight * crossentropy_loss + else: + crossentropy_loss = 0.0 + + # Compute distillation loss using ULD approximation + distillation_loss = self._compute_distillation_loss( + student_logits, + teacher_logits, + student_labels, + teacher_labels, + student_input_ids, + teacher_input_ids, + student_byte_offsets=student_byte_offsets, + teacher_byte_offsets=teacher_byte_offsets, + ) + + return crossentropy_loss + distillation_loss + + def _initialize_vocabulary_mapping(self): + """Initialize vocabulary mapping for hybrid ULD loss.""" + # Computing vocabulary mapping for hybrid ULD + + student_vocab = self.student_tokenizer.get_vocab() + teacher_vocab = self.teacher_tokenizer.get_vocab() + + # Create reverse mapping for student + student_token_to_id = dict(student_vocab.items()) + + vocab_mapping = {} + teacher_matched_ids = set() + student_matched_ids = set() + + for token_str, teacher_id in teacher_vocab.items(): + if token_str in student_token_to_id: + student_id = student_token_to_id[token_str] + vocab_mapping[teacher_id] = student_id + teacher_matched_ids.add(teacher_id) + student_matched_ids.add(student_id) + + self._vocab_mapping = vocab_mapping + self._teacher_matched_ids = teacher_matched_ids + self._student_matched_ids = student_matched_ids + + max_matched_teacher_id = max(self._vocab_mapping.keys()) + self.mapping_tensor = torch.full((max_matched_teacher_id + 1,), -1, dtype=torch.long) # -1 for unmapped ids + for k, v in self._vocab_mapping.items(): + self.mapping_tensor[k] = v + if self.device is not None: + self.mapping_tensor = self.mapping_tensor.to(self.device) + + def _compute_distillation_loss( + self, + student_logits, + teacher_logits, + student_labels, + teacher_labels, + student_input_ids, + teacher_input_ids, + student_byte_offsets=None, + teacher_byte_offsets=None, + ): + """ + Compute the Universal Logit Distillation loss with token mapping. + + This version uses actual input_ids for accurate token mapping and multiplies probabilities for split tokens. + Both student_input_ids and teacher_input_ids are required for optimal alignment. + """ + # Get answer regions (same as original) + student_answer_index, student_answer_size = self._get_start_and_size_answers(student_labels) + teacher_answer_index, teacher_answer_size = self._get_start_and_size_answers(teacher_labels) + + if self.skip_student_eos: + student_answer_size = [size - 1 for size in student_answer_size] + if self.skip_teacher_eos: + teacher_answer_size = [size - 1 for size in teacher_answer_size] + + # Handle edge case where all answer sizes are 0 + if ( + not student_answer_size + or not teacher_answer_size + or max(max(student_answer_size), max(teacher_answer_size)) <= 0 + ): + return torch.zeros(1, device=student_logits.device, requires_grad=True) * student_logits.sum() * 1e-8 + + batch_size = student_logits.size(0) + distillation_losses = [] + + for i in range(batch_size): + # Get answer regions for this batch item + student_start = student_answer_index[i] + student_size = student_answer_size[i] + teacher_start = teacher_answer_index[i] + teacher_size = teacher_answer_size[i] + + if student_size <= 0 or teacher_size <= 0: + loss_i = student_logits[i].sum() * 0.0 + distillation_losses.append(loss_i) + continue + + # Extract answer logits + student_answer_logits = student_logits[i, student_start : student_start + student_size] + teacher_answer_logits = teacher_logits[i, teacher_start : teacher_start + teacher_size] + + # Convert to probabilities + student_probs = F.softmax(student_answer_logits / self.student_temperature, dim=-1) + teacher_probs = F.softmax(teacher_answer_logits / self.teacher_temperature, dim=-1) + + # Pass actual input_ids so split-token groups can multiply conditional probabilities. + student_token_ids = student_input_ids[i, student_start : student_start + student_size].tolist() + teacher_token_ids = teacher_input_ids[i, teacher_start : teacher_start + teacher_size].tolist() + + if self.use_extended_uld: + if student_byte_offsets is None or teacher_byte_offsets is None: + raise ValueError("Byte offsets are required when `use_extended_uld=True`.") + + # Both sides are completion-relative, so plain slicing gives a shared byte coordinate system. + s_answer = student_byte_offsets[i, student_start : student_start + student_size].tolist() + t_answer = teacher_byte_offsets[i, teacher_start : teacher_start + teacher_size].tolist() + student_groups, teacher_groups = self._align_by_byte_offsets(s_answer, t_answer) + # Drop degenerate pairs where either side is empty — e.g. teacher's trailing zero-width EOS at + # ``(content_len, content_len)`` paired with an empty student group merges to a zero distribution + # and inflates the loss (only reachable when ``skip_teacher_eos=False``). + paired = [(sg, tg) for sg, tg in zip(student_groups, teacher_groups, strict=False) if sg and tg] + student_groups = [sg for sg, _ in paired] + teacher_groups = [tg for _, tg in paired] + student_aligned = self._merge_probabilities_with_alignment_groups( + student_probs, student_groups, student_token_ids + ) + teacher_aligned = self._merge_probabilities_with_alignment_groups( + teacher_probs, teacher_groups, teacher_token_ids + ) + else: + min_length = min(len(student_token_ids), len(teacher_token_ids)) + student_aligned = student_probs[:min_length, :] + teacher_aligned = teacher_probs[:min_length, :] + + # Apply ULD loss computation + if self.use_hybrid_loss and self._vocab_mapping is not None: + # Use hybrid approach: direct comparison for matched tokens, sorting for unmatched + aligned_loss = self._compute_hybrid_uld_loss(student_aligned, teacher_aligned) + else: + # Original approach: sort all probabilities + student_sorted = student_aligned.sort(dim=-1, descending=True).values + teacher_sorted = teacher_aligned.sort(dim=-1, descending=True).values + + # Pad vocabularies to same size + student_vocab_size = student_sorted.size(-1) + teacher_vocab_size = teacher_sorted.size(-1) + max_vocab_size = max(student_vocab_size, teacher_vocab_size) + + if student_vocab_size < max_vocab_size: + student_sorted = F.pad(student_sorted, (0, max_vocab_size - student_vocab_size)) + if teacher_vocab_size < max_vocab_size: + teacher_sorted = F.pad(teacher_sorted, (0, max_vocab_size - teacher_vocab_size)) + + # Compute L1 distance (ULD approach) + aligned_loss = F.l1_loss(student_sorted, teacher_sorted, reduction="sum") + aligned_loss /= student_aligned.size(0) # Normalize by sequence length + distillation_losses.append(aligned_loss) + + distillation_loss = torch.stack(distillation_losses).mean() + return self.distillation_weight * distillation_loss + + @staticmethod + def _align_by_byte_offsets(s_offsets, t_offsets): + """ + Walk both byte-offset arrays, advancing the side whose current token ends earlier. A group closes when both + sides reach the same byte boundary — the points where the two tokenizers agree on a split. + """ + s_groups, t_groups = [], [] + s_start = t_start = s = t = 0 + n_s, n_t = len(s_offsets), len(t_offsets) + while s < n_s and t < n_t: + s_end, t_end = s_offsets[s][1], t_offsets[t][1] + if s_end < t_end: + s += 1 + elif s_end > t_end: + t += 1 + else: + s += 1 + t += 1 + s_groups.append(list(range(s_start, s))) + t_groups.append(list(range(t_start, t))) + s_start, t_start = s, t + if s < n_s or t < n_t: + s_groups.append(list(range(s_start, n_s))) + t_groups.append(list(range(t_start, n_t))) + return s_groups, t_groups + + def _merge_probabilities_with_alignment_groups(self, probs, alignment_groups, token_ids=None): + """ + Merge probabilities based on alignment groups with corrected conditional probability handling. + + For a group merging tokens at positions [i, i+1, ..., i+k], we compute: + P_merged(y | x) = P(y | x) × P(token_{i+1} | token_i, x) × ... × P(token_{i+k} | ..., x) + + Where: + - P(y | x) is the marginal probability distribution over all vocabulary tokens at position i + - token_{i+1}, ..., token_{i+k} are the ACTUAL tokens that were generated + - The conditional probabilities P(token_j | ..., x) are extracted as SCALARS + - y ranges over all vocabulary tokens at position i + + This ensures the probability of the actual generated sequence is correct (by the chain rule), while introducing + a known bias for counterfactual tokens (since we don't have P(token_{i+k} | y, x) for y != token_i). The merged + distribution is unnormalized but preserves correct relative probabilities. + + Args: + probs: Probability tensor [seq_len, vocab_size] + alignment_groups: List of alignment groups (each group is a list of positions to merge) + token_ids: Actual token IDs that were generated [seq_len]. REQUIRED when any group has + len(group) > 1. If None when multi-token groups exist, raises ValueError. + + Returns: + Merged probability tensor [num_groups, vocab_size] + + Raises: + ValueError: If token_ids is None when merging multi-token groups + """ + if not alignment_groups: + return probs + + # Create aligned tensor + vocab_size = probs.size(-1) + target_len = len(alignment_groups) + aligned_probs = torch.zeros(target_len, vocab_size, device=probs.device, dtype=probs.dtype) + eps = 1e-8 + + # Process each alignment group + for group_idx, group in enumerate(alignment_groups): + # Handle probability merging + if len(group) > 1: + # Multiple tokens map to this group - merge using corrected conditional probability approach + if token_ids is None: + raise ValueError( + "token_ids must be provided when merging multi-token groups. " + "This is required for mathematically correct probability merging." + ) + + # Start with the marginal distribution at the first position + first_pos = group[0] + marginal_probs = probs[first_pos] # P(y | x₀) for all y + + # For each subsequent token in the group, extract the SCALAR conditional probability + # of the actual token that was generated, and multiply + conditional_prob_product = 1.0 + for idx in group[1:]: + # Get the actual token ID that was generated at this position + actual_token_id = token_ids[idx] + # Extract its probability (scalar) + token_prob = probs[idx, actual_token_id].clamp_min(eps) + conditional_prob_product *= token_prob + + # Merge: multiply the scalar conditional prob product with the entire marginal distribution + # This gives: P(y | x_0) × P(token_1 | token_0, x) × ... × P(token_k | ..., x) + # Note: This is unnormalized, but preserves the correct joint probability for the actual sequence + merged_probs = marginal_probs * conditional_prob_product + aligned_probs[group_idx] = merged_probs + + elif len(group) == 1: + aligned_probs[group_idx] = probs[group[0]] + else: + # No tokens map to this group + aligned_probs[group_idx] = torch.zeros_like(probs[0]) + + return aligned_probs + + def _compute_hybrid_uld_loss(self, student_aligned, teacher_aligned): + """ + Compute hybrid ULD loss on aligned probability distributions. This method: + 1. Directly compares probabilities for tokens with matching vocabulary entries + 2. Uses sorting approach only for tokens with different vocabulary entries + + Args: + student_aligned: Aligned student probabilities [seq_len, student_vocab_size] + teacher_aligned: Aligned teacher probabilities [seq_len, teacher_vocab_size] + Returns: + Combined hybrid loss + """ + device = student_aligned.device + # seq_len = student_aligned.size(0) # Unused variable + student_vocab_size = student_aligned.size(-1) + teacher_vocab_size = teacher_aligned.size(-1) + + # Convert sets to sorted tensors for indexing + if self._teacher_matched_ids: + teacher_matched_indices = torch.tensor(sorted(self._teacher_matched_ids), dtype=torch.long, device=device) + student_matched_indices = self.mapping_tensor[teacher_matched_indices] + else: + teacher_matched_indices = torch.tensor([], dtype=torch.long, device=device) + student_matched_indices = torch.tensor([], dtype=torch.long, device=device) + + # Create masks for unmatched tokens + teacher_matched_mask = torch.zeros(teacher_vocab_size, dtype=torch.bool, device=device) + student_matched_mask = torch.zeros(student_vocab_size, dtype=torch.bool, device=device) + + if len(teacher_matched_indices) > 0: + teacher_matched_mask[teacher_matched_indices] = True + student_matched_mask[student_matched_indices] = True + + # 1. JSD loss for matched vocabulary tokens (direct semantic correspondence) + matched_loss = torch.tensor(0.0, device=device) + matched_token_count = 0 + if len(teacher_matched_indices) > 0: + # Extract probabilities for matched tokens + teacher_matched_probs = teacher_aligned[:, teacher_matched_indices] # [seq_len, num_matched] + student_matched_probs = student_aligned[:, student_matched_indices] # [seq_len, num_matched] + matched_token_count = teacher_matched_probs.size(-1) + + # Use JSD loss for semantically aligned tokens + # Convert probabilities back to logits for JSD computation + + # Apply generalized JSD loss to matched tokens + matched_loss = self._compute_jsd_loss_for_matched_tokens(student_matched_probs, teacher_matched_probs) + + # 2. Sorted comparison loss for unmatched vocabulary tokens + teacher_unmatched_mask = ~teacher_matched_mask + student_unmatched_mask = ~student_matched_mask + + teacher_unmatched_probs = teacher_aligned[:, teacher_unmatched_mask] # [seq_len, num_teacher_unmatched] + student_unmatched_probs = student_aligned[:, student_unmatched_mask] # [seq_len, num_student_unmatched] + + unmatched_loss = torch.tensor(0.0, device=device) + if teacher_unmatched_probs.size(-1) > 0 and student_unmatched_probs.size(-1) > 0: + # Sort unmatched probabilities + teacher_unmatched_sorted = teacher_unmatched_probs.sort(dim=-1, descending=True).values + student_unmatched_sorted = student_unmatched_probs.sort(dim=-1, descending=True).values + + # Pad to same size if needed + teacher_unmatched_size = teacher_unmatched_sorted.size(-1) + student_unmatched_size = student_unmatched_sorted.size(-1) + max_unmatched_size = max(teacher_unmatched_size, student_unmatched_size) + + if teacher_unmatched_size < max_unmatched_size: + teacher_unmatched_sorted = F.pad( + teacher_unmatched_sorted, (0, max_unmatched_size - teacher_unmatched_size) + ) + if student_unmatched_size < max_unmatched_size: + student_unmatched_sorted = F.pad( + student_unmatched_sorted, (0, max_unmatched_size - student_unmatched_size) + ) + + # L1 loss on sorted unmatched tokens + unmatched_loss = F.l1_loss(student_unmatched_sorted, teacher_unmatched_sorted, reduction="sum") + unmatched_loss /= student_aligned.size(0) # Normalize by sequence length + + # 3. Combine losses with weights + if self.hybrid_matched_weight is None: + # Use adaptive weighting based on vocabulary overlap + hybrid_matched_weight = matched_token_count / max(1, teacher_vocab_size) + hybrid_unmatched_weight = 1.0 - hybrid_matched_weight + else: + # Use fixed weights provided in config + hybrid_matched_weight = self.hybrid_matched_weight + hybrid_unmatched_weight = self.hybrid_unmatched_weight + + total_loss = hybrid_matched_weight * matched_loss + hybrid_unmatched_weight * unmatched_loss + + # Store matched/unmatched components for logging + self.last_matched_loss = matched_loss + self.last_unmatched_loss = unmatched_loss + + return total_loss + + def _compute_jsd_loss_for_matched_tokens(self, student_logits, teacher_logits): + """ + Compute JSD loss for matched vocabulary tokens. + + Args: + student_logits: Student logits for matched tokens [seq_len, num_matched] + teacher_logits: Teacher logits for matched tokens [seq_len, num_matched] + Returns: + JSD loss for matched tokens + """ + # Reshape to [batch_size * seq_len, vocab_size] format expected by generalized_jsd_loss + batch_seq_len, num_matched = student_logits.shape + + student_logits_reshaped = student_logits.view(-1, num_matched) + teacher_logits_reshaped = teacher_logits.view(-1, num_matched) + + # Use the GOLD generalized JSD loss implementation that accepts probability inputs + jsd_loss = GOLDTrainer.generalized_jsd_loss( + student_logits_reshaped, + teacher_logits_reshaped, + labels=None, # No masking needed for matched tokens + beta=self.beta, # Standard JSD beta + temperature=1.0, # Already applied in main computation + reduction="batchmean", + logits_are_probs=True, + ) + + return jsd_loss + + def _get_start_and_size_answers(self, answer_tensors): + answers_index = [] + answers_size = [] + + for answer in answer_tensors: + answer_mask = answer.ne(self.ignore_index) + if not answer_mask.any(): + answers_index.append(0) + answers_size.append(0) + continue + + valid_indices = answer_mask.nonzero(as_tuple=True)[0] + answers_index.append(int(valid_indices[0].item())) + answers_size.append(int(answer_mask.sum().item())) + return answers_index, answers_size + + +class GOLDTrainer(SFTTrainer): + _tag_names = ["trl", "gold"] + _name = "GOLD" + _paper = { + "title": "Unlocking On-Policy Distillation for Any Model Family", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @misc{patino2025unlocking, + title = {{Unlocking On-Policy Distillation for Any Model Family}}, + author = {Carlos Miguel Patiño and Kashif Rasul and Quentin Gallouédec and Ben Burtenshaw and Sergio Paniego and Vaibhav Srivastav and Thibaud Frere and Ed Beeching and Lewis Tunstall and Leandro von Werra and Thomas Wolf}, + year = 2025, + url = {https://huggingface.co/spaces/HuggingFaceH4/general-on-policy-logit-distillation}, + }"""), + } + + def __init__( + self, + model: PreTrainedModel | nn.Module | str | None = None, + teacher_model: PreTrainedModel | nn.Module | str = None, + args: GOLDConfig | None = None, + data_collator: DataCollator | None = None, # type: ignore + train_dataset: Dataset | None = None, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + processing_class: PreTrainedTokenizerBase + | BaseImageProcessor + | FeatureExtractionMixin + | ProcessorMixin + | None = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + peft_config: Optional["PeftConfig"] = None, + ): + self.model_name_or_path = model if isinstance(model, str) else model.config._name_or_path + self.model_revision = (args.model_init_kwargs or {}).get("revision") + + # Respect a user-provided data_collator; otherwise, provide a ChatML collator that + if data_collator is None: + data_collator = DataCollatorForChatML(tokenizer=processing_class, max_length=args.max_length) + + # Liger fused GKD loss (JSD) + self.use_liger_gkd_loss = False + if args.use_liger_kernel: + self.liger_jsd_loss = LigerFusedLinearJSDLoss( + beta=args.beta, + ignore_index=-100, + temperature=args.temperature, + compiled=False, + weight_hard_loss=0.0, + weight_soft_loss=1.0, + ) + self.use_liger_gkd_loss = True + self._forward_redirection = _ForwardRedirection() + + if args.teacher_model_init_kwargs is None: + teacher_model_init_kwargs = {} + elif not isinstance(teacher_model, str): + raise ValueError( + "You passed teacher_model_init_kwargs to the GOLDConfig, but your teacher_model is already instantiated." + ) + else: + teacher_model_init_kwargs = args.teacher_model_init_kwargs + teacher_model_init_kwargs["dtype"] = ( + teacher_model_init_kwargs["dtype"] + if teacher_model_init_kwargs["dtype"] in ["auto", None] + else getattr(torch, teacher_model_init_kwargs["dtype"]) + ) + + if args.use_uld_loss and args.teacher_tokenizer_name_or_path is None: + if isinstance(teacher_model, str): + args.teacher_tokenizer_name_or_path = teacher_model + else: + raise ValueError( + "`teacher_tokenizer_name_or_path` must be set when using ULD loss with a pre-instantiated teacher model." + ) + + if isinstance(teacher_model, str): + init_kwargs = dict(teacher_model_init_kwargs) + if args.teacher_model_revision is not None: + init_kwargs.setdefault("revision", args.teacher_model_revision) + init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + teacher_model = create_model_from_path(teacher_model, **init_kwargs) + self.use_uld_loss = args.use_uld_loss + self.teacher_tokenizer = None + if args.use_uld_loss and args.teacher_tokenizer_name_or_path is not None: + self.teacher_tokenizer = AutoTokenizer.from_pretrained( + args.teacher_tokenizer_name_or_path, trust_remote_code=args.trust_remote_code + ) + if not hasattr(self.teacher_tokenizer, "pad_token") or self.teacher_tokenizer.pad_token is None: + self.teacher_tokenizer.pad_token = self.teacher_tokenizer.eos_token + + # Hybrid ULD loss configuration is handled in ULDLoss class + + super().__init__( + model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + peft_config=peft_config, + ) + + if args.disable_dropout: + disable_dropout_in_model(self.model) + if not args.use_uld_loss: + teacher_model.resize_token_embeddings(self.model.config.get_text_config().vocab_size) + + if self.is_deepspeed_enabled: + self.teacher_model = prepare_deepspeed(teacher_model, self.accelerator) + else: + self.teacher_model = self.accelerator.prepare_model(teacher_model, evaluation_mode=True) + + self.lmbda = args.lmbda + self.beta = args.beta + self.temperature = args.temperature + self.top_p = args.top_p + self.seq_kd = args.seq_kd + self.num_generations = args.num_generations + + # Track per-step loss statistics for on/off-policy batches (used in logging) + self._on_policy_loss_total = 0.0 + self._off_policy_loss_total = 0.0 + self._on_policy_step_equiv = 0.0 + self._off_policy_step_equiv = 0.0 + + # Buffering for rollouts across gradient accumulation steps + self._buffered_inputs = None + self._buffered_on_policy = None + self._buffered_text_logs = None + self._step = 0 + + # Hybrid ULD matched/unmatched accumulators (logged every step when ULD hybrid is used) + self._matched_sum = 0.0 + self._unmatched_sum = 0.0 + self._matched_step_eq = 0.0 + self._unmatched_step_eq = 0.0 + + self.uld_loss_fn = None + if self.use_uld_loss: + self.uld_loss_fn = ULDLoss( + config=args, + student_tokenizer=processing_class, + teacher_tokenizer=self.teacher_tokenizer, + device=self.accelerator.device, + ) + + generation_kwargs = { + "max_new_tokens": args.max_completion_length, + "temperature": args.temperature, + "top_p": args.top_p, + "do_sample": True, + "top_k": args.top_k, + "pad_token_id": self.processing_class.pad_token_id, + } + self.generation_config = GenerationConfig(**generation_kwargs) + # Keep training-specific generation kwargs to overwrite model's original generation config + self.generation_kwargs = generation_kwargs + if ( + hasattr(self.model.generation_config, "eos_token_id") + and self.model.generation_config.eos_token_id is not None + ): + self.generation_config.eos_token_id = self.model.generation_config.eos_token_id + + # Initialize the metrics + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + self._total_train_tokens = 0 + self.log_completions = args.log_completions + self.log_completion_steps = args.log_completions_steps + self.wandb_log_unique_prompts = args.wandb_log_unique_prompts + self.num_completions_to_print = args.num_completions_to_print + # maxlen is set to the total number of forward passes per step. This value of `maxlen` ensures we log only the + # final optimization step. + maxlen = self.accelerator.num_processes * args.per_device_train_batch_size * args.gradient_accumulation_steps + self._textual_logs = { + "prompt": deque(maxlen=maxlen), + "completion": deque(maxlen=maxlen), + "rewards": defaultdict(lambda: deque(maxlen=maxlen)), + "advantages": deque(maxlen=maxlen), + } + + self.use_vllm = args.use_vllm + if self.use_vllm: + if not is_vllm_available(): + raise ImportError( + "vLLM is not available and use_vllm is set to True. Please install vLLM with " + "`pip install vllm` to use it." + ) + self.vllm_generation = VLLMGeneration( + model=self.model, + accelerator=self.accelerator, + processing_class=self.processing_class, + mode=args.vllm_mode, + structured_outputs_regex=args.vllm_structured_outputs_regex, + server_base_url=args.vllm_server_base_url, + server_host=args.vllm_server_host, + server_port=args.vllm_server_port, + group_port=args.vllm_group_port, + server_timeout=args.vllm_server_timeout, + tensor_parallel_size=args.vllm_tensor_parallel_size, + gpu_memory_utilization=args.vllm_gpu_memory_utilization, + max_model_length=args.vllm_max_model_length or args.max_length, + max_num_seqs=args.per_device_train_batch_size * args.gradient_accumulation_steps, + enable_sleep_mode=args.vllm_enable_sleep_mode, + model_impl=args.vllm_model_impl, + repetition_penalty=getattr(args, "repetition_penalty", 1.0), + temperature=args.temperature, + top_p=args.top_p, + top_k=args.top_k, + min_p=getattr(args, "min_p", 0.0), + max_completion_length=args.max_completion_length, + logprobs=None, + ) + self.vllm_sync_frequency = args.vllm_sync_frequency + self._last_vllm_sync_step = -self.vllm_sync_frequency + + def _set_signature_columns_if_needed(self): + super()._set_signature_columns_if_needed() + required_columns = [ + "prompts", + "prompt_attention_mask", + "messages", + "chat_template_kwargs", + "tools", + "original_prompt_text", + "original_completion_text", + "byte_offsets", + "completion_mask", + ] + if self._signature_columns is None: + self._signature_columns = required_columns + else: + for column in required_columns: + if column not in self._signature_columns: + self._signature_columns.append(column) + + def _get_train_sampler(self, dataset=None): + if dataset is None: + dataset = self.train_dataset + return RepeatSampler( + data_source=dataset, + mini_repeat_count=self.num_generations, + batch_size=self.args.generation_batch_size * self.accelerator.num_processes, + repeat_count=self.args.gradient_accumulation_steps, + shuffle=True, + seed=self.args.seed, + ) + + def get_train_dataloader(self): + """ + Override Trainer.get_train_dataloader to load one generation batch per optimizer window. + + The dataloader yields local batches of size `per_device_train_batch_size * gradient_accumulation_steps`. The + `RepeatSampler` (with `repeat_count=gradient_accumulation_steps`) ensures each generation batch is sampled + `gradient_accumulation_steps` times so Trainer's loop iterates the correct number of times. Only the first + batch in each window triggers `_fill_buffer`; the rest are ignored by `_prepare_inputs`. + """ + if self.train_dataset is None: + raise ValueError("Trainer: training requires a train_dataset.") + + train_dataset = self.train_dataset + data_collator = self.data_collator + if is_datasets_available() and isinstance(train_dataset, Dataset): + train_dataset = self._remove_unused_columns(train_dataset, description="training") + else: + data_collator = self._get_collator_with_removed_columns(data_collator, description="training") + + dataloader_params = { + "batch_size": self._train_batch_size * self.args.gradient_accumulation_steps, + "collate_fn": data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "persistent_workers": self.args.dataloader_persistent_workers, + } + + if not isinstance(train_dataset, torch.utils.data.IterableDataset): + dataloader_params["sampler"] = self._get_train_sampler() + dataloader_params["drop_last"] = self.args.dataloader_drop_last + dataloader_params["worker_init_fn"] = partial( + seed_worker, + num_workers=self.args.dataloader_num_workers, + rank=self.args.process_index, + ) + if self.args.dataloader_num_workers > 0: + dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor + + return self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params)) + + @profiling_decorator + def _prepare_inputs(self, generation_batch: dict[str, torch.Tensor | Any]) -> dict[str, torch.Tensor | Any]: + if not self.model.training: + return generation_batch + + buffer_steps = self.args.gradient_accumulation_steps + if self._step % buffer_steps == 0 or self._buffered_inputs is None: + self._fill_buffer(generation_batch, buffer_steps) + + slice_idx = self._step % buffer_steps + inputs = self._buffered_inputs[slice_idx] + self._step += 1 + return inputs + + @staticmethod + def _build_sequence_batch( + new_input_ids: torch.Tensor, + prompt_lengths: torch.Tensor, + pad_token_id: int | None, + attention_mask: torch.Tensor | None = None, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Build attention mask and labels from full sequences and prompt lengths.""" + prompt_lengths = prompt_lengths.to(device=new_input_ids.device, dtype=torch.long) + positions = torch.arange(new_input_ids.shape[1], device=new_input_ids.device).unsqueeze(0) + completion_mask = positions >= prompt_lengths.unsqueeze(1) + + if attention_mask is not None: + new_attention_mask = attention_mask.to(device=new_input_ids.device, dtype=new_input_ids.dtype) + else: + new_attention_mask = torch.ones_like(new_input_ids) + if pad_token_id is not None: + new_attention_mask[new_input_ids == pad_token_id] = 0 + + new_labels = torch.full_like(new_input_ids, -100) + new_labels[completion_mask & new_attention_mask.bool()] = new_input_ids[ + completion_mask & new_attention_mask.bool() + ] + if attention_mask is None and pad_token_id is not None: + new_labels[new_input_ids == pad_token_id] = -100 + + return new_attention_mask, new_labels + + def _maybe_add_completion_byte_offsets(self, updated_slice: dict[str, torch.Tensor | Any]) -> None: + """Attach completion-relative byte offsets to on-policy ULD batches. + + Derived from the sampled ids via ``piece_byte_len`` (no decode→re-encode round-trip). + """ + if not ( + self.use_uld_loss + and self.teacher_tokenizer is not None + and self.uld_loss_fn is not None + and self.uld_loss_fn.use_extended_uld + ): + return + + new_input_ids = updated_slice["input_ids"] + new_labels = updated_slice["labels"] + seq_len = new_input_ids.shape[1] + + rows: list[list[tuple[int, int]]] = [] + for row_ids, row_labels in zip(new_input_ids.cpu().tolist(), new_labels.cpu().tolist(), strict=True): + offs: list[tuple[int, int]] = [(0, 0)] * seq_len + cumulative = 0 + for pos, (tid, label) in enumerate(zip(row_ids, row_labels, strict=True)): + if label == -100: + continue + nb = piece_byte_len(self.processing_class.convert_ids_to_tokens([tid])[0]) + offs[pos] = (cumulative, cumulative + nb) + cumulative += nb + rows.append(offs) + updated_slice["byte_offsets"] = torch.tensor(rows, dtype=torch.long, device=new_input_ids.device) + + @profiling_decorator + def _fill_buffer(self, generation_batch: dict[str, torch.Tensor | Any], buffer_steps: int): + slices = split_tensor_dict(generation_batch, buffer_steps) + + if self.accelerator.is_main_process: + on_policy_flags = [random.random() <= self.lmbda for _ in range(buffer_steps)] + else: + on_policy_flags = [False] * buffer_steps + + on_policy_flags = broadcast_object_list(on_policy_flags, from_process=0) + on_policy_indices = [i for i, flag in enumerate(on_policy_flags) if flag] + + self._buffered_inputs = [None] * buffer_steps + self._buffered_on_policy = on_policy_flags + self._buffered_text_logs = [None] * buffer_steps + + for i, flag in enumerate(on_policy_flags): + if not flag: + slice_inputs = slices[i] + + if ( + self.use_uld_loss + and self.teacher_tokenizer is not None + and ("original_prompt_text" not in slice_inputs or "original_completion_text" not in slice_inputs) + ): + raise ValueError( + "Off-policy batch missing 'original_prompt_text' or 'original_completion_text' fields. " + "Use the default DataCollatorForChatML (or a collator that emits these fields) so the " + "teacher tokenizer has source text to align against." + ) + if ( + self.use_uld_loss + and self.teacher_tokenizer is not None + and self.uld_loss_fn.use_extended_uld + and "byte_offsets" not in slice_inputs + ): + raise ValueError( + "Off-policy batch missing `byte_offsets`. Use the default DataCollatorForChatML or set " + "`use_extended_uld=False`." + ) + + self._buffered_inputs[i] = slice_inputs + + if on_policy_indices: + self._generate_on_policy_for_slices(slices, on_policy_indices) + + @profiling_decorator + def _generate_on_policy_for_slices( + self, slices: list[dict[str, torch.Tensor | Any]], on_policy_indices: list[int] + ): + prompt_ids_list = [] + local_slice_indices = [] + for slice_idx in on_policy_indices: + slice_inputs = slices[slice_idx] + prompt_attention_mask = slice_inputs.get("prompt_attention_mask") + for prompt_idx, prompt in enumerate(slice_inputs["prompts"]): + if prompt_attention_mask is not None: + prompt = prompt[prompt_attention_mask[prompt_idx].bool()] + prompt_ids_list.append(prompt.tolist()) + local_slice_indices.append(slice_idx) + + prompts_text = self.processing_class.batch_decode( + prompt_ids_list, + skip_special_tokens=False, + ) + + if not self.use_vllm: + self._generate_non_vllm_for_slices(slices, on_policy_indices) + return + + if ( + self.state.global_step != self._last_vllm_sync_step + and self.state.global_step >= self._last_vllm_sync_step + self.vllm_sync_frequency + ): + self.vllm_generation.sync_weights() + self._last_vllm_sync_step = self.state.global_step + + _, completion_ids, _, _ = self.vllm_generation.generate( + prompts=prompt_ids_list, + images=None, + num_generations=self.num_generations, + ) + + self._process_completions_to_buffer( + slices, + on_policy_indices, + local_slice_indices, + completion_ids, + prompt_ids_list, + prompts_text, + self.generation_config.max_new_tokens, + ) + + def _generate_non_vllm_for_slices(self, slices: list[dict[str, torch.Tensor | Any]], on_policy_indices: list[int]): + """Fallback generation without vLLM (uses model.generate per slice).""" + with unwrap_model_for_generation( + self.model, + self.accelerator, + generation_kwargs=self.generation_kwargs, + ) as unwrapped_model: + for slice_idx in on_policy_indices: + slice_inputs = slices[slice_idx] + result = self.generate_on_policy_outputs( + unwrapped_model, + slice_inputs, + self.generation_config, + self.processing_class.pad_token_id, + ) + new_input_ids, new_attention_mask, new_labels, prompt_texts, completion_texts = result + + updated_slice = dict(slice_inputs) + updated_slice["input_ids"] = new_input_ids + updated_slice["attention_mask"] = new_attention_mask + updated_slice["labels"] = new_labels + updated_slice["original_prompt_text"] = prompt_texts + updated_slice["original_completion_text"] = completion_texts + self._maybe_add_completion_byte_offsets(updated_slice) + + self._buffered_inputs[slice_idx] = updated_slice + self._buffered_text_logs[slice_idx] = (prompt_texts, completion_texts) + + def _process_completions_to_buffer( + self, + slices: list[dict[str, torch.Tensor | Any]], + on_policy_indices: list[int], + local_slice_indices: list[int], + completion_ids: list, + prompt_ids_list: list[list[int]], + prompts_text: list[str], + max_completion_length: int, + ): + """ + Process vLLM completions and update buffered inputs for on-policy slices. + """ + device = self.accelerator.device + pad_token_id = self.processing_class.pad_token_id if self.processing_class.pad_token_id is not None else 0 + + slice_completions = {idx: [] for idx in on_policy_indices} + slice_prompt_ids = {idx: [] for idx in on_policy_indices} + slice_prompts = {idx: [] for idx in on_policy_indices} + + for i, slice_idx in enumerate(local_slice_indices): + slice_completions[slice_idx].append(completion_ids[i]) + slice_prompt_ids[slice_idx].append(prompt_ids_list[i]) + slice_prompts[slice_idx].append(prompts_text[i]) + + for slice_idx in on_policy_indices: + slice_inputs = slices[slice_idx] + completion_ids_for_slice = slice_completions[slice_idx] + prompt_ids_for_slice = slice_prompt_ids[slice_idx] + prompt_txts = slice_prompts[slice_idx] + + prompt_max_length = max(1, self.args.max_length - max_completion_length) if self.args.max_length else None + truncated_prompt_ids = [] + prompt_attention_masks = [] + truncation_side = getattr(self.processing_class, "truncation_side", "right") + for prompt_ids in prompt_ids_for_slice: + if prompt_max_length and len(prompt_ids) > prompt_max_length: + if truncation_side == "left": + prompt_ids = prompt_ids[-prompt_max_length:] + else: + prompt_ids = prompt_ids[:prompt_max_length] + prompt_tensor = torch.tensor(prompt_ids, device=device, dtype=torch.long) + truncated_prompt_ids.append(prompt_tensor) + prompt_attention_masks.append(torch.ones(len(prompt_ids), device=device, dtype=torch.long)) + + prompt_ids = pad(truncated_prompt_ids, padding_side="left", padding_value=pad_token_id) + prompt_attention_mask = pad(prompt_attention_masks, padding_side="left", padding_value=0) + + # Decode the truncated prompt so the teacher conditions on the same context the student saw. + # `clean_up_tokenization_spaces=False` matches the completion decode below so byte counts stay aligned. + prompt_txts_with_special = self.processing_class.batch_decode( + [ids.tolist() for ids in truncated_prompt_ids], + skip_special_tokens=False, + clean_up_tokenization_spaces=False, + ) + + completion_ids_tensors = [torch.tensor(ids, device=device) for ids in completion_ids_for_slice] + completion_ids_for_text: list[list[int]] = [] + padded_completion_ids_list = [] + completion_attention_masks = [] + for completion_tensor in completion_ids_tensors: + if len(completion_tensor) > max_completion_length: + truncated_completion_tensor = completion_tensor[:max_completion_length] + padded_completion_ids_list.append(truncated_completion_tensor) + completion_ids_for_text.append(truncated_completion_tensor.tolist()) + completion_attention_masks.append( + torch.ones(len(truncated_completion_tensor), device=device, dtype=torch.long) + ) + elif len(completion_tensor) < max_completion_length: + padding_needed = max_completion_length - len(completion_tensor) + padded_tensor = torch.cat( + [ + completion_tensor, + torch.full( + (padding_needed,), + pad_token_id, + device=device, + dtype=completion_tensor.dtype, + ), + ] + ) + padded_completion_ids_list.append(padded_tensor) + completion_ids_for_text.append(completion_tensor.tolist()) + completion_attention_masks.append( + torch.cat( + [ + torch.ones(len(completion_tensor), device=device, dtype=torch.long), + torch.zeros(padding_needed, device=device, dtype=torch.long), + ] + ) + ) + else: + padded_completion_ids_list.append(completion_tensor) + completion_ids_for_text.append(completion_tensor.tolist()) + completion_attention_masks.append( + torch.ones(len(completion_tensor), device=device, dtype=torch.long) + ) + + completion_ids_padded = torch.stack(padded_completion_ids_list) + completion_attention_mask = torch.stack(completion_attention_masks) + + new_input_ids = torch.cat([prompt_ids, completion_ids_padded], dim=1) + new_attention_mask = torch.cat([prompt_attention_mask, completion_attention_mask], dim=1) + prompt_lengths = torch.full((prompt_ids.shape[0],), prompt_ids.shape[1], device=device) + new_attention_mask, new_labels = self._build_sequence_batch( + new_input_ids, + prompt_lengths, + pad_token_id, + attention_mask=new_attention_mask, + ) + + completion_texts = self.processing_class.batch_decode( + completion_ids_for_text, + skip_special_tokens=False, + clean_up_tokenization_spaces=False, + ) + + updated_slice = dict(slice_inputs) + updated_slice["input_ids"] = new_input_ids + updated_slice["attention_mask"] = new_attention_mask + updated_slice["labels"] = new_labels + updated_slice["original_prompt_text"] = prompt_txts_with_special + updated_slice["original_completion_text"] = completion_texts + self._maybe_add_completion_byte_offsets(updated_slice) + + self._buffered_inputs[slice_idx] = updated_slice + self._buffered_text_logs[slice_idx] = (prompt_txts, completion_texts) + + def _prepare_dataset( + self, + dataset: Dataset | IterableDataset, + processing_class: PreTrainedTokenizerBase | BaseImageProcessor | FeatureExtractionMixin | ProcessorMixin, + args, + packing: bool, + formatting_func: Callable[[dict], str] | None, + dataset_name: str, + ) -> Dataset | IterableDataset: + """Preserve original text fields for ULD when needed.""" + column_names = list(next(iter(dataset)).keys()) + is_processed = "input_ids" in column_names + + if packing and self.use_uld_loss and self.teacher_tokenizer is not None: + raise ValueError( + "Packing is not supported with cross-tokenizer ULD because byte-offset alignment is defined per " + "prompt/completion example." + ) + + if not is_processed or (self.use_uld_loss and self.teacher_tokenizer is not None): + return self._prepare_dataset_with_original_text( + dataset, processing_class, args, packing, formatting_func, dataset_name + ) + + return super()._prepare_dataset(dataset, processing_class, args, packing, formatting_func, dataset_name) + + def _prepare_dataset_with_original_text( + self, + dataset: Dataset | IterableDataset, + processing_class: PreTrainedTokenizerBase | BaseImageProcessor | FeatureExtractionMixin | ProcessorMixin, + args, + packing: bool, + formatting_func: Callable[[dict], str] | None, + dataset_name: str, + ) -> Dataset | IterableDataset: + """ + Prepare dataset while preserving original text for cross-tokenizer distillation. + """ + # Build the kwargs for the `map` function + map_kwargs = {} + if isinstance(dataset, Dataset): # IterableDataset does not support num_proc + map_kwargs["num_proc"] = args.dataset_num_proc + + with PartialState().main_process_first(): + # Apply the formatting function if any + if formatting_func is not None: + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Applying formatting function to {dataset_name} dataset" + + def _func(example): + return {"text": formatting_func(example)} + + dataset = dataset.map(_func, batched=False, **map_kwargs) + + # Convert the dataset to ChatML if needed + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Converting {dataset_name} dataset to ChatML" + column_names = next(iter(dataset)).keys() + dataset = dataset.map( + maybe_convert_to_chatml, + remove_columns="conversations" if "conversations" in column_names else None, + **map_kwargs, + ) + + # Add EOS token if needed: non-conversational only + first_example = next(iter(dataset)) + if not is_conversational(first_example): + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Adding EOS to {dataset_name} dataset" + + def add_eos(example, eos_token): + if "text" in example and not example["text"].endswith(eos_token): # language modeling case + example["text"] = example["text"] + eos_token + elif "completion" in example and not example["completion"].endswith(eos_token): + example["completion"] = example["completion"] + eos_token + return example + + dataset = dataset.map( + add_eos, + fn_kwargs={"eos_token": processing_class.eos_token}, + remove_columns="messages" if "messages" in column_names else None, # renamed to "text" + **map_kwargs, + ) + + # Tokenize the dataset while preserving original text + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Tokenizing {dataset_name} dataset (preserving original text)" + + def tokenize_with_original_text(example, processing_class, dataset_text_field, max_length): + """Emit input_ids, attention_mask, byte_offsets, completion_mask, and the original prompt/completion + text. Byte offsets and input_ids come from a single ``encode_with_byte_offsets`` call.""" + backend = processing_class.backend_tokenizer + result = {} + + if "prompt" in example: # prompt-completion case + if is_conversational(example): + prompt_text = processing_class.apply_chat_template( + example["prompt"], + add_generation_prompt=True, + tokenize=False, + **example.get("chat_template_kwargs", {}), + ) + full_text = processing_class.apply_chat_template( + example["prompt"] + example["completion"], + tokenize=False, + **example.get("chat_template_kwargs", {}), + ) + prompt_text = "".join( + x for x, _ in takewhile(lambda x: x[0] == x[1], zip(prompt_text, full_text, strict=False)) + ) + completion_text = full_text[len(prompt_text) :] + else: + prompt_text = example["prompt"] + completion_text = example["completion"] + full_text = prompt_text + completion_text + result["original_prompt_text"] = prompt_text + result["original_completion_text"] = completion_text + elif is_conversational(example): + messages = example["messages"] + assistant_indices = [idx for idx, msg in enumerate(messages) if msg["role"] == "assistant"] + if assistant_indices: + completion_idx = assistant_indices[-1] + prompt_messages = messages[:completion_idx] + full_messages = messages[: completion_idx + 1] + if prompt_messages: + prompt_text = processing_class.apply_chat_template( + prompt_messages, + add_generation_prompt=True, + tokenize=False, + **example.get("chat_template_kwargs", {}), + ) + else: + prompt_text = "" + full_text = processing_class.apply_chat_template( + full_messages, + add_generation_prompt=False, + tokenize=False, + **example.get("chat_template_kwargs", {}), + ) + prompt_text = "".join( + x for x, _ in takewhile(lambda x: x[0] == x[1], zip(prompt_text, full_text, strict=False)) + ) + completion_text = full_text[len(prompt_text) :] + result["original_prompt_text"] = prompt_text + result["original_completion_text"] = completion_text + else: + full_text = processing_class.apply_chat_template( + messages, tokenize=False, **example.get("chat_template_kwargs", {}) + ) + prompt_text = "" + result["original_prompt_text"] = "" + result["original_completion_text"] = full_text + else: + text = example.get(dataset_text_field, example.get("text", "")) + prompt_text = "" + full_text = text + result["original_prompt_text"] = "" + result["original_completion_text"] = text + + # Single backend call: ids and char-derived byte offsets from the same encoding, + # so input_ids[i] is described by full_offs[i] without any boundary slop. + [(input_ids, full_offs)] = encode_with_byte_offsets(backend, [full_text], add_special_tokens=False) + prompt_byte_len = len(prompt_text.encode("utf-8")) + completion_start = next( + (idx for idx, (s, _) in enumerate(full_offs) if s >= prompt_byte_len), + len(input_ids), + ) + # Completion-relative: prompt positions zeroed, completion offsets shifted to + # the assistant content's first byte (matches build_teacher_inputs_from_texts). + byte_offsets = [(0, 0)] * completion_start + [ + (s - prompt_byte_len, e - prompt_byte_len) for s, e in full_offs[completion_start:] + ] + + # Keep the last `max_length` tokens (the completion end). `completion_mask` tracks the + # boundary so it survives truncation without re-tokenizing the prompt. + if max_length is not None and len(input_ids) > max_length: + drop = len(input_ids) - max_length + input_ids = input_ids[drop:] + byte_offsets = byte_offsets[drop:] + completion_start = max(0, completion_start - drop) + # If truncation ate into the completion, rebase the kept completion offsets so they're + # relative to the new (truncated) `original_completion_text` the teacher will re-encode. + if completion_start < len(byte_offsets): + base = byte_offsets[completion_start][0] + if base > 0: + byte_offsets = byte_offsets[:completion_start] + [ + (s - base, e - base) for s, e in byte_offsets[completion_start:] + ] + # Resync the strings the teacher will re-encode with the ids the student kept. + decode = partial( + processing_class.decode, skip_special_tokens=False, clean_up_tokenization_spaces=False + ) + result["original_prompt_text"] = decode(input_ids[:completion_start]) + result["original_completion_text"] = decode(input_ids[completion_start:]) + + result["input_ids"] = input_ids + result["attention_mask"] = [1] * len(input_ids) + result["byte_offsets"] = byte_offsets + result["completion_mask"] = [0] * completion_start + [1] * (len(input_ids) - completion_start) + return result + + dataset = dataset.map( + tokenize_with_original_text, + fn_kwargs={ + "processing_class": processing_class, + "dataset_text_field": args.dataset_text_field, + "max_length": args.max_length, + }, + **map_kwargs, + ) + + # Pack if requested. Truncation already happened in `tokenize_with_original_text`, keeping + # the completion end — so the generic front-truncating `truncate_dataset` is intentionally + # not applied here (it would drop the completion). + if packing: + if args.max_length is None: + raise ValueError("When packing is enabled, `max_length` can't be `None`.") + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Packing {dataset_name} dataset" + + columns_to_keep = ["input_ids", "original_prompt_text", "original_completion_text"] + existing_columns = set(dataset.column_names) + columns_to_select = [col for col in columns_to_keep if col in existing_columns] + + dataset = dataset.select_columns(columns_to_select) + dataset = pack_dataset(dataset, args.max_length, args.packing_strategy, map_kwargs) + + if args.use_liger_kernel: + required_columns = { + "input_ids", + "attention_mask", + "position_ids", + "completion_mask", + "messages", + "original_prompt_text", + "original_completion_text", + "byte_offsets", + } + dataset = dataset.select_columns(required_columns.intersection(dataset.column_names)) + + return dataset + + @staticmethod + def generalized_jsd_loss( + student_logits, + teacher_logits, + labels=None, + beta=0.5, + temperature=1.0, + reduction="batchmean", + logits_are_probs=False, + num_items_in_batch=None, + ): + """ + Compute the generalized Jensen-Shannon Divergence loss for knowledge distillation using F.kl_div. See Eq. (1) + of https://huggingface.co/papers/2306.13649 for the definition. + + Args: + student_logits: + Tensor of shape (batch_size, sequence_length, vocab_size) + teacher_logits: + Tensor of shape (batch_size, sequence_length, vocab_size) + labels: + Tensor of shape (batch_size, sequence_length) with -100 for padding tokens to ignore when computing + loss + beta: + Interpolation coefficient between 0 and 1 (default: 0.5) + temperature: + Softmax temperature (default: 1.0) + reduction: + Specifies the reduction to apply to the output (default: 'batchmean') + + Returns: + loss: Scalar tensor with the generalized JSD loss + """ + + if logits_are_probs: + student_log_probs = torch.log(student_logits.clamp_min(1e-8)) + teacher_log_probs = torch.log(teacher_logits.clamp_min(1e-8)) + else: + # Apply temperature scaling to logits before computing probabilities + student_logits = student_logits / temperature + teacher_logits = teacher_logits / temperature + # Compute log probabilities for student and probabilities for teacher + student_log_probs = F.log_softmax(student_logits, dim=-1) + teacher_log_probs = F.log_softmax(teacher_logits, dim=-1) + + if beta == 0: + jsd = F.kl_div(student_log_probs, teacher_log_probs, reduction="none", log_target=True) + elif beta == 1: + jsd = F.kl_div(teacher_log_probs, student_log_probs, reduction="none", log_target=True) + else: + # Compute the log of the mixture distribution + # log(a + b) = log(exp(log(a)) + exp(log(b))) -> for mixture + beta = torch.tensor(beta, dtype=student_log_probs.dtype, device=student_log_probs.device) + mixture_log_probs = torch.logsumexp( + torch.stack([student_log_probs + torch.log1p(-beta), teacher_log_probs + torch.log(beta)]), + dim=0, + ) + + # Compute KL divergences using F.kl_div + # PyTorch differs from the standard mathematical definition, so the order of the probability distributions is swapped compared to that defined in the paper. + kl_teacher = F.kl_div(mixture_log_probs, teacher_log_probs, reduction="none", log_target=True) + kl_student = F.kl_div(mixture_log_probs, student_log_probs, reduction="none", log_target=True) + + # Compute the Generalized Jensen-Shannon Divergence + jsd = beta * kl_teacher + (1 - beta) * kl_student + + # Masking + if labels is not None: + mask = labels != -100 + jsd = jsd[mask] + + # Apply reduction + if num_items_in_batch is not None: + # Normalize by the global number of valid tokens for gradient-accumulation-correct loss (see issue #4719). + jsd_sum = jsd.sum() + if isinstance(num_items_in_batch, torch.Tensor): + num_items_in_batch = num_items_in_batch.to(jsd_sum.device) + return jsd_sum / num_items_in_batch + if reduction == "batchmean": + # clamp_min(1) avoids 0/0 -> nan when a sample has no unmasked positions + # (e.g. completion fully truncated). jsd[mask] is empty -> jsd.sum() == 0, + # so 0/1 == 0 with a valid grad path. + denom = mask.sum().clamp_min(1) if labels is not None else max(jsd.size(0), 1) + return jsd.sum() / denom + elif reduction == "sum": + return jsd.sum() + elif reduction == "mean": + return jsd.mean() + else: + return jsd + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + if self.use_uld_loss and self.teacher_tokenizer is not None: + # Both DataCollatorForChatML and the on-policy generation path attach these + # fields, so cross-tokenizer ULD never has to round-trip through batch_decode. + prompt_texts = inputs["original_prompt_text"] + completion_texts = inputs["original_completion_text"] + + ( + teacher_input_ids, + teacher_labels, + teacher_attention_mask, + teacher_completion_byte_offsets, + ) = build_teacher_inputs_from_texts(self.teacher_tokenizer, prompt_texts, completion_texts) + + teacher_input_ids = teacher_input_ids.to(self.accelerator.device) + teacher_labels = teacher_labels.to(self.accelerator.device) + teacher_attention_mask = teacher_attention_mask.to(self.accelerator.device) + + outputs_student = model( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + use_cache=False, + ) + + self.teacher_model.eval() + with torch.no_grad(): + outputs_teacher = self.teacher_model( + input_ids=teacher_input_ids, + attention_mask=teacher_attention_mask, + ) + else: + if self.use_liger_gkd_loss: + # Forward only through the base models (avoid lm_head to save memory). + # Route through the DDP/FSDP wrapper via _forward_redirection so that + # DDP.forward() is called and prepare_for_backward() fires correctly. + unwrapped_student = self.accelerator.unwrap_model(model) + student_outputs = self._forward_redirection( + model, unwrapped_student, self._liger_student_forward, unwrapped_student, inputs + ) + + self.teacher_model.eval() + unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model) + if hasattr(unwrapped_teacher, "get_decoder") and unwrapped_teacher.get_decoder() is not None: + base_teacher = unwrapped_teacher.get_decoder() + else: + base_teacher = getattr( + unwrapped_teacher, getattr(unwrapped_teacher, "base_model_prefix", "model"), unwrapped_teacher + ) + with torch.no_grad(): + teacher_outputs = base_teacher( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + use_cache=False, + ) + + student_hidden = student_outputs.last_hidden_state[:, :-1] + teacher_hidden = teacher_outputs.last_hidden_state[:, :-1] + + del student_outputs, teacher_outputs + + student_hidden = student_hidden.reshape(-1, student_hidden.shape[-1]) + teacher_hidden = teacher_hidden.reshape(-1, teacher_hidden.shape[-1]) + + labels_mask = inputs["labels"] != -100 + masked_input_ids = torch.where( + labels_mask, inputs["input_ids"], torch.full_like(inputs["input_ids"], -100) + ) + true_labels = masked_input_ids[:, 1:].reshape(-1) + + student_head = unwrapped_student.get_output_embeddings() + teacher_head = unwrapped_teacher.get_output_embeddings() + + loss = self.liger_jsd_loss( + student_input=student_hidden, + student_weight=student_head.weight, + teacher_input=teacher_hidden, + teacher_weight=teacher_head.weight, + true_labels=true_labels, + student_bias=getattr(student_head, "bias", None), + teacher_bias=getattr(teacher_head, "bias", None), + ) + + # The Liger JSD loss normalizes by the local number of valid tokens. Under gradient accumulation we + # want the global normalization, so rescale by `num_valid_local / num_items_in_batch`. + if num_items_in_batch is not None: + num_valid_local = (true_labels != -100).sum().clamp_min(1) + if isinstance(num_items_in_batch, torch.Tensor): + num_items_in_batch = num_items_in_batch.to(loss.device) + loss = loss * num_valid_local / num_items_in_batch + + del student_hidden, teacher_hidden, true_labels + else: + outputs_student = model( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + ) + + self.teacher_model.eval() + with torch.no_grad(): + outputs_teacher = self.teacher_model( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + ) + + # Standard causal shift: logits at position i predict the token at i + 1. The `labels != -100` mask + # inside `generalized_jsd_loss` already excludes prompt (and padding) positions, so we do not slice by + # prompt length. Slicing by `inputs["prompts"].shape[1]` (the batch-max prompt width) would drop real + # completion tokens for samples whose prompt is shorter than the batch maximum, since `labels` is + # padded to the full-sequence width independently of `prompts`. + shifted_student_logits = outputs_student.logits[:, :-1, :] + shifted_teacher_logits = outputs_teacher.logits[:, :-1, :] + shifted_labels = inputs["labels"][:, 1:] + loss = self.generalized_jsd_loss( + student_logits=shifted_student_logits, + teacher_logits=shifted_teacher_logits, + labels=shifted_labels, + beta=self.beta, + temperature=self.temperature, + num_items_in_batch=num_items_in_batch, + ) + + if self.use_uld_loss and self.teacher_tokenizer is not None: + student_labels = inputs["labels"].clone() + if self.processing_class.pad_token_id is not None: + student_labels[student_labels == self.processing_class.pad_token_id] = -100 + if self.teacher_tokenizer.pad_token_id is not None: + teacher_labels[teacher_labels == self.teacher_tokenizer.pad_token_id] = -100 + + student_byte_offsets = inputs.get("byte_offsets") + if self.uld_loss_fn.use_extended_uld and student_byte_offsets is None: + raise ValueError("Input batches must include `byte_offsets` when `use_extended_uld=True`.") + + loss = self.uld_loss_fn( + student_logits=outputs_student.logits, + teacher_logits=outputs_teacher.logits, + student_labels=student_labels, + teacher_labels=teacher_labels, + student_input_ids=inputs["input_ids"], + teacher_input_ids=teacher_input_ids, + student_byte_offsets=student_byte_offsets, + teacher_byte_offsets=teacher_completion_byte_offsets, + ) + + if hasattr(self.uld_loss_fn, "last_matched_loss") and hasattr(self.uld_loss_fn, "last_unmatched_loss"): + ga = max(1, int(self.args.gradient_accumulation_steps)) + step_eq = 1.0 / ga + matched_val = ( + self.uld_loss_fn.last_matched_loss.item() + if self.uld_loss_fn.last_matched_loss is not None + else 0.0 + ) + unmatched_val = ( + self.uld_loss_fn.last_unmatched_loss.item() + if self.uld_loss_fn.last_unmatched_loss is not None + else 0.0 + ) + + self._matched_sum += matched_val + self._unmatched_sum += unmatched_val + self._matched_step_eq += step_eq + self._unmatched_step_eq += step_eq + + empty_cache() + + return (loss, outputs_student) if return_outputs else loss + + def generate_on_policy_outputs(self, model, inputs, generation_config, pad_token_id=None): + # Generate output with respect to the prompt only + generated_outputs = model.generate( + input_ids=inputs["prompts"], + attention_mask=inputs.get("prompt_attention_mask", None), + generation_config=generation_config, + return_dict_in_generate=True, + ) + # Get the generated token IDs + generated_tokens = generated_outputs.sequences + + batch_size = generated_tokens.size(0) + device = generated_tokens.device + + prompt_mask = inputs.get("prompt_attention_mask") + pad_token_id = pad_token_id if pad_token_id is not None else self.processing_class.pad_token_id + + # model.generate() returns full sequences (prompt + completion), so completions start + # after the full padded prompt width. + prompt_lengths = torch.full((batch_size,), inputs["prompts"].shape[1], dtype=torch.long, device=device) + + new_input_ids = generated_tokens + new_attention_mask, new_labels = self._build_sequence_batch(new_input_ids, prompt_lengths, pad_token_id) + + prompt_texts = [] + completion_texts = [] + for idx in range(batch_size): + length = int(prompt_lengths[idx].item()) + prompt_tokens = inputs["prompts"][idx] + if prompt_mask is not None: + prompt_tokens = prompt_tokens[prompt_mask[idx].bool()] + elif pad_token_id is not None: + prompt_tokens = prompt_tokens[prompt_tokens != pad_token_id] + prompt_texts.append( + self.processing_class.decode( + prompt_tokens.tolist(), + skip_special_tokens=False, + clean_up_tokenization_spaces=False, + ) + ) + completion_tokens = new_input_ids[idx, length:] + completion_tokens = completion_tokens[new_labels[idx, length:] != -100] + completion_texts.append( + self.processing_class.decode( + completion_tokens.tolist(), + skip_special_tokens=False, + clean_up_tokenization_spaces=False, + ) + ) + + return new_input_ids, new_attention_mask, new_labels, prompt_texts, completion_texts + + def _liger_student_forward(self, student, inputs): + """Decoder-only forward used by the Liger JSD path (skips lm_head to save memory).""" + if hasattr(student, "get_decoder") and student.get_decoder() is not None: + decoder = student.get_decoder() + else: + decoder = getattr(student, getattr(student, "base_model_prefix", "model"), student) + return decoder( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + use_cache=False, + ) + + def _get_liger_zero3_lm_head_gather_ctx(self, model: nn.Module): + if not self.use_liger_gkd_loss: + return nullcontext() + + deepspeed_plugin = self.accelerator.state.deepspeed_plugin + if deepspeed_plugin is None or deepspeed_plugin.zero_stage != 3: + return nullcontext() + + import deepspeed + + unwrapped_student = self.accelerator.unwrap_model(model) + unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model) + student_head = unwrapped_student.get_output_embeddings() + teacher_head = unwrapped_teacher.get_output_embeddings() + params = [student_head.weight, teacher_head.weight] + if student_head.bias is not None: + params.append(student_head.bias) + if teacher_head.bias is not None: + params.append(teacher_head.bias) + return deepspeed.zero.GatheredParameters(params, modifier_rank=None) + + @profiling_decorator + def training_step( + self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None + ) -> torch.Tensor: + """ + Perform a training step for the General Online Logit Distillation (GOLD) model. + + This method implements the on-policy learning approach described in the GOLD blog post. With probability + `self.lmbda`, it generates new responses using the student model, which are then used for training instead of + the offline original inputs. + """ + buffer_steps = self.args.gradient_accumulation_steps + + # Keep lm_head gathered across forward+backward for Liger + ZeRO-3. + with self._get_liger_zero3_lm_head_gather_ctx(model): + loss = super().training_step(model, inputs, num_items_in_batch) + + slice_idx = (self._step - 1) % buffer_steps + + on_policy = False + if self._buffered_on_policy is not None and slice_idx < len(self._buffered_on_policy): + on_policy = self._buffered_on_policy[slice_idx] + + if on_policy and self._buffered_text_logs is not None and self._buffered_text_logs[slice_idx] is not None: + prompt_texts, completion_texts = self._buffered_text_logs[slice_idx] + self._textual_logs["prompt"].extend(gather_object(prompt_texts)) + self._textual_logs["completion"].extend(gather_object(completion_texts)) + + loss_scalar = float(loss.detach()) + step_equiv = 1.0 / self.args.gradient_accumulation_steps + + if on_policy: + self._on_policy_loss_total += loss_scalar + self._on_policy_step_equiv += step_equiv + else: + self._off_policy_loss_total += loss_scalar + self._off_policy_step_equiv += step_equiv + return loss + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} # average the metrics + + if mode == "train": + device = self.accelerator.device if hasattr(self.accelerator, "device") else torch.device("cpu") + vec = torch.tensor( + [ + self._on_policy_loss_total, + self._off_policy_loss_total, + self._on_policy_step_equiv, + self._off_policy_step_equiv, + self._matched_sum, + self._unmatched_sum, + self._matched_step_eq, + self._unmatched_step_eq, + ], + dtype=torch.float64, + device=device, + ) + + if ( + getattr(self.accelerator, "distributed_type", DistributedType.NO) != DistributedType.NO + and dist.is_available() + and dist.is_initialized() + ): + dist.all_reduce(vec, op=dist.ReduceOp.SUM) + + ( + on_sum, + off_sum, + on_eq, + off_eq, + matched_sum, + unmatched_sum, + matched_eq, + unmatched_eq, + ) = vec.tolist() + + if on_eq > 0: + logs["on_policy_loss"] = round(on_sum / on_eq, 4) + if off_eq > 0: + logs["off_policy_loss"] = round(off_sum / off_eq, 4) + + if matched_eq > 0: + logs["matched_loss"] = round(matched_sum / matched_eq, 4) + if unmatched_eq > 0: + logs["unmatched_loss"] = round(unmatched_sum / unmatched_eq, 4) + + self._on_policy_loss_total = self._off_policy_loss_total = 0.0 + self._on_policy_step_equiv = self._off_policy_step_equiv = 0.0 + self._matched_sum = self._unmatched_sum = 0.0 + self._matched_step_eq = self._unmatched_step_eq = 0.0 + + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + if ( + self.accelerator.is_main_process + and self.log_completions + and ((self.state.global_step % self.log_completion_steps) == 0) + ): + if is_rich_available(): + print_prompt_completions_sample_uld( + self._textual_logs["prompt"], + self._textual_logs["completion"], + self.state.global_step, + self.num_completions_to_print, + ) + + if self.args.report_to and "wandb" in self.args.report_to and wandb.run is not None: + import pandas as pd + + table = { + "step": [self.state.global_step] * len(self._textual_logs["prompt"]), + "prompt": self._textual_logs["prompt"], + "completion": self._textual_logs["completion"], + } + df = pd.DataFrame(table) + if self.wandb_log_unique_prompts: + df = df.drop_duplicates(subset=["prompt"]) + if self.num_completions_to_print and len(df) > 0: + df = df.sample(n=self.num_completions_to_print, random_state=42) + wandb.log({"completions": wandb.Table(dataframe=df)}) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/grpo_with_replay_buffer/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/grpo_with_replay_buffer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..708ea62d6740e6ca43c7de21bb716abce1e7c284 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/grpo_with_replay_buffer/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .grpo_with_replay_buffer_config import GRPOWithReplayBufferConfig +from .grpo_with_replay_buffer_trainer import GRPOWithReplayBufferTrainer, ReplayBuffer diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_config.py new file mode 100644 index 0000000000000000000000000000000000000000..9955af51dcf2264c905452e7bb578f3041a60b5c --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_config.py @@ -0,0 +1,34 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field + +from ...trainer.grpo_config import GRPOConfig + + +@dataclass +class GRPOWithReplayBufferConfig(GRPOConfig): + """ + New Parameters: + replay_buffer_size (`int`, *optional*, defaults to `64`): + A cache that stores the rollouts with the highest advantage scores and variance per group. If a new + group has 0 variance, it is replaced with a group sampled from the replay buffer. + """ + + replay_buffer_size: int = field( + default=64, + metadata={ + "help": "A cache that stores the rollouts with the highest advantage scores and variance per group. If a new group has 0 variance, it is replaced with a group sampled from the replay buffer." + }, + ) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..3ab9617170a30d282f2602eb5145a25cbd3b8c7c --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_trainer.py @@ -0,0 +1,797 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import heapq +from typing import Any + +import torch +from accelerate.utils import gather_object + +from ...data_utils import apply_chat_template, is_conversational, prepare_multimodal_messages +from ...models.utils import disable_gradient_checkpointing +from ...trainer.grpo_trainer import GRPOTrainer +from ...trainer.utils import nanmax, nanmin, nanstd, pad +from .grpo_with_replay_buffer_config import GRPOWithReplayBufferConfig + + +class ReplayBuffer: + """ + A simple replay buffer to store and sample previously seen rollouts. + """ + + def __init__(self, max_size: int): + self.max_size = max_size + self.heap = [] # Min-heap of (score, data) tuples + + def add(self, scores: list[float], data: list[dict]): + for score, datum in zip(scores, data, strict=True): + if len(self.heap) < self.max_size: + heapq.heappush(self.heap, (score, datum)) + else: + # Only add if score is better than worst (minimum) item + if score > self.heap[0][0]: + heapq.heapreplace(self.heap, (score, datum)) + + def sample(self, num_samples: int) -> list[dict[str, torch.Tensor]]: + if not self.heap: + return None + + # Sample by normalized scores + scores = torch.tensor([item[0] for item in self.heap], dtype=torch.float32) + probabilities = scores / scores.sum() + replacement = False + if num_samples > len(self.heap): + replacement = True + chosen_indices = torch.multinomial(probabilities, num_samples, replacement=replacement).tolist() + return [self.heap[i][1] for i in chosen_indices] + + +class GRPOWithReplayBufferTrainer(GRPOTrainer): + def __init__(self, args: GRPOWithReplayBufferConfig | None = None, **kwargs): + super().__init__(args=args, **kwargs) + self.replay_buffer = ReplayBuffer(args.replay_buffer_size) if args.replay_buffer_size > 0 else None + + def _generate_and_score_completions( + self, inputs: list[dict[str, torch.Tensor | Any]] + ) -> dict[str, torch.Tensor | Any]: + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + + prompts = [x["prompt"] for x in inputs] + + if "images" in inputs[0]: + images = [example.get("images") for example in inputs] + elif "image" in inputs[0]: + images = [[example.get("image")] if example.get("image") is not None else None for example in inputs] + else: + images = None + # Transformers requires at least one image in the batch, otherwise it throws an error + if images is not None and all(img_list == [] for img_list in images): + images = None + + # If the prompts are conversational and the inputs contain images, we need to convert the prompts from + # [{"role": "user", "content": "What color is the sky?"}] to + # [{"role": "user", "content": [{"type": "image", "image": }, {"type": "text", "text": "What color is the sky?"}]}] + if images is not None: + if not is_conversational(inputs[0]): + raise ValueError( + "Multimodal training requires conversational prompts. It looks like the dataset contains " + "non-conversational inputs, likely because a chat template was applied before passing the dataset " + "to the trainer. Please provide the raw conversational prompts and let the trainer apply the chat " + "template internally." + ) + prompts = [ + prepare_multimodal_messages(prompt, images=image_list) + for prompt, image_list in zip(prompts, images, strict=True) + ] + + dataset_images = images # preserve dataset images before _generate may overwrite + ( + prompt_ids_list, + completion_ids_list, + tool_mask_list, + completions, + num_items_in_batch, + sampling_per_token_logps_list, + extra_fields, + images, + tool_images, + ) = self._generate(prompts) + if images is None: + images = dataset_images # restore dataset images (rollout_func path returns None) + + # Convert lists of token IDs to padded tensors + prompt_ids = [torch.tensor(ids) for ids in prompt_ids_list] + prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids] + prompt_ids = pad( + prompt_ids, + padding_value=self._tokenizer.pad_token_id, + padding_side="left", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + prompt_mask = pad( + prompt_mask, + padding_value=0, + padding_side="left", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + completion_ids = [torch.tensor(ids) for ids in completion_ids_list] + completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids] + completion_ids = pad( + completion_ids, + padding_value=self._tokenizer.pad_token_id, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + completion_mask = pad( + completion_mask, + padding_value=0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + if sampling_per_token_logps_list is not None: + sampling_per_token_logps = [torch.tensor(logps) for logps in sampling_per_token_logps_list] + sampling_per_token_logps = pad( + sampling_per_token_logps, + padding_value=0.0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + else: + sampling_per_token_logps = None + if self.tools: + tool_mask = [torch.tensor(mask) for mask in tool_mask_list] + tool_mask = pad( + tool_mask, + padding_value=1, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) # 0 for tool result tokens, 1 elsewhere + + # If mask_truncated_completions is enabled, zero out truncated completions in completion_mask + if self.mask_truncated_completions: + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device) + completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int() + + # Concatenate prompt_mask with completion_mask for logit computation + prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) # (B, P+C) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P+C) + + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + batch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size + + num_images = [len(img_list) if img_list else 0 for img_list in images] if images is not None else None + + # Get forward_kwargs for models with multimodal inputs + if images is not None: + prompts_text = [ + apply_chat_template( + {"prompt": prompt}, self.processing_class, tools=self.tools, **self.chat_template_kwargs + )["prompt"] + for prompt in prompts + ] + prompt_inputs = self.processing_class(images=images, text=prompts_text, padding=True, return_tensors="pt") + prompt_inputs = super()._prepare_inputs(prompt_inputs) + forward_kwargs = {k: v for k, v in prompt_inputs.items() if k not in ["input_ids", "attention_mask"]} + else: + forward_kwargs = {} + + # If token_type_ids are used, extend them with zeros for the completion part + if "token_type_ids" in forward_kwargs: + token_type_ids = forward_kwargs["token_type_ids"] + if self.pad_to_multiple_of is not None: + # Needed only with pad_to_multiple_of: otherwise prompt_ids and token_type_ids must have equal len + padding_size = prompt_ids.size(1) - token_type_ids.size(1) + if padding_size > 0: + token_type_ids = torch.cat( + [token_type_ids.new_zeros((token_type_ids.size(0), padding_size)), token_type_ids], dim=1 + ) + forward_kwargs["token_type_ids"] = torch.cat( + [token_type_ids, token_type_ids.new_zeros(completion_ids.shape)], dim=1 + ) + # If mm_token_type_ids are used, extend them with zeros for the completion part + if "mm_token_type_ids" in forward_kwargs: + mm_token_type_ids = forward_kwargs["mm_token_type_ids"] + if self.pad_to_multiple_of is not None: + # Needed only with pad_to_multiple_of: otherwise prompt_ids and mm_token_type_ids must have equal len + padding_size = prompt_ids.size(1) - mm_token_type_ids.size(1) + if padding_size > 0: + mm_token_type_ids = torch.cat( + [mm_token_type_ids.new_zeros((mm_token_type_ids.size(0), padding_size)), mm_token_type_ids], + dim=1, + ) + forward_kwargs["mm_token_type_ids"] = torch.cat( + [mm_token_type_ids, mm_token_type_ids.new_zeros(completion_ids.shape)], dim=1 + ) + + # When gradient checkpointing is enabled with use_reentrant=True (non default), calling the model inside a + # torch.no_grad() block triggers a harmless PyTorch warning ("None of the inputs have requires_grad=True"). + # Temporarily disable checkpointing to avoid this warning during inference. + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + # If the generation and optimization steps are misaligned—i.e., if generation does not occur at the end of + # a full optimizer step (when gradient_accumulation_steps is not a multiple of generate_every)—then the + # samples may come from an earlier version of the model. In that case, we need to track old_per_token_logps + # for importance sampling. If the steps are aligned, importance sampling isn't necessary and we set + # old_per_token_logps to None. + # When using vLLM, we always compute old_per_token_logps for importance sampling, it was shown that the + # distribution mismatch between vLLM and the training model can be large and harm the training. + generate_every = self.args.steps_per_generation * self.num_iterations # generation frequency + if self.args.gradient_accumulation_steps % generate_every != 0 or ( + self.use_vllm and self.vllm_importance_sampling_correction + ): + old_per_token_logps, _, _ = self._get_per_token_logps_and_entropies( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes + ) + else: + old_per_token_logps = None + + # Compute the importance sampling ratio when using vLLM, to correct for potential distribution mismatch + if self.use_vllm and self.vllm_importance_sampling_correction: + importance_sampling_ratio = torch.exp(old_per_token_logps - sampling_per_token_logps) + importance_sampling_ratio = torch.clamp( + importance_sampling_ratio, + min=self.vllm_importance_sampling_clip_min, + max=self.vllm_importance_sampling_clip_max, + ) + + # Compute the per-token log probabilities for the reference model + if self.beta != 0.0: + if self.ref_model is not None: + ref_per_token_logps, _, _ = self._get_per_token_logps_and_entropies( + self.ref_model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size=batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes + ) + else: + with self.accelerator.unwrap_model(self.model).disable_adapter(): + ref_per_token_logps, _, _ = self._get_per_token_logps_and_entropies( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size=batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes + ) + else: + ref_per_token_logps = None + + # Decode + prompts_text = self.processing_class.batch_decode(prompt_ids, skip_special_tokens=True) + completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + + # Merge extra_fields from rollout_func into inputs for reward functions + if extra_fields: + for i, inp in enumerate(inputs): + for key, values in extra_fields.items(): + if isinstance(values, list) and i < len(values): + inp[key] = values[i] + elif not isinstance(values, list): + inp[key] = values + + # Calculate rewards for each reward function. rewards_per_func aggregates rewards across all processes. This is + # important because rewards will be normalized per group, and completions are distributed. We will later slice + # rewards_per_func to extract each process's subset. + rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list) + + # Apply weights to each reward function's output and sum + rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1) + + # Compute grouped-wise rewards + mean_grouped_rewards = rewards.view(-1, self.num_generations).mean(dim=1) + + # Normalize the rewards to compute the advantages + mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(self.num_generations, dim=0) + advantages = rewards - mean_grouped_rewards + + grouped_std_rewards = rewards.view(-1, self.num_generations).std(dim=1) + grouped_std_rewards = grouped_std_rewards.repeat_interleave(self.num_generations, dim=0) + + if self.scale_rewards in ["group", "none"]: + # If self.scale_rewards = "none", we'll still log group level std + std_rewards = grouped_std_rewards.clone() + elif self.scale_rewards == "batch": + # Compute global std + std_rewards = rewards.std().expand_as(rewards) + else: + raise ValueError( + f"Invalid value for scale_rewards: {self.scale_rewards}. Must be one of 'batch', 'group', or 'none'." + ) + + is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards)) + if self.scale_rewards != "none": + advantages = advantages / (std_rewards + 1e-4) + + # Slice to keep only the local part of the data + process_slice = slice( + self.accelerator.process_index * len(prompts), + (self.accelerator.process_index + 1) * len(prompts), + ) + all_process_advantages = advantages.clone() # keep the aggregated advantages for logging + advantages = advantages[process_slice] + grouped_std_rewards = grouped_std_rewards[process_slice] + + # Calculate mean reward per function, but only for samples where the function was applied (non-NaN values) + for i, reward_func_name in enumerate(self.reward_func_names): + mean_rewards = torch.nanmean(rewards_per_func[:, i]).item() + self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards) + std_func_rewards = nanstd(rewards_per_func[:, i]).item() + self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_func_rewards) + rewards = (rewards_per_func * self.reward_weights.to(rewards_per_func.device).unsqueeze(0)).nansum(dim=1) + self._metrics[mode]["reward"].append(rewards.mean().item()) + self._metrics[mode]["reward_std"].append(rewards.std().item()) + self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item()) + + # Log prompt and completion texts + self._logs["prompt"].extend(gather_object(prompts_text)) + self._logs["completion"].extend(gather_object(completions_text)) + for i, name in enumerate(self.reward_func_names): + self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist()) + self._logs["advantages"].extend(all_process_advantages.tolist()) + + if images is not None: + self._logs["images"].extend(gather_object(images)) + + if self.use_vllm and self.vllm_importance_sampling_correction: + delta = torch.abs(old_per_token_logps - sampling_per_token_logps) + mask = completion_mask.bool() if not self.tools else (completion_mask * tool_mask).bool() + delta = delta[mask] + mean_delta = torch.mean(delta) if delta.numel() > 0 else torch.tensor(0.0, device=device) + max_delta = torch.max(delta) if delta.numel() > 0 else torch.tensor(0.0, device=device) + self._metrics[mode]["sampling/sampling_logp_difference/mean"].append( + self.accelerator.gather(mean_delta).mean().item() + ) + self._metrics[mode]["sampling/sampling_logp_difference/max"].append( + self.accelerator.gather(max_delta).max().item() + ) + + flat_is_ratio = importance_sampling_ratio[mask] + min_importance_sampling_ratio = ( + torch.min(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device) + ) + mean_importance_sampling_ratio = ( + torch.mean(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device) + ) + max_importance_sampling_ratio = ( + torch.max(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device) + ) + self._metrics[mode]["sampling/importance_sampling_ratio/min"].append( + nanmin(self.accelerator.gather(min_importance_sampling_ratio)).item() + ) + self._metrics[mode]["sampling/importance_sampling_ratio/mean"].append( + self.accelerator.gather(mean_importance_sampling_ratio).nanmean().item() + ) + self._metrics[mode]["sampling/importance_sampling_ratio/max"].append( + nanmax(self.accelerator.gather(max_importance_sampling_ratio)).item() + ) + outputs_after_sampling_buffer = self.update_with_replay_buffer( + advantages, + grouped_std_rewards, + prompt_ids, + prompt_mask, + completion_ids, + completion_mask, + forward_kwargs, + num_items_in_batch, + old_per_token_logps, + ref_per_token_logps, + importance_sampling_ratio if self.use_vllm and self.vllm_importance_sampling_correction else None, + ) + if outputs_after_sampling_buffer is not None: + return outputs_after_sampling_buffer + else: + output = { + "prompt_ids": prompt_ids, + "prompt_mask": prompt_mask, + "completion_ids": completion_ids, + "completion_mask": completion_mask, + "advantages": advantages, + "num_items_in_batch": num_items_in_batch, + } + if old_per_token_logps is not None: + output["old_per_token_logps"] = old_per_token_logps + if self.use_vllm and self.vllm_importance_sampling_correction: + output["importance_sampling_ratio"] = importance_sampling_ratio + if ref_per_token_logps is not None: + output["ref_per_token_logps"] = ref_per_token_logps + if "pixel_values" in forward_kwargs: + output["pixel_values"] = forward_kwargs["pixel_values"] + if "image_grid_thw" in forward_kwargs: + output["image_grid_thw"] = forward_kwargs["image_grid_thw"] + if "pixel_attention_mask" in forward_kwargs: + output["pixel_attention_mask"] = forward_kwargs["pixel_attention_mask"] + if "image_sizes" in forward_kwargs: + output["image_sizes"] = forward_kwargs["image_sizes"] + if "token_type_ids" in forward_kwargs: + output["token_type_ids"] = forward_kwargs["token_type_ids"] + if images is not None: + output["num_images"] = num_images + if self.tools: + output["tool_mask"] = tool_mask + return output + + def slice_group_data( + self, data: torch.Tensor, mask: torch.Tensor, group_idx: int + ) -> tuple[torch.Tensor, torch.Tensor]: + """ + Slices the input data and mask tensors for a specific group index. Also trims the sequence length to the + maximum length in the group based on the mask. + + Args: + data: Tensor of shape (num_groups * num_generations, seq_length) + mask: Tensor of shape (num_groups * num_generations, seq_length) + group_idx: Index of the group to slice + Returns: + Tuple of (sliced_data, sliced_mask) for the specified group, with sequence length trimmed to the maximum + length in the group. + """ + start_idx = group_idx * self.num_generations + end_idx = (group_idx + 1) * self.num_generations + group_data = data[start_idx:end_idx] + group_mask = mask[start_idx:end_idx] + group_max_len = group_mask.sum(dim=1).max().item() + return group_data[:, :group_max_len], group_mask[:, :group_max_len] + + def update_replay_buffer( + self, + groups_with_variance: torch.Tensor, + group_advantages: torch.Tensor, + group_std_rewards: torch.Tensor, + prompt_ids: torch.Tensor, + prompt_mask: torch.Tensor, + completion_ids: torch.Tensor, + completion_mask: torch.Tensor, + forward_kwargs: dict, + optional_vision_fields: list[str] = None, + old_per_token_logps: torch.Tensor | None = None, + ref_per_token_logps: torch.Tensor | None = None, + importance_sampling_ratio: float | None = None, + ) -> None: + """ + Update the replay buffer with groups that have reward variance (std > 0). + + Args: + groups_with_variance: Boolean tensor indicating which groups have reward variance + group_advantages: Tensor of shape (num_groups, num_generations) containing advantage values + group_std_rewards: Tensor of shape (num_groups, num_generations) containing std of rewards per group + prompt_ids: Tensor containing prompt token IDs + prompt_mask: Tensor containing prompt attention masks + completion_ids: Tensor containing completion token IDs + completion_mask: Tensor containing completion attention masks + forward_kwargs: Dictionary containing additional prompt inputs (vision data, etc.) + optional_vision_fields: List of optional vision-related fields to include if present in forward_kwargs + old_per_token_logps: Optional tensor of old per-token log probabilities + ref_per_token_logps: Optional tensor of reference per-token log probabilities + importance_sampling_ratio: Optional importance sampling correction ratio + """ + # Prepare buffered outputs for groups with variance + buffered_outputs = [] + for _, group_idx in enumerate(groups_with_variance.nonzero(as_tuple=True)[0].unique().tolist()): + group_prompt_ids, group_prompt_mask = self.slice_group_data(prompt_ids, prompt_mask, group_idx) + group_completion_ids, group_completion_mask = self.slice_group_data( + completion_ids, completion_mask, group_idx + ) + + # Store unpadded data in the buffer + buffered_output = { + "prompt_ids": group_prompt_ids, + "completion_ids": group_completion_ids, + "advantages": group_advantages[group_idx].tolist(), + "prompt_mask": group_prompt_mask, + "completion_mask": group_completion_mask, + } + + # Add optional fields if they exist + optional_fields = { + "old_per_token_logps": old_per_token_logps if old_per_token_logps is not None else None, + "ref_per_token_logps": ref_per_token_logps if ref_per_token_logps is not None else None, + } + + for field_name, field_data in optional_fields.items(): + if field_data is not None: + buffered_output[field_name] = self.slice_group_data(field_data, completion_mask, group_idx)[0] + + # Add importance sampling if needed + if self.use_vllm and self.vllm_importance_sampling_correction: + buffered_output["importance_sampling_ratio"] = importance_sampling_ratio + + if optional_vision_fields: + # Add vision-related fields if they exist + for field_name in optional_vision_fields: + if field_name in forward_kwargs: + buffered_output[field_name] = self.slice_group_data( + forward_kwargs[field_name], prompt_mask, group_idx + )[0] + + buffered_outputs.append(buffered_output) + + if groups_with_variance.any(): + # Calculate replay buffer scores for groups with variance + replay_buffer_scores = (group_advantages.abs() * group_std_rewards).sum(dim=-1)[groups_with_variance] + # Add all groups to replay buffer at once (batch operation) + self.replay_buffer.add(replay_buffer_scores.tolist(), buffered_outputs) + + def sample_from_replay_buffer( + self, num_samples: int, optional_vision_fields: list[str] = None, optional_tensor_fields: list[str] = None + ) -> list[dict]: + """ + Sample groups from the replay buffer. + + Args: + num_samples: Number of samples to draw from the replay buffer + optional_vision_fields: List of optional vision-related fields to include if present in sampled data + optional_tensor_fields: List of optional tensor fields to include if present in sampled data + Returns: + List of sampled data dictionaries from the replay buffer + """ + sampled = self.replay_buffer.sample(num_samples=num_samples) + + # Extract and concatenate sampled data + sampled_data = { + "prompt_ids": [], + "prompt_mask": [], + "completion_ids": [], + "completion_mask": [], + "advantages": [], + } + + all_optional_fields = (optional_tensor_fields or []) + (optional_vision_fields or []) + # Initialize containers for optional fields if they exist in sampled data + for field in all_optional_fields: + if sampled and field in sampled[0]: + sampled_data[field] = [] + + # Extract data from each sampled item + for item in sampled: + # Handle core fields + for key in ["prompt_ids", "prompt_mask", "completion_ids", "completion_mask"]: + sampled_data[key].append(item[key]) + + # Handle advantages (list, not tensor) + sampled_data["advantages"].append(item["advantages"]) + + # Handle optional fields + for field in all_optional_fields: + if field in item: + sampled_data[field].append(item[field]) + + return sampled_data + + def update_with_replay_buffer( + self, + group_advantages: torch.Tensor, + group_std_rewards: torch.Tensor, + prompt_ids: torch.Tensor, + prompt_mask: torch.Tensor, + completion_ids: torch.Tensor, + completion_mask: torch.Tensor, + forward_kwargs: dict, + num_items_in_batch: int, + old_per_token_logps: torch.Tensor | None = None, + ref_per_token_logps: torch.Tensor | None = None, + importance_sampling_ratio: float | None = None, + ) -> None: + """ + Update current batch data with samples from replay buffer. + + Groups with reward variance (std > 0) are added to the replay buffer and then replaced with samples from the + buffer to improve training stability. + + Args: + group_advantages: Tensor of shape (num_groups, num_generations) containing advantage values + group_std_rewards: Tensor of shape (num_groups, num_generations) containing std of rewards per group + prompt_ids: Tensor containing prompt token IDs + prompt_mask: Tensor containing prompt attention masks + completion_ids: Tensor containing completion token IDs + completion_mask: Tensor containing completion attention masks + forward_kwargs: Dictionary containing additional prompt inputs (vision data, etc.) + num_items_in_batch: Number of items in the current batch + old_per_token_logps: Optional tensor of old per-token log probabilities + ref_per_token_logps: Optional tensor of reference per-token log probabilities + importance_sampling_ratio: Optional importance sampling correction ratio + """ + if self.replay_buffer.max_size <= 0: + return + + # Groups to consider for adding to the replay buffer + groups_with_variance = group_std_rewards.max(dim=0).values > 0 + # Groups to replace from the replay buffer + groups_without_variance = ~groups_with_variance + + # Track which optional fields are present in sampled data + optional_tensor_fields = ["old_per_token_logps", "ref_per_token_logps"] + vision_fields = ["pixel_values", "image_grid_thw", "pixel_attention_mask", "image_sizes"] + + self.update_replay_buffer( + groups_with_variance, + group_advantages, + group_std_rewards, + prompt_ids, + prompt_mask, + completion_ids, + completion_mask, + forward_kwargs, + vision_fields, + old_per_token_logps, + ref_per_token_logps, + importance_sampling_ratio, + ) + + # Sample from replay buffer to replace groups with variance + num_groups_to_replace = groups_without_variance.sum().item() + if not num_groups_to_replace: + return + + sampled_data = self.sample_from_replay_buffer( + num_samples=num_groups_to_replace, + optional_vision_fields=vision_fields, + optional_tensor_fields=optional_tensor_fields, + ) + + # Pad sampled data if they are shorter than the current batch sequences + # Or pad the current batch if sampled are longer + current_batch_prompt_seq_len = prompt_ids.size(1) + current_batch_completion_seq_len = completion_ids.size(1) + + groups_to_replace_idxs = groups_with_variance.logical_not().nonzero(as_tuple=True)[0].unique().tolist() + + # Determine target (max) sequence lengths once + sampled_prompt_lengths = [t.size(1) for t in sampled_data["prompt_ids"]] + sampled_completion_lengths = [t.size(1) for t in sampled_data["completion_ids"]] + target_prompt_len = max([current_batch_prompt_seq_len] + sampled_prompt_lengths) + target_completion_len = max([current_batch_completion_seq_len] + sampled_completion_lengths) + + # If any sampled prompt is longer, pad the whole batch prompt tensors once (left padding) + if target_prompt_len > current_batch_prompt_seq_len: + prompt_ids = pad( + list(prompt_ids.unbind(0)), + padding_value=self._tokenizer.pad_token_id, + pad_to_multiple_of=target_prompt_len, + padding_side="left", + ) + prompt_mask = pad( + list(prompt_mask.unbind(0)), padding_value=0, pad_to_multiple_of=target_prompt_len, padding_side="left" + ) + # If any sampled completion is longer, pad the whole batch completion tensors once (right padding) + if target_completion_len > current_batch_completion_seq_len: + completion_ids = pad( + list(completion_ids.unbind(0)), + padding_value=self._tokenizer.pad_token_id, + pad_to_multiple_of=target_completion_len, + padding_side="right", + ) + completion_mask = pad( + list(completion_mask.unbind(0)), + padding_value=0, + pad_to_multiple_of=target_completion_len, + padding_side="right", + ) + if old_per_token_logps is not None: + old_per_token_logps = pad( + list(old_per_token_logps.unbind(0)), + padding_value=0.0, + pad_to_multiple_of=target_completion_len, + padding_side="right", + ) + if ref_per_token_logps is not None: + ref_per_token_logps = pad( + list(ref_per_token_logps.unbind(0)), + padding_value=0.0, + pad_to_multiple_of=target_completion_len, + padding_side="right", + ) + + # Replace per-group data, padding only sampled groups that are shorter than the target + for i, group_idx in enumerate(groups_to_replace_idxs): + start_idx = group_idx * self.num_generations + end_idx = (group_idx + 1) * self.num_generations + idx_range = slice(start_idx, end_idx) + + # Pad sampled prompt to target length if needed + if sampled_data["prompt_ids"][i].size(1) < target_prompt_len: + sampled_data["prompt_ids"][i] = pad( + sampled_data["prompt_ids"][i], + padding_value=self._tokenizer.pad_token_id, + pad_to_multiple_of=target_prompt_len, + padding_side="left", + ) + sampled_data["prompt_mask"][i] = pad( + sampled_data["prompt_mask"][i], + padding_value=0, + pad_to_multiple_of=target_prompt_len, + padding_side="left", + ) + + # Pad sampled completion to target length if needed + if sampled_data["completion_ids"][i].size(1) < target_completion_len: + sampled_data["completion_ids"][i] = pad( + sampled_data["completion_ids"][i], + padding_value=self._tokenizer.pad_token_id, + pad_to_multiple_of=target_completion_len, + padding_side="right", + ) + sampled_data["completion_mask"][i] = pad( + sampled_data["completion_mask"][i], + padding_value=0, + pad_to_multiple_of=target_completion_len, + padding_side="right", + ) + if "old_per_token_logps" in sampled_data: + sampled_data["old_per_token_logps"][i] = pad( + sampled_data["old_per_token_logps"][i], + padding_value=0.0, + pad_to_multiple_of=target_completion_len, + padding_side="right", + ) + if "ref_per_token_logps" in sampled_data: + sampled_data["ref_per_token_logps"][i] = pad( + sampled_data["ref_per_token_logps"][i], + padding_value=0.0, + pad_to_multiple_of=target_completion_len, + padding_side="right", + ) + + # Assign (replace) group slice + prompt_ids[idx_range] = sampled_data["prompt_ids"][i] + prompt_mask[idx_range] = sampled_data["prompt_mask"][i] + completion_ids[idx_range] = sampled_data["completion_ids"][i] + completion_mask[idx_range] = sampled_data["completion_mask"][i] + group_advantages[group_idx] = sampled_data["advantages"][i] + + if "old_per_token_logps" in sampled_data: + old_per_token_logps[idx_range] = sampled_data["old_per_token_logps"][i] + if "ref_per_token_logps" in sampled_data: + ref_per_token_logps[idx_range] = sampled_data["ref_per_token_logps"][i] + + for field in vision_fields: + if field in sampled_data and field in forward_kwargs: + forward_kwargs[field][idx_range] = sampled_data[field][i] + + # Prepare final outputs after sampling and replacement + outputs_after_sampling_buffer = { + "prompt_ids": prompt_ids, + "prompt_mask": prompt_mask, + "completion_ids": completion_ids, + "completion_mask": completion_mask, + "advantages": group_advantages, + } + + # Replace optional tensor fields if they exist + for field in optional_tensor_fields: + if field in sampled_data: + outputs_after_sampling_buffer[field] = ( + old_per_token_logps if field == "old_per_token_logps" else ref_per_token_logps + ) + + # Replace vision fields if they exist + for field in vision_fields: + if field in sampled_data and field in forward_kwargs: + outputs_after_sampling_buffer[field] = forward_kwargs[field] + + outputs_after_sampling_buffer["num_items_in_batch"] = num_items_in_batch + if self.use_vllm and self.vllm_importance_sampling_correction: + outputs_after_sampling_buffer["importance_sampling_ratio"] = importance_sampling_ratio + + return outputs_after_sampling_buffer diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gspo_token/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gspo_token/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4c9814fddca65cfe8d5ccabccc9d646141e19364 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gspo_token/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .grpo_trainer import GRPOTrainer diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gspo_token/grpo_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gspo_token/grpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..2e2cc940b23361f76886ef4dee93e0e9b360327b --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/gspo_token/grpo_trainer.py @@ -0,0 +1,161 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch + +from ...trainer.grpo_trainer import GRPOTrainer as _GRPOTrainer +from ...trainer.utils import nanmax, nanmin + + +class GRPOTrainer(_GRPOTrainer): + def _compute_loss(self, model, inputs): + # Compute the per-token log probabilities for the model + prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"] + completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"] + input_ids = torch.cat([prompt_ids, completion_ids], dim=1) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + + # Compute the per_token_logps and the entropy at each position in the completion + per_token_logps, entropies, _ = self._get_per_token_logps_and_entropies( + model, + input_ids, + attention_mask, + logits_to_keep, + compute_entropy=True, + pixel_values=inputs.get("pixel_values"), + image_grid_thw=inputs.get("image_grid_thw"), + num_images=inputs.get("num_images"), + pixel_attention_mask=inputs.get("pixel_attention_mask"), + image_sizes=inputs.get("image_sizes"), + token_type_ids=inputs.get("token_type_ids"), + ) + + if self.top_entropy_quantile < 1.0: + entropy_mask = self.get_high_entropy_mask(entropies, completion_mask, 1 - self.top_entropy_quantile) + else: + entropy_mask = None + + # Compute the KL divergence between the model and the reference model + if self.beta != 0.0: + ref_per_token_logps = inputs["ref_per_token_logps"] + per_token_kl = ( + torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1 + ) + + # Compute the loss + advantages = inputs["advantages"] + # In the base GRPO implementation, advantages are expected to have shape (B,). To support subclasses that + # provide advantages with shape (B, T) (e.g., MiniLLM), we *conditionally* unsqueeze the tensor. + if advantages.dim() == 1: + advantages = advantages.unsqueeze(1) + # When num_iterations == 1 and steps_per_generation <= gradient_accumulation_steps, + # old_per_token_logps == per_token_logps. In this case we can skip its computation + # (see _generate_and_score_completions) and instead use per_token_logps.detach(). + # The exception is when using vLLM, where we always compute old_per_token_logps + # for importance sampling + old_per_token_logps = inputs.get("old_per_token_logps") + old_per_token_logps = per_token_logps.detach() if old_per_token_logps is None else old_per_token_logps + + log_ratio = per_token_logps - old_per_token_logps + if self.importance_sampling_level == "token": + log_importance_weights = log_ratio + elif self.importance_sampling_level == "sequence": + log_importance_weights = (log_ratio * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0) + log_importance_weights = log_importance_weights.unsqueeze(-1) + elif self.importance_sampling_level == "sequence_token": + # GSPO-token: sg[si(θ)] * πθ(yi,t)/sg[πθ(yi,t)] + seq_level_log_weight = (log_ratio * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0) + seq_level_log_weight = seq_level_log_weight.detach().unsqueeze(-1) # Stop gradient + log_importance_weights = per_token_logps - per_token_logps.detach() + seq_level_log_weight + else: + raise ValueError( + f"Unknown importance sampling level: {self.importance_sampling_level}. Possible values are 'token' " + "and 'sequence'." + ) + # From here, log_importance_weights (and all subsequent tensors, coef_1, coef_2, etc.) shape depends on + # importance_sampling_level: "token" level: (B, T); "sequence" level: (B, 1) + + coef_1 = torch.exp(log_importance_weights) + coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high) + + # Two-sided clipping + if self.args.delta is not None: + coef_1 = torch.clamp(coef_1, max=self.args.delta) + + per_token_loss1 = coef_1 * advantages + per_token_loss2 = coef_2 * advantages + per_token_loss = -torch.min(per_token_loss1, per_token_loss2) + if entropy_mask is not None: + per_token_loss = per_token_loss * entropy_mask + + if self.use_vllm and self.vllm_importance_sampling_correction: + per_token_loss = per_token_loss * inputs["importance_sampling_ratio"] + + if self.beta != 0.0: + per_token_loss = per_token_loss + self.beta * per_token_kl + + mode = "train" if self.model.training else "eval" + if self.loss_type == "grpo": + loss = ((per_token_loss * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0)).mean() + normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval + loss = loss / normalizer + elif self.loss_type == "bnpo": + loss = (per_token_loss * completion_mask).sum() / completion_mask.sum().clamp(min=1.0) + normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval + loss = loss / normalizer + elif self.loss_type == "dr_grpo": + loss = (per_token_loss * completion_mask).sum() / (per_token_loss.size(0) * self.max_completion_length) + normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval + loss = loss / normalizer + elif self.loss_type == "dapo": + normalizer = inputs["num_items_in_batch"] / self.accelerator.num_processes + loss = (per_token_loss * completion_mask).sum() / normalizer + else: + raise ValueError(f"Unknown loss type: {self.loss_type}") + + # Log the metrics + completion_token_count = completion_mask.sum().clamp(min=1.0) + + def masked_batch_mean(x): + if x.shape[1] == 1: # when importance_sampling_level == "sequence" + return x.mean() + else: + return (x * completion_mask).sum() / completion_token_count + + if self.beta != 0.0: + mean_kl = masked_batch_mean(per_token_kl) + self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item()) + + mean_entropy = masked_batch_mean(entropies) + self._metrics[mode]["entropy"].append(self.accelerator.gather(mean_entropy).nanmean().item()) + + # Compute the clipped probability ratios + is_low_clipped = (coef_1 < 1 - self.epsilon_low) & (advantages < 0) + is_high_clipped = (coef_1 > 1 + self.epsilon_high) & (advantages > 0) + is_region_clipped = is_low_clipped | is_high_clipped + + low_clip = masked_batch_mean(is_low_clipped.float()) + high_clip = masked_batch_mean(is_high_clipped.float()) + clip_ratio = masked_batch_mean(is_region_clipped.float()) + + gathered_low_clip = self.accelerator.gather(low_clip) + self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item()) + self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item()) + gathered_high_clip = self.accelerator.gather(high_clip) + self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item()) + self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item()) + gathered_clip_ratio = self.accelerator.gather(clip_ratio) + self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item()) + return loss diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/harbor/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/harbor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..54b8d243e40b5f288090501ca79d71aef23a9e38 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/harbor/__init__.py @@ -0,0 +1,32 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Harbor × TRL integration (experimental). + +Train on Harbor agentic task suites with `GRPOTrainer` via `environment_factory`, with a pluggable base agent +(harness). Requires `harbor` installed in the same interpreter (`pip install trl[harbor]`, Python >= 3.12); `harbor` is +imported lazily so this module imports without it. + +```python +>>> from trl.experimental.harbor import HarborSpec + +>>> spec = HarborSpec("AdithyaSK/data_agent_rl_environment_train", agent="bash", num_tasks=64) +``` +""" + +from ._env import AGENTS, HarborBashEnv, HarborEnv +from ._spec import HarborSpec + + +__all__ = ["AGENTS", "HarborBashEnv", "HarborEnv", "HarborSpec"] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/harbor/_env.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/harbor/_env.py new file mode 100644 index 0000000000000000000000000000000000000000..fdef9800e264cc283b7c955e9195080b8f6032d2 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/harbor/_env.py @@ -0,0 +1,231 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Harbor-backed environments for `GRPOTrainer(environment_factory=...)`. + +A `HarborEnv` wraps a Harbor sandbox + verifier. TRL drives the rollout loop: it calls the env's tool methods during +generation and reads `env.reward` afterwards. The pluggable "base agent" is the harness — the set of tool methods the +env exposes + how it submits. `HarborBashEnv` is the single-`bash`-tool harness (submit by writing +`/workdir/answer.txt`); subclass `HarborEnv` to add your own. + +Harbor's API is async and its sandbox client is bound to the event loop it was created on, so each env owns one loop +and drives start/exec/verify/stop through it synchronously (TRL's tool loop is sync). `harbor` is imported lazily, so +importing this module does not require it installed (install `trl[harbor]`, which needs Python >= 3.12). +""" + +import asyncio +import tempfile +import threading +import uuid +from pathlib import Path + + +_NO_REWARD = object() # sentinel: reward not computed yet (0.0 is a valid reward) + + +class HarborEnv: + """Base TRL environment backed by a Harbor sandbox + verifier. + + Subclasses define the tool methods (the harness). The lifecycle TRL drives per rollout: `reset(task_dir)` (start + the task's sandbox, return its instruction) -> tool methods (exec into the sandbox) -> `reward` (run the verifier + once, lazily, after the rollout). + + Args: + environment_type (`str`, *optional*, defaults to `"docker"`): + Harbor sandbox backend, passed through to Harbor (`"docker"`, `"e2b"`, `"daytona"`, ...). + """ + + #: Extra guidance appended to the task instruction by the harness subclass. + PROMPT_SUFFIX: str = "" + + def __init__(self, environment_type: str = "docker"): + self._environment_type = environment_type + # Harbor's async sandbox client is bound to the loop it was created on, so we run that loop on a + # dedicated daemon thread and submit coroutines to it via `run_coroutine_threadsafe`. This works + # whether the caller is on a plain thread (GRPOTrainer drives tools from the main thread) or + # already inside a running event loop (AsyncGRPOTrainer's rollout worker calls tool methods from + # its own loop, where `loop.run_until_complete` would raise "another loop is already running"). + self._loop = asyncio.new_event_loop() + self._loop_thread = threading.Thread(target=self._loop.run_forever, daemon=True) + self._loop_thread.start() + self._env = None # harbor BaseEnvironment for the current task + self._task = None + self._paths = None + self._reward = _NO_REWARD + + def _run(self, coro): + """Run a coroutine on this env's loop (which lives on its own thread) and block for the result.""" + return asyncio.run_coroutine_threadsafe(coro, self._loop).result() + + def reset(self, task_dir: str | None = None, **kwargs) -> str: + if task_dir is None: + raise ValueError("HarborEnv.reset requires `task_dir` (provided by the dataset row).") + instruction = self._run(self._start(task_dir)) + self._reward = _NO_REWARD + return instruction + self.PROMPT_SUFFIX + + def _exec(self, command: str, timeout: int = 180) -> str: + """Run a shell command in the sandbox; return combined stdout+stderr (truncated to 8k).""" + result = self._run(self._env.exec(command, timeout_sec=timeout)) + out = (result.stdout or "") + (result.stderr or "") + if len(out) > 8000: + out = out[:8000] + "\n... [truncated]" + return out or f"(empty output, rc={result.return_code})" + + @property + def reward(self) -> float: + # Submission = the agent wrote /workdir/answer.txt during the rollout; the verifier reads it. + # Computed once, lazily, on first read (TRL reads this after the rollout via reward_funcs). + # A fresh env that was never `reset` (e.g. the trainer probing tool methods via + # `inspect.getmembers`, which evaluates properties) has no sandbox/task to verify — return 0.0 + # without invoking the verifier, which would start the Harbor backend and import `harbor`. + if self._env is None: + return 0.0 + if self._reward is _NO_REWARD: + self._reward = self._run(self._verify()) + return self._reward + + # ── harbor lifecycle (async, run on this env's loop) ──────────────────── + + async def _start(self, task_dir: str) -> str: + from harbor.environments.factory import EnvironmentFactory + from harbor.models.task.task import Task + from harbor.models.trial.config import EnvironmentConfig as TrialEnvironmentConfig + from harbor.models.trial.paths import TrialPaths + + await self._stop() # tear down the previous task's sandbox + self._task = Task(task_dir=Path(task_dir)) + self._paths = TrialPaths(trial_dir=Path(tempfile.mkdtemp(prefix="harbor_trl_"))) + self._env = EnvironmentFactory.create_environment_from_config( + config=TrialEnvironmentConfig(type=self._environment_type), + environment_dir=self._task.paths.environment_dir, + environment_name=self._task.short_name, + session_id=uuid.uuid4().hex, + trial_paths=self._paths, + task_env_config=self._task.config.environment, + ) + await self._env.start(force_build=False) + await self._upload_build_files() # some sandbox builds (e.g. E2B from_dockerfile) drop COPY'd files + await self._env.run_healthcheck() # task pre-agent hook (e.g. pull data into /home/user/input) + await self._env.exec("mkdir -p /workdir /home/user/input") + await self._setup() # harness-specific sandbox prep (e.g. start a Jupyter kernel) + return self._task.instruction + + async def _upload_build_files(self) -> None: + """Replicate the task Dockerfile's `COPY` directives into the sandbox. + + E2B's remote `from_dockerfile` build honors `RUN` steps but silently drops files `COPY`'d from the build + context, which breaks healthchecks that run those files (e.g. a data-pull script). We re-create them at + runtime: `upload_file` writes as the sandbox `user`, so we stage each file in a user-writable tmp path and `mv` + it into place as root (destinations like `/opt` are root-owned). Idempotent. Handles the common ``COPY + `` form; flags / globs / ``--from`` are skipped. + """ + dockerfile = self._task.paths.environment_dir / "Dockerfile" + if not dockerfile.exists(): + return + for line in dockerfile.read_text().splitlines(): + s = line.strip() + if not s.upper().startswith("COPY ") or "--from" in s: + continue + parts = [p for p in s[len("COPY ") :].split() if not p.startswith("--")] + if len(parts) < 2: + continue + *srcs, dst = parts + for src in srcs: + local = self._task.paths.environment_dir / src + if not local.is_file(): + continue + remote = dst if (len(srcs) == 1 and not dst.endswith("/")) else dst.rstrip("/") + "/" + Path(src).name + parent = remote.rsplit("/", 1)[0] or "/" + tmp = "/tmp/" + uuid.uuid4().hex + await self._env.upload_file(local, tmp) + await self._env.exec(f"mkdir -p {parent} && mv {tmp} {remote}", user="root") + + async def _setup(self) -> None: + """Harness-specific sandbox preparation, run once per `reset` after the sandbox is up. + + Override to upload helper files (`await self._env.upload_file(...)`) or start servers in the sandbox. The + default is a no-op (the bash harness needs nothing beyond the base setup). + """ + + async def _verify(self) -> float: + from harbor.models.trial.config import VerifierConfig + from harbor.models.trial.paths import EnvironmentPaths + from harbor.verifier.factory import VerifierFactory + + # Pre-create the verifier dir (test.sh redirects stdout there; the shell can't mkdir the parent). + env_paths = EnvironmentPaths.for_os(self._env.os) + await self._env.empty_dirs([env_paths.verifier_dir], chmod=True) + # Carry the task's [verifier].env (e.g. expected-answer / judge-model settings) into the verifier, + # mirroring Harbor's trial runner (`override_env=`). A default trial `VerifierConfig()` is otherwise + # correct here — the task verifier has no trial-level import_path/kwargs to forward. + verifier = VerifierFactory.create_verifier_from_config( + VerifierConfig(), + task=self._task, + trial_paths=self._paths, + environment=self._env, + override_env=self._task.config.verifier.env or None, + ) + result = await verifier.verify() + rewards = result.rewards or {} + return float(rewards.get("reward", next(iter(rewards.values()), 0.0))) + + async def _stop(self) -> None: + if self._env is not None: + try: + await self._env.stop(delete=True) + finally: + self._env = None + + def __del__(self): + try: + self._run(self._stop()) + except Exception: # noqa: BLE001 — best-effort teardown + pass + finally: + self._loop.call_soon_threadsafe(self._loop.stop) + + +_BASH_PROMPT_SUFFIX = ( + "\n\nYou have a single `bash` tool: run a shell command in the sandbox and get its stdout+stderr. " + "The dataset files are in /home/user/input/. Python 3 + pandas + numpy + scikit-learn are " + "preinstalled. **Submit your final answer by writing it to /workdir/answer.txt via the `bash` " + 'tool**, e.g. `echo -n "" > /workdir/answer.txt`. Stating the answer in prose does NOT submit ' + "it; only writing the file counts. Keep the answer short, and do not end your turn without submitting." +) + + +class HarborBashEnv(HarborEnv): + """Single-`bash`-tool harness; submit by writing `/workdir/answer.txt`.""" + + PROMPT_SUFFIX = _BASH_PROMPT_SUFFIX + + def bash(self, command: str) -> str: + """ + Run a shell command in the sandbox and return its combined stdout+stderr. The shell is non-stateful between + calls. Use it to explore files (ls, head, cat), run Python (`python3 -c "..."`), and submit the answer (`echo + -n "" > /workdir/answer.txt`). + + Args: + command: The shell command to run. + + Returns: + The command's combined stdout and stderr. + """ + return self._exec(command) + + +#: Built-in harnesses, selectable by name in `HarborSpec(agent=...)`. Pass a `HarborEnv` subclass (or an +#: import path / file path resolving to one) for a custom harness. +AGENTS: dict[str, type[HarborEnv]] = {"bash": HarborBashEnv} diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/harbor/_spec.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/harbor/_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..47240607e0bf425dd5cf438a720a61cf18248057 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/harbor/_spec.py @@ -0,0 +1,216 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""User-facing spec for the Harbor × TRL integration (mirror of ``OpenRewardSpec``). + +Construct **one** ``HarborSpec`` and read three properties off it — ``.train_dataset``, ``.environment_factory``, +``.reward_funcs`` — each plugging into the matching ``GRPOTrainer`` kwarg: + +```python +>>> from trl import GRPOConfig, GRPOTrainer +>>> from trl.experimental.harbor import HarborSpec + +>>> spec = HarborSpec("AdithyaSK/data_agent_rl_environment_train", agent="bash", num_tasks=64) + +>>> trainer = GRPOTrainer( +... model="Qwen/Qwen3.5-4B", +... args=GRPOConfig(num_generations=8, max_steps=50, max_tool_calling_iterations=25), +... train_dataset=spec.train_dataset, +... environment_factory=spec.environment_factory, +... reward_funcs=spec.reward_funcs, +... ) +>>> trainer.train() +``` + +A Harbor *task* is a directory (``instruction.md`` + ``task.toml`` + ``environment/`` + ``tests/``); the dataset is a +tree of them. The ``environment_factory`` env runs Harbor in-process (see ``_env.py``), so ``harbor`` must be installed +in the same interpreter (``pip install trl[harbor]``, Python >= 3.12). The **base agent** (harness/tool surface) is +selected by ``agent=`` — ``"bash"`` today, or a custom ``HarborEnv`` subclass. +""" + +from __future__ import annotations + +import os +from collections.abc import Callable +from functools import cached_property, partial +from pathlib import Path +from typing import Any + +from ._env import AGENTS, HarborEnv + + +def _outcome_reward_func(environments=None, environment_reward=None, **_) -> list[float]: + """Default reward: the Harbor verifier's scalar per rollout. + + `GRPOTrainer` passes the live env instances as `environments=` (read `env.reward`); `AsyncGRPOTrainer` runs envs in + its rollout worker and passes the already-captured per-rollout rewards as `environment_reward=`. Support both so + the same spec plugs into either trainer. + """ + if environment_reward is not None: + return [float(r) for r in environment_reward] + return [float(env.reward) for env in environments] + + +def _resolve_agent(agent: str | type[HarborEnv]) -> type[HarborEnv]: + """Resolve the `agent=` selector to a `HarborEnv` subclass. + + Accepts a `HarborEnv` subclass, a built-in name (`"bash"`), a module import path (`"pkg.module:Class"`), or a file + path (`"path/to/file.py:Class"`). + """ + if isinstance(agent, type): + cls = agent + elif agent in AGENTS: + cls = AGENTS[agent] + elif ":" in agent: + import importlib + import importlib.util + + target, _, cls_name = agent.rpartition(":") # rpartition: don't split a Windows drive (``D:\...``) + if target.endswith(".py") or os.path.sep in target: # file path -> load module from file + spec = importlib.util.spec_from_file_location(Path(target).stem, target) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + else: # dotted module path on sys.path + module = importlib.import_module(target) + cls = getattr(module, cls_name) + else: + raise ValueError( + f"Unknown agent {agent!r}; use a built-in name ({sorted(AGENTS)}), an import path " + "'pkg.module:Class', a file path 'path/to/file.py:Class', or a HarborEnv subclass." + ) + if not (isinstance(cls, type) and issubclass(cls, HarborEnv)): + raise TypeError(f"agent {agent!r} must resolve to a HarborEnv subclass, got {cls!r}") + return cls + + +def _read_task_meta(task_dir: Path) -> dict[str, Any]: + """Pull a few useful fields out of ``task.toml`` for the dataset rows / reward funcs.""" + try: + import tomllib # stdlib on Python 3.11+; lazy so the module imports on 3.10 (e.g. doc build) + + cfg = tomllib.loads((task_dir / "task.toml").read_text()) + except Exception: # noqa: BLE001 + return {} + meta = cfg.get("metadata", {}) + return { + "gold_answer": meta.get("gold_answer"), + "reward_mode": meta.get("reward_mode_initial"), + "difficulty_level": meta.get("difficulty_level"), + "kaggle_dataset": meta.get("kaggle_dataset_name"), + } + + +class HarborSpec: + """Single spec object that wires a Harbor task suite into a TRL trainer. + + Args: + dataset (`str`): + A Hugging Face dataset repo id holding a Harbor task tree (e.g. + `"AdithyaSK/data_agent_rl_environment_train"`), or a local path to a directory containing a `tasks/` + subtree. Each task is a dir with `instruction.md` / `task.toml` / `environment/` / `tests/`. + agent (`str` or `type`, *optional*, defaults to `"bash"`): + The base agent / harness — i.e. the tool surface the env exposes. One of: a built-in name (`"bash"`), an + import path `"package.module:ClassName"`, a file path `"path/to/file.py:ClassName"`, or a + [`~trl.experimental.harbor.HarborEnv`] subclass directly. + environment_type (`str`, *optional*, defaults to `"docker"`): + Harbor sandbox backend, passed through to Harbor (whatever it supports — `"docker"`, `"e2b"`, `"daytona"`, + `"gke"`, `"modal"`, `"runloop"`, ...). Not validated here; Harbor validates. `"docker"` is Harbor's own + default; pick `"e2b"` to offload sandboxing to the cloud. + num_tasks (`int`, *optional*): + Cap on the number of tasks pulled into the dataset. `None` uses every task in the tree. + indices (`list[int]`, *optional*): + Specific task indices (into the sorted task list). Mutually exclusive with `num_tasks`. + include_metadata (`bool`, *optional*, defaults to `True`): + Fold per-task `task.toml` metadata (gold_answer, difficulty, ...) into the dataset rows. + """ + + def __init__( + self, + dataset: str, + *, + agent: str | type[HarborEnv] = "bash", + environment_type: str = "docker", + num_tasks: int | None = None, + indices: list[int] | None = None, + include_metadata: bool = True, + ) -> None: + if num_tasks is not None and indices is not None: + raise ValueError("Provide num_tasks or indices, not both.") + self._dataset = dataset + self._environment_type = environment_type + self._num_tasks = num_tasks + self._indices = indices + self._include_metadata = include_metadata + self._env_cls = _resolve_agent(agent) + + # ── public surface ────────────────────────────────────────────── + + @cached_property + def _task_dirs(self) -> list[Path]: + """Resolve the dataset to a sorted list of local task directories (downloading if needed).""" + local = Path(self._dataset) + if (local / "tasks").is_dir(): + root = local / "tasks" + elif local.is_dir() and any(local.glob("*/task.toml")): + root = local + else: + # Treat as an HF dataset repo id; download the task tree. + from huggingface_hub import snapshot_download + + path = Path(snapshot_download(self._dataset, repo_type="dataset", allow_patterns=["tasks/**"])) + root = path / "tasks" + dirs = sorted(p.parent for p in root.glob("*/task.toml")) + if self._indices is not None: + dirs = [dirs[i] for i in self._indices] + elif self._num_tasks is not None: + dirs = dirs[: self._num_tasks] + if not dirs: + raise ValueError(f"No tasks (dir with task.toml) found under {root}") + return dirs + + @cached_property + def train_dataset(self): + """A `datasets.Dataset` of tasks. Plugs into TRL's `train_dataset=`. + + Columns: `prompt` (empty user message — TRL appends the env's instruction from `reset`), `task_dir` (passed to + `reset`), `task_index`, and per-task metadata when `include_metadata`. + """ + from datasets import Dataset + + dirs = self._task_dirs + rows: dict[str, list[Any]] = { + "prompt": [[{"role": "user", "content": ""}] for _ in dirs], + "task_dir": [str(d) for d in dirs], + # task_index is the position in the sorted suite, so it matches the `indices` selector. + "task_index": list(self._indices) if self._indices is not None else list(range(len(dirs))), + } + if self._include_metadata: + metas = [_read_task_meta(d) for d in dirs] + for key in ("gold_answer", "reward_mode", "difficulty_level", "kaggle_dataset"): + rows[key] = [m.get(key) for m in metas] + return Dataset.from_dict(rows) + + @cached_property + def environment_factory(self) -> Callable[[], HarborEnv]: + """Zero-arg callable returning a fresh harness env. Plugs into TRL's `environment_factory=`. + + Returns a `functools.partial` (not a closure) so it stays picklable — `AsyncGRPOTrainer` runs its rollout + worker in a separate process and pickles the factory to it (closures/lambdas would fail). + """ + return partial(self._env_cls, environment_type=self._environment_type) + + @property + def reward_funcs(self) -> Callable[..., list[float]]: + """Default outcome reward (Harbor verifier scalar). Plugs into TRL's `reward_funcs=`.""" + return _outcome_reward_func diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/kto/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/kto/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d7c21e2316bff7d621faa06622584271ee176d0e --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/kto/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .kto_config import KTOConfig +from .kto_trainer import KTOTrainer + + +__all__ = ["KTOConfig", "KTOTrainer"] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/kto/kto_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/kto/kto_config.py new file mode 100644 index 0000000000000000000000000000000000000000..d3b14f332456c55a3f2859f2c3de7c779a1bbde0 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/kto/kto_config.py @@ -0,0 +1,235 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class KTOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`experimental.kto.KTOTrainer`]. + + This class includes only the parameters that are specific to KTO training. For a full list of training arguments, + please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may + differ from those in [`~transformers.TrainingArguments`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + > Parameters that control the model + + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model` + argument of the [`KTOTrainer`] is provided as a string. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to + [`~transformers.AutoModelForCausalLM.from_pretrained`] and + [`~transformers.AutoProcessor.from_pretrained`]. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model and reference model. + + > Parameters that control the data preprocessing + + dataset_num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + max_length (`int` or `None`, *optional*, defaults to `1024`): + Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from the left. + If `None`, no truncation is applied. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + precompute_ref_log_probs (`bool`, *optional*, defaults to `False`): + Whether to precompute the reference model log probabilities for the entire training dataset before + training. This allows to save memory during training, as the reference model does not need to be kept in + memory. + precompute_ref_batch_size (`int`, *optional*): + Batch size to use when precomputing reference model log probabilities. This can be set higher than the + training batch size to speed up preprocessing. If `None`, defaults to `per_device_train_batch_size` for + training and `per_device_eval_batch_size` for evaluation. + + > Parameters that control the training + + loss_type (`str`, *optional*, defaults to `"kto"`): + Type of loss to use. Possible values are: + + - `"kto"`: KTO loss from the [KTO](https://huggingface.co/papers/2402.01306) paper. + - `"apo_zero_unpaired"`: Unpaired variant of APO-zero loss from the + [APO](https://huggingface.co/papers/2408.06266) paper. + + beta (`float`, *optional*, defaults to `0.1`): + Parameter controlling the deviation from the reference model. Higher β means less deviation from the + reference model. + desirable_weight (`float`, *optional*, defaults to `1.0`): + Desirable losses are weighed by this factor to counter unequal number of desirable and undesirable pairs. + undesirable_weight (`float`, *optional*, defaults to `1.0`): + Undesirable losses are weighed by this factor to counter unequal number of desirable and undesirable pairs. + activation_offloading (`bool`, *optional*, defaults to `False`): + Whether to offload the activations to the CPU. + sync_ref_model (`bool`, *optional*, defaults to `False`): + Whether to synchronize the reference model with the active model every `ref_model_sync_steps` steps, using + the `ref_model_mixup_alpha` parameter. This synchronization originates from the + [TR-DPO](https://huggingface.co/papers/2404.09656) paper. `sync_ref_model=True` is not yet compatible with + PEFT or `precompute_ref_log_probs=True`. + ref_model_mixup_alpha (`float`, *optional*, defaults to `0.6`): + α parameter from the TR-DPO paper, which controls the mix between the current policy and the previous + reference policy during updates. The reference policy is updated according to the equation: `π_ref = α * + π_θ + (1 - α) * π_ref_prev`. To use this parameter, you must set `sync_ref_model=True`. + ref_model_sync_steps (`int`, *optional*, defaults to `512`): + τ parameter from the TR-DPO paper, which determines how frequently the current policy is synchronized with + the reference policy. To use this parameter, you must set `sync_ref_model=True`. + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `1e-6` instead of `5e-5`. + > - `train_sampling_strategy`: Defaults to `"sequential"` instead of `"random"`. Loss types + > that estimate the KL divergence term (all except `"apo_zero_unpaired"`) require sequential + > sampling because the KL completion for each example is precomputed against its neighbors in + > a fixed-order batch; any other strategy breaks that pairing. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=1e-6, + metadata={"help": "The initial learning rate for AdamW."}, + ) + train_sampling_strategy: str = field( + default="sequential", + metadata={ + "help": "Sampler to use for the training dataloader. Loss types that estimate the KL divergence term " + "(all except `'apo_zero_unpaired'`) require `'sequential'` because the KL completion for each example is " + "precomputed against its neighbors in a fixed-order batch; any other strategy breaks that pairing. " + "Possible values are `'random'`, `'sequential'`, and `'group_by_length'`.", + "choices": ["random", "sequential", "group_by_length"], + }, + ) + + # Parameters that control the model + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of " + "the `KTOTrainer` is provided as a string." + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. " + "Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoProcessor.from_pretrained`." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the model and reference model."}, + ) + + # Parameters that control the data preprocessing + dataset_num_proc: int | None = field( + default=None, + metadata={"help": "Number of processes to use for processing the dataset."}, + ) + max_length: int | None = field( + default=1024, + metadata={ + "help": "Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from " + "the left. If `None`, no truncation is applied." + }, + ) + pad_to_multiple_of: int | None = field( + default=None, + metadata={"help": "If set, the sequences will be padded to a multiple of this value."}, + ) + precompute_ref_log_probs: bool = field( + default=False, + metadata={ + "help": "Whether to precompute the reference model log probabilities for the entire training dataset " + "before training. This allows to save memory during training, as the reference model does not need to be " + "kept in memory." + }, + ) + precompute_ref_batch_size: int | None = field( + default=None, + metadata={ + "help": "Batch size to use when precomputing reference model log probabilities. This can be set higher " + "than the training batch size to speed up preprocessing. If `None`, defaults to " + "`per_device_train_batch_size` for training and `per_device_eval_batch_size` for evaluation." + }, + ) + + # Parameters that control the training + loss_type: str = field( + default="kto", + metadata={ + "help": "Type of loss to use.", + "choices": ["kto", "apo_zero_unpaired"], + }, + ) + beta: float = field( + default=0.1, + metadata={ + "help": "Parameter controlling the deviation from the reference model. Higher β means less deviation from " + "the reference model." + }, + ) + desirable_weight: float = field( + default=1.0, + metadata={ + "help": "Desirable losses are weighed by this factor to counter unequal number of desirable and " + "undesirable pairs.", + }, + ) + undesirable_weight: float = field( + default=1.0, + metadata={ + "help": "Undesirable losses are weighed by this factor to counter unequal number of desirable and " + "undesirable pairs.", + }, + ) + activation_offloading: bool = field( + default=False, + metadata={"help": "Whether to offload the activations to the CPU."}, + ) + sync_ref_model: bool = field( + default=False, + metadata={ + "help": "Whether to synchronize the reference model with the active model every `ref_model_sync_steps` " + "steps, using the `ref_model_mixup_alpha` parameter. This synchronization originates from the " + "[TR-DPO](https://huggingface.co/papers/2404.09656) paper. `sync_ref_model=True` is not yet compatible " + "with PEFT or `precompute_ref_log_probs=True`." + }, + ) + ref_model_mixup_alpha: float = field( + default=0.6, + metadata={ + "help": "α parameter from the TR-DPO paper, which controls the mix between the current policy and the " + "previous reference policy during updates. The reference policy is updated according to the equation: " + "`π_ref = α * π_θ + (1 - α) * π_ref_prev`. To use this parameter, you must set `sync_ref_model=True`." + }, + ) + ref_model_sync_steps: int = field( + default=512, + metadata={ + "help": "τ parameter from the TR-DPO paper, which determines how frequently the current policy is " + "synchronized with the reference policy. To use this parameter, you must set `sync_ref_model=True`." + }, + ) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/kto/kto_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/kto/kto_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..278646522dbb21bf98f613ccf76444c125eca0bb --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/kto/kto_trainer.py @@ -0,0 +1,1534 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import contextlib +import os +import textwrap +from collections import defaultdict +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import torch +import transformers +from accelerate import PartialState +from accelerate.logging import get_logger +from accelerate.utils import is_peft_model, tqdm +from datasets import Dataset, IterableDataset, IterableDatasetDict, concatenate_datasets +from datasets.fingerprint import Hasher +from packaging.version import Version +from torch.nn import functional as F +from torch.utils.data import DataLoader, Sampler, SequentialSampler +from transformers import ( + AutoProcessor, + DataCollator, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, +) +from transformers.data.data_collator import DataCollatorMixin +from transformers.trainer_utils import EvalLoopOutput, has_length +from transformers.utils import is_peft_available + +from ...data_utils import ( + apply_chat_template, + extract_prompt, + is_conversational, + prepare_multimodal_messages, + unpair_preference_dataset, +) +from ...import_utils import is_liger_kernel_available +from ...models import get_act_offloading_ctx_manager +from ...models.utils import disable_gradient_checkpointing, prepare_deepspeed, prepare_fsdp +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.callbacks import SyncRefModelCallback +from ...trainer.utils import ( + create_model_from_path, + disable_dropout_in_model, + flush_left, + get_config_model_id, + hash_module, + pad, + selective_log_softmax, + use_adapter, +) +from .kto_config import KTOConfig + + +if is_liger_kernel_available(): + from liger_kernel.chunked_loss import LigerFusedLinearKTOLoss + +if is_peft_available(): + import peft + from peft import LoraConfig, PeftConfig, PeftModel, get_peft_model + + +logger = get_logger(__name__) + +RUNNING_NAME = "running.pt" + + +def get_dataset_column_names(dataset: Dataset | IterableDataset) -> list[str]: + return list(next(iter(dataset)).keys()) if dataset.column_names is None else dataset.column_names + + +def _get_kl_completion_ids(batch: dict[str, list[Any]]) -> dict[str, list[Any]]: + """ + Creates mismatched pairs of prompts and completions for the KL dataset by adding a +1 offset to the order of + completions. For best results, the mismatched outputs y' used to estimate the KL term for a batch should be the + same set as the matched outputs y used to estimate the rewards in that batch, just paired with different x. + """ + batch["completion_ids"] = [batch["completion_ids"][-1]] + batch["completion_ids"][:-1] + return batch + + +@dataclass +class DataCollatorForUnpairedPreference(DataCollatorMixin): + """ + Data collator for unpaired preference data. Assembles completions from raw token IDs and pads sequences to the + maximum length of the batch. + + Each example is expected to contain `"prompt_ids"`, `"completion_ids"` (and optionally `"KL_completion_ids"`) keys. + The collator returns a dictionary with the following keys for each prefix (`"completion"` and, if present, + `"KL_completion"`): + - `"{prefix}_input_ids"`: full prompt + completion token IDs, padded to the batch maximum length. + - `"{prefix}_attention_mask"`: attention mask, padded with 0s. + - `"{prefix}_mask"`: binary mask where 1 marks completion tokens and 0 marks prompt or padding tokens. + + Args: + pad_token_id (`int`): + Token ID to use for padding `input_ids` sequences. + max_length (`int`, *optional*): + Maximum sequence length after assembly. Sequences longer than `max_length` are truncated from the end. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + return_tensors (`str`, *optional*, defaults to `"pt"`): + The tensor type to return. Currently, only `"pt"` (PyTorch tensors) is supported. + """ + + pad_token_id: int + max_length: int | None = None + pad_to_multiple_of: int | None = None + return_tensors: str = "pt" + + def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + batch = {} + for prefix, ids_key in [("completion", "completion_ids"), ("KL_completion", "KL_completion_ids")]: + if ids_key not in examples[0]: + continue + + full_ids_list = [] + completion_mask_list = [] + for ex in examples: + prompt_ids = ex["prompt_ids"] + answer_ids = ex[ids_key] + full_ids = prompt_ids + answer_ids + completion_mask = [0] * len(prompt_ids) + [1] * len(answer_ids) + if self.max_length is not None: + full_ids = full_ids[: self.max_length] + completion_mask = completion_mask[: self.max_length] + full_ids_list.append(full_ids) + completion_mask_list.append(completion_mask) + + batch[f"{prefix}_input_ids"] = pad( + [torch.tensor(ids, dtype=torch.int64) for ids in full_ids_list], + padding_value=self.pad_token_id, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + batch[f"{prefix}_attention_mask"] = pad( + [torch.ones(len(ids), dtype=torch.int64) for ids in full_ids_list], + padding_value=0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + batch[f"{prefix}_mask"] = pad( + [torch.tensor(m, dtype=torch.int64) for m in completion_mask_list], + padding_value=0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + + if "ref_logps" in examples[0]: + batch["ref_logps"] = torch.tensor([ex["ref_logps"] for ex in examples]) + if "ref_KL_logps" in examples[0]: + batch["ref_KL_logps"] = torch.tensor([ex["ref_KL_logps"] for ex in examples]) + batch["label"] = [ex["label"] for ex in examples] + return batch + + +@dataclass +class DataCollatorForVisionUnpairedPreference(DataCollatorMixin): + """ + Data collator for vision unpaired preference data. Performs tokenization and image processing on-the-fly. + + Unlike the text-only [`DataCollatorForUnpairedPreference`], this collator does not expect pre-tokenized inputs. + Instead, it takes raw examples with `"prompt"`, `"completion"`, and `"images"` (or `"image"`) keys and processes + them at collation time. When `calculate_kl` is `True`, the collator also produces KL sequences by cycling + completions within the batch — the same mismatching strategy as the text-only path, but done here rather than as a + dataset pre-processing step. + + Each input example should contain at least: + - A `"prompt"` key with either a plain text string or a list of message dicts. + - A `"completion"` key with a plain text string or a list of message dicts. + - An `"images"` key holding a list of images, or an `"image"` key holding a single image. + - A `"label"` key (`bool`) indicating whether the completion is desirable. + + The collator outputs: + - `"completion_input_ids"`, `"completion_attention_mask"`, `"completion_mask"`: full prompt+completion sequence. + - `"pixel_values"` and any additional processor outputs (e.g., `"image_grid_thw"`). + - `"label"`: list of booleans. + - When `calculate_kl=True`: `"KL_completion_input_ids"`, `"KL_completion_attention_mask"`, `"KL_completion_mask"` + for the cycled KL sequences. + + Args: + processor ([`~transformers.ProcessorMixin`]): + The processor used to tokenize text and process images. + max_length (`int`, *optional*): + Maximum sequence length. Sequences longer than `max_length` are truncated. + calculate_kl (`bool`, *optional*, defaults to `True`): + Whether to produce KL sequences by cycling completions within the batch. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + return_tensors (`str`, *optional*, defaults to `"pt"`): + The tensor type to return. Only `"pt"` is supported. + """ + + processor: ProcessorMixin + max_length: int | None = None + calculate_kl: bool = True + pad_to_multiple_of: int | None = None + return_tensors: str = "pt" + + def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + if self.pad_to_multiple_of is not None: + raise NotImplementedError( + "Padding to a multiple of a value is not yet implemented for vision-language modeling and " + "prompt-completion data." + ) + if "image" in examples[0]: + for example in examples: + example["images"] = [example.pop("image")] + images = [example["images"] for example in examples] + # Transformers requires at least one image in the batch, otherwise it throws an error + if all(img_list == [] for img_list in images): + images = None + if is_conversational(examples[0]): # conversational case + for example in examples: + example["prompt"] = prepare_multimodal_messages(example["prompt"], images=example["images"]) + example["completion"] = prepare_multimodal_messages(example["completion"]) + examples = [apply_chat_template(example, self.processor) for example in examples] + + prompts = [example["prompt"] for example in examples] + completions = [example["completion"] for example in examples] + + processed_prompts = self.processor( + images=images, + text=prompts, + padding=True, + padding_side="left", + return_tensors=self.return_tensors, + add_special_tokens=False, # to avoid adding the BOS twice, see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens + ) + processed_completions = self.processor( + text=completions, + padding=True, + padding_side="right", + return_tensors=self.return_tensors, + add_special_tokens=False, # to avoid adding the BOS twice, see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens + ) + + # Concatenate prompts and completions + prompt_ids, prompt_mask = processed_prompts["input_ids"], processed_prompts["attention_mask"] + completion_ids, completion_mask = processed_completions["input_ids"], processed_completions["attention_mask"] + input_ids = torch.cat((prompt_ids, completion_ids), dim=1) + attention_mask = torch.cat((prompt_mask, completion_mask), dim=1) + completion_mask = torch.cat((torch.zeros_like(prompt_mask), completion_mask), dim=1) + + has_tti = "token_type_ids" in processed_prompts + has_mm_tti = "mm_token_type_ids" in processed_prompts + + if has_tti: # special case for Gemma + prompt_token_type_ids = processed_prompts["token_type_ids"] + completion_token_type_ids = processed_completions["token_type_ids"] + token_type_ids = torch.cat((prompt_token_type_ids, completion_token_type_ids), dim=1) + if has_mm_tti: # special case for Qwen2.5-VL + prompt_mm_token_type_ids = processed_prompts["mm_token_type_ids"] + completion_mm_token_type_ids = processed_completions.get( + "mm_token_type_ids", torch.zeros_like(completion_ids) + ) + mm_token_type_ids = torch.cat((prompt_mm_token_type_ids, completion_mm_token_type_ids), dim=1) + + # Flush left to reduce padding + if has_tti and has_mm_tti: + attention_mask, input_ids, completion_mask, token_type_ids, mm_token_type_ids = flush_left( + attention_mask, input_ids, completion_mask, token_type_ids, mm_token_type_ids + ) + elif has_tti: + attention_mask, input_ids, completion_mask, token_type_ids = flush_left( + attention_mask, input_ids, completion_mask, token_type_ids + ) + elif has_mm_tti: + attention_mask, input_ids, completion_mask, mm_token_type_ids = flush_left( + attention_mask, input_ids, completion_mask, mm_token_type_ids + ) + else: + attention_mask, input_ids, completion_mask = flush_left(attention_mask, input_ids, completion_mask) + + # Truncate if necessary + if self.max_length is not None: + input_ids = input_ids[:, : self.max_length] + attention_mask = attention_mask[:, : self.max_length] + completion_mask = completion_mask[:, : self.max_length] + if has_tti: + token_type_ids = token_type_ids[:, : self.max_length] + if has_mm_tti: + mm_token_type_ids = mm_token_type_ids[:, : self.max_length] + + # Build the output dictionary + output = processed_prompts # we take processed_prompts because it contains the images + output.pop("input_ids", None) + output.pop("attention_mask", None) + output["completion_input_ids"] = input_ids + output["completion_attention_mask"] = attention_mask + output["completion_mask"] = completion_mask + if has_tti: + output["token_type_ids"] = token_type_ids + if has_mm_tti: + output["mm_token_type_ids"] = mm_token_type_ids + + if self.calculate_kl: + # Cycle completions by +1 within the batch to create mismatched KL pairs — same strategy as + # _get_kl_completion_ids in the text-only path, but done here to keep the VLM dataset fully raw. + kl_completions = completions[-1:] + completions[:-1] + processed_kl = self.processor( + text=kl_completions, + padding=True, + padding_side="right", + return_tensors=self.return_tensors, + add_special_tokens=False, # to avoid adding the BOS twice, see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens + ) + kl_ids = processed_kl["input_ids"] + kl_mask = processed_kl["attention_mask"] + + kl_input_ids = torch.cat((prompt_ids, kl_ids), dim=1) + kl_attention_mask = torch.cat((prompt_mask, kl_mask), dim=1) + kl_completion_mask = torch.cat((torch.zeros_like(prompt_mask), kl_mask), dim=1) + + # Build KL token-type tensors using the original (pre-flush) prompt tensors + if has_tti: + kl_completion_token_type_ids = processed_kl.get("token_type_ids", torch.zeros_like(kl_ids)) + kl_token_type_ids = torch.cat((prompt_token_type_ids, kl_completion_token_type_ids), dim=1) + if has_mm_tti: + kl_completion_mm_token_type_ids = processed_kl.get("mm_token_type_ids", torch.zeros_like(kl_ids)) + kl_mm_token_type_ids = torch.cat((prompt_mm_token_type_ids, kl_completion_mm_token_type_ids), dim=1) + + if has_tti and has_mm_tti: + kl_attention_mask, kl_input_ids, kl_completion_mask, kl_token_type_ids, kl_mm_token_type_ids = ( + flush_left( + kl_attention_mask, kl_input_ids, kl_completion_mask, kl_token_type_ids, kl_mm_token_type_ids + ) + ) + elif has_tti: + kl_attention_mask, kl_input_ids, kl_completion_mask, kl_token_type_ids = flush_left( + kl_attention_mask, kl_input_ids, kl_completion_mask, kl_token_type_ids + ) + elif has_mm_tti: + kl_attention_mask, kl_input_ids, kl_completion_mask, kl_mm_token_type_ids = flush_left( + kl_attention_mask, kl_input_ids, kl_completion_mask, kl_mm_token_type_ids + ) + else: + kl_attention_mask, kl_input_ids, kl_completion_mask = flush_left( + kl_attention_mask, kl_input_ids, kl_completion_mask + ) + + # Truncate if necessary + if self.max_length is not None: + kl_input_ids = kl_input_ids[:, : self.max_length] + kl_attention_mask = kl_attention_mask[:, : self.max_length] + kl_completion_mask = kl_completion_mask[:, : self.max_length] + if has_tti: + kl_token_type_ids = kl_token_type_ids[:, : self.max_length] + if has_mm_tti: + kl_mm_token_type_ids = kl_mm_token_type_ids[:, : self.max_length] + + output["KL_completion_input_ids"] = kl_input_ids + output["KL_completion_attention_mask"] = kl_attention_mask + output["KL_completion_mask"] = kl_completion_mask + if has_tti: + output["KL_completion_token_type_ids"] = kl_token_type_ids + if has_mm_tti: + output["KL_completion_mm_token_type_ids"] = kl_mm_token_type_ids + + output["label"] = [ex["label"] for ex in examples] + return output + + +class KTOTrainer(_BaseTrainer): + """ + Initialize KTOTrainer. + + Args: + model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]): + Model to be trained. Can be either: + + - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using `.from_pretrained` (where `` is derived from the model + config) with the keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported. + - A [`~peft.PeftModel`] object. Only causal language models are supported. + ref_model ([`~transformers.PreTrainedModel`], *optional*): + Reference model used to compute the reference log probabilities. + + - If provided, this model is used directly as the reference policy. + - If `None`, the trainer will automatically use the initial policy corresponding to `model`, i.e. the model + state before KTO training starts. + args ([`experimental.kto.KTOConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + The dataset to use for training. + eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`): + The dataset to use for evaluation. + processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. The padding side must be set to "left". If `None`, the + processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A + padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token, + `tokenizer.eos_token` will be used as the default. + data_collator ([`~transformers.DataCollator`], *optional*): + The data collator to use for training. If None is specified, the default data collator + ([`~experimental.kto.kto_trainer.DataCollatorForUnpairedPreference`]) will be used which will pad the + sequences to the maximum length of the sequences in the batch. + callbacks (`list[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration used to wrap the model. If `None`, the model is not wrapped. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to + metric values. + """ + + _tag_names = ["trl", "kto"] + _name = "KTO" + _paper = { + "title": "KTO: Model Alignment as Prospect Theoretic Optimization", + "id": "2402.01306", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{ethayarajh2024kto, + title = {{KTO: Model Alignment as Prospect Theoretic Optimization}}, + author = {Kawin Ethayarajh and Winnie Xu and Niklas Muennighoff and Dan Jurafsky and Douwe Kiela}, + year = 2024, + eprint = {arXiv:2402.01306}, + }"""), + } + + def __init__( + self, + model: "str | PreTrainedModel | PeftModel", + ref_model: PreTrainedModel | None = None, + args: KTOConfig | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + data_collator: DataCollator | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + peft_config: "PeftConfig | None" = None, + compute_metrics: Callable[[EvalLoopOutput], dict] | None = None, + ): + # Args + if args is None: + model_name = model if isinstance(model, str) else get_config_model_id(model.config) + model_name = model_name.split("/")[-1] + args = KTOConfig(f"{model_name}-KTO") + + if train_dataset is None: + raise ValueError("`train_dataset` is required") + elif isinstance(train_dataset, IterableDataset): + # IterableDataset requires dispatch_batches=False because Accelerate's dispatch mode may try to concatenate + # batches from multiple processes, leading to mismatch errors. + if args.accelerator_config.dispatch_batches is True: + logger.warning( + "You are using an `IterableDataset` for training with `dispatch_batches=True`. `dispatch_batches` " + "is forced to `False` when using an `IterableDataset`. To remove this warning, unset " + "`dispatch_batches` in `KTOConfig` or set it to `False`." + ) + args.accelerator_config.dispatch_batches = False + + # Model + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + model = create_model_from_path(model, **model_init_kwargs) + else: + if args.model_init_kwargs is not None: + logger.warning( + "You passed `model_init_kwargs` to the KTOConfig, but your model is already instantiated. " + "The `model_init_kwargs` will be ignored." + ) + # Non-quantized models do not have the `is_loaded_in_{8,4}bit` attributes, whereas quantized models do + _is_quantized_model = getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False) + if ref_model is model: + raise ValueError( + "`model` and `ref_model` cannot be the same object. In most cases you should omit `ref_model` and " + "we'll initialize it to a copy of `model` for you." + ) + + # Processing class + if processing_class is None: + processing_class = AutoProcessor.from_pretrained( + get_config_model_id(model.config), trust_remote_code=args.trust_remote_code + ) + if isinstance(processing_class, ProcessorMixin): + self._tokenizer = processing_class.tokenizer + self._is_vlm = True + elif isinstance(processing_class, PreTrainedTokenizerBase): + self._tokenizer = processing_class + self._is_vlm = False + else: + raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`") + if self._tokenizer.pad_token is None: + self._tokenizer.pad_token = self._tokenizer.eos_token + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge " + "and unload the existing adapter, save the resulting base model, and then pass that base model along " + "with the new `peft_config` to the trainer." + ) + # Create PEFT model + # ZeRO-3 + PEFT for non-quantized models: + # - PEFT's default autocast_adapter_dtype=True upcasts LoRA adapter params to fp32 even when the base model is bf16. + # - ZeRO-3's _allgather_params_coalesced allocates output buffers using the dtype of the first persistent parameter, + # so mixed-dtype persistent_parameters (bf16 base + fp32 LoRA) cause a TypeError on the first optimizer step. + # - Passing autocast_adapter_dtype=False keeps adapter params in the base model dtype (bf16), fixing the mismatch. + # - This is safe: the fp32 upcast is a QLoRA-specific concern (low-bit quantized base models), not needed for + # non-quantized bf16 training. + # - See: + # - TRL issue: https://github.com/huggingface/trl/issues/6089 + # - Upstream issue: https://github.com/deepspeedai/DeepSpeed/issues/8072 + # - autocast_adapter_dtype was introduced in PEFT 0.12.0; before, no upcast existed: no need to pass the kwarg + get_peft_model_kwargs = {} + if ( + args.deepspeed_plugin is not None + and args.deepspeed_plugin.zero_stage == 3 + and not _is_quantized_model + and Version(peft.__version__) >= Version("0.12.0") + ): + get_peft_model_kwargs["autocast_adapter_dtype"] = False + model = get_peft_model(model, peft_config, **get_peft_model_kwargs) + + elif is_peft_model(model) and ref_model is None: + # If the model is a PEFT model with a pretrained adapter, we need to create a "ref" adapter that is a copy + # of the "default" adapter, so that we can use it as the reference model during KTO training. PEFT only + # supports one adapter per model when the LoRA config uses `target_parameters` (see peft#3340), so in that + # case we skip the "ref" adapter and compute the reference log probs with adapters disabled, i.e. with the + # base model. + default_config = model.peft_config["default"] + if isinstance(default_config, LoraConfig) and default_config.target_parameters: + logger.warning( + "PEFT can't add a frozen reference adapter alongside one that uses `target_parameters` " + "(peft#3340), so the reference log probs are computed from the base model (adapters disabled). " + "If you wrapped the model only to apply LoRA, pass a `peft_config` to the trainer instead; if you " + "wrapped it deliberately (pretrained adapter or custom init), note that the base model matches " + "your adapter only when it's freshly zero-initialized. If it is, this warning is safe to ignore." + ) + else: + model.add_adapter("ref", default_config) + for name, param in model.named_parameters(): + if ".default." in name: + ref_name = name.replace(".default.", ".ref.") + ref_param = model.get_parameter(ref_name) + ref_param.data.copy_(param.data) + + # When using gradient checkpointing with PEFT, we need to enable input gradients. transformers.Trainer normally + # handles this, but a bug currently prevents it; see https://github.com/huggingface/transformers/issues/42489 + if is_peft_model(model) and args.gradient_checkpointing: + model.enable_input_require_grads() + + # When using QLoRA, the PEFT adapter weights are converted to bf16 to follow the recommendations from the + # original paper (see https://huggingface.co/papers/2305.14314, paragraph 3). Normally, this can be done by + # passing `autocast_adapter_dtype=False` to `get_peft_model`, but this option is not yet supported for + # quantized models. See: https://github.com/huggingface/peft/issues/2889 + if _is_quantized_model: + for param in model.parameters(): + if param.requires_grad: + param.data = param.data.to(torch.bfloat16) + + # Vision dataset detection + dataset_sample = next(iter(train_dataset)) + self._is_vision_dataset = "image" in dataset_sample or "images" in dataset_sample + if self._is_vision_dataset and not self._is_vlm: + raise ValueError( + "The dataset appears to be vision-related (contains 'image' or 'images' keys), but the provided " + "model does not seem to be a vision-language model. Please check your model and dataset." + ) + if self._is_vision_dataset and args.precompute_ref_log_probs: + raise ValueError( + "`precompute_ref_log_probs=True` is not supported for vision datasets. For vision-language " + "models, all data processing is performed on the fly rather than upfront. " + "Set `precompute_ref_log_probs=False`." + ) + if self._is_vision_dataset and ("chosen" in dataset_sample or "rejected" in dataset_sample): + raise ValueError( + "Vision datasets must be in unpaired format with `completion` and `label` columns. " + "Paired format (`chosen`/`rejected`) is not supported for vision datasets because " + "iterating over the full dataset to unpair it would be too expensive for large image " + "collections. Unpair your dataset first: `dataset = unpair_preference_dataset(dataset)`." + ) + + # Data collator + calculate_kl = args.loss_type not in ["apo_zero_unpaired"] + if data_collator is None and not self._is_vision_dataset: + data_collator = DataCollatorForUnpairedPreference( + pad_token_id=self._tokenizer.pad_token_id, + max_length=args.max_length, + pad_to_multiple_of=args.pad_to_multiple_of, + ) + elif data_collator is None and self._is_vision_dataset: + data_collator = DataCollatorForVisionUnpairedPreference( + processor=processing_class, + max_length=args.max_length, + calculate_kl=calculate_kl, + pad_to_multiple_of=args.pad_to_multiple_of, + ) + + # Training arguments + self.beta = args.beta + self.precompute_ref_logps = args.precompute_ref_log_probs + self.loss_type = args.loss_type + self.desirable_weight = args.desirable_weight + self.undesirable_weight = args.undesirable_weight + self.aux_loss_enabled = getattr(model.config, "output_router_logits", False) + self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0) + self.calculate_KL = calculate_kl + if self.calculate_KL and args.train_sampling_strategy != "sequential": + raise ValueError( + f"Loss type `'{args.loss_type}'` estimates the KL divergence term and requires " + f"`train_sampling_strategy='sequential'` because the KL completion for each example is precomputed " + f"against its neighbors in a fixed-order batch; any other strategy breaks that pairing. " + f"Got `train_sampling_strategy='{args.train_sampling_strategy}'`." + ) + if self.calculate_KL and args.per_device_train_batch_size <= 1: + raise ValueError( + "Actual (not effective) batch size must be > 1. KTO will not work properly because the KL term will be equivalent to the implied reward." + ) + if self.aux_loss_enabled and self.aux_loss_coef == 0.0: + logger.warning( + "You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to " + "`0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value " + "greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary " + "loss.", + ) + + # Dataset + # Skip dataset preparation for VLMs: tokenization and image processing happen on-the-fly in the collator. + if not self._is_vision_dataset: + train_dataset = self._prepare_dataset(train_dataset, processing_class, args, "train") + if eval_dataset is not None: + if isinstance(eval_dataset, dict): + eval_dataset = { + key: self._prepare_dataset(dataset, processing_class, args, key) + for key, dataset in eval_dataset.items() + } + else: + eval_dataset = self._prepare_dataset(eval_dataset, processing_class, args, "eval") + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + ) + + # Initialize activation offloading context + if self.args.activation_offloading: + self.maybe_activation_offload_context = get_act_offloading_ctx_manager(model=self.model) + else: + self.maybe_activation_offload_context = contextlib.nullcontext() + + # Reference model + if ref_model is None: + if is_peft_model(self.model) or args.precompute_ref_log_probs: + # If PEFT is used, the reference model is not needed since the adapter can be disabled to revert to the + # initial model. If precompute_ref_log_probs is True, the reference model does not need to be kept in + # memory during training. + self.ref_model = None + else: + ref_model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if self.args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + ref_model_init_kwargs["device_map"] = None + ref_model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + ref_model_path = get_config_model_id(self.model.config) + self.ref_model = create_model_from_path(ref_model_path, **ref_model_init_kwargs) + else: + self.ref_model = ref_model + + # Disable dropout in the model and reference model + if args.disable_dropout: + disable_dropout_in_model(model) + if self.ref_model is not None: + disable_dropout_in_model(self.ref_model) + + # Initialize the metrics + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + + # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the + # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set + # self.model_accepts_loss_kwargs to False to enable scaling. + self.model_accepts_loss_kwargs = False + + # Add tags to the model + self.model.add_model_tags(self._tag_names) + + if self.ref_model is not None: + if self.is_deepspeed_enabled: + self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator) + elif self.is_fsdp_enabled: + self.ref_model = prepare_fsdp(self.ref_model, self.accelerator) + else: + self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True) + + if args.sync_ref_model: + if is_peft_model(self.model): + raise NotImplementedError( + "You passed `sync_ref_model=True` while using a PEFT model, which is currently not supported. " + "With PEFT, KTOTrainer does not keep a separate reference model in memory; instead, it recovers " + "reference behavior by temporarily disabling the adapter. As a result, there is no standalone " + "`ref_model` instance to synchronize. Use `sync_ref_model=False`, or opt for full fine-tuning if " + "you need a synced reference model. If you need `sync_ref_model` to work with PEFT, please open a " + "feature request at https://github.com/huggingface/trl/issues." + ) + if args.precompute_ref_log_probs: + raise ValueError( + "You cannot use `sync_ref_model=True` together with `precompute_ref_log_probs=True`. " + "`precompute_ref_log_probs=True` assumes a fixed reference model, but with `sync_ref_model=True` " + "the reference model is periodically updated during training, making any precomputed reference " + "log-probs stale. Set `precompute_ref_log_probs=False` or disable `sync_ref_model`." + ) + self.add_callback(SyncRefModelCallback(ref_model=self.ref_model, accelerator=self.accelerator)) + + self.use_liger_kernel = args.use_liger_kernel + # Import Liger kernel if enabled + if self.use_liger_kernel: + if not is_liger_kernel_available(): + raise ImportError( + "You set `use_liger_kernel=True` but the liger kernel is not available. " + "Please install liger-kernel first: `pip install liger-kernel`" + ) + if self.loss_type in ["apo_zero_unpaired"]: + raise ValueError( + "You cannot set `loss_type='apo_zero_unpaired'` with liger-kernel." + "Only KTO loss is supported with liger-kernel." + ) + if self.precompute_ref_logps: + raise ValueError( + "You cannot use `precompute_ref_log_probs=True` with liger kernel. Please set " + "`precompute_ref_log_probs=False`." + ) + if is_peft_model(self.model): + raise ValueError( + "You cannot use `use_liger_kernel=True` with Peft models. Please set `use_liger_kernel=False`." + ) + self.liger_loss_fn = LigerFusedLinearKTOLoss(beta=self.beta, use_ref_model=(self.ref_model is not None)) + + if self.precompute_ref_logps: + if isinstance(self.train_dataset, IterableDataset) or isinstance( + self.eval_dataset, (IterableDataset, IterableDatasetDict) + ): + raise ValueError( + "`precompute_ref_log_probs=True` is not supported with IterableDataset. Please use a map-style " + "Dataset or set `precompute_ref_log_probs=False`." + ) + self.train_dataset = self._precompute_ref_logps( + self.train_dataset, + "train", + self.args.precompute_ref_batch_size or self.args.per_device_train_batch_size, + ) + if self.eval_dataset is not None: + if isinstance(self.eval_dataset, dict): + self.eval_dataset = { + name: self._precompute_ref_logps( + dataset, name, self.args.precompute_ref_batch_size or self.args.per_device_eval_batch_size + ) + for name, dataset in self.eval_dataset.items() + } + else: + self.eval_dataset = self._precompute_ref_logps( + self.eval_dataset, + "eval", + self.args.precompute_ref_batch_size or self.args.per_device_eval_batch_size, + ) + + def _tokenize( + self, + processing_class: PreTrainedTokenizerBase | ProcessorMixin, + input: str | list, + **kwargs, + ) -> dict[str, list]: + """Tokenize a single example for dataset preprocessing. + + Dispatches to `apply_chat_template` for conversational input (list of message dicts) and to `__call__` for + non-conversational input (str). + + Args: + processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`]): + The tokenizer or processor to use. + input (`str` or `list`): + A string for non-conversational input, or a list of message dicts for conversational input. + **kwargs: + Forwarded to `apply_chat_template` (e.g. `add_generation_prompt`, `return_assistant_tokens_mask`). + + Returns: + `dict` with at least an `"input_ids"` key mapping to a flat `list[int]`. + """ + if isinstance(input, list): # conversational: list of message dicts + if self._is_vlm: + input = prepare_multimodal_messages(input) + result = processing_class.apply_chat_template(input, tokenize=True, return_dict=True, **kwargs) + else: # non-conversational: plain text string + result = processing_class(text=input) + # VLMs emit a batch dimension even for single examples; unwrap it + if self._is_vlm: + return {k: v[0] for k, v in result.items()} + return result + + def _get_kl_dataset( + self, + dataset: Dataset | IterableDataset, + dataset_name: str, + args: KTOConfig, + ) -> Dataset | IterableDataset: + """ + Creates the KL dataset by creating mismatched (prompt, completion) pairs for KL divergence estimation. + + Args: + dataset (`Dataset` or `IterableDataset`): + Tokenized dataset with `prompt_ids` and `completion_ids` columns. + dataset_name (`str`): + Name used in progress bar descriptions. + args ([`KTOConfig`]): + Training arguments providing `per_device_train_batch_size` and `dataset_num_proc`. + + Returns: + `Dataset` or `IterableDataset` with a single `KL_completion_ids` column. + """ + map_kwargs = {} + if isinstance(dataset, Dataset): # IterableDataset does not support num_proc or desc + map_kwargs["num_proc"] = args.dataset_num_proc + map_kwargs["desc"] = f"Extracting KL {dataset_name} dataset" + kl_dataset = dataset.map( + _get_kl_completion_ids, batched=True, batch_size=args.per_device_train_batch_size, **map_kwargs + ) + + def rename_kl_fn(example): + return {"KL_completion_ids": example["completion_ids"]} + + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Assembling KL {dataset_name} dataset" + column_names = get_dataset_column_names(dataset) + kl_dataset = kl_dataset.map( + rename_kl_fn, + remove_columns=[c for c in get_dataset_column_names(kl_dataset) if c in column_names], + **map_kwargs, + ) + return kl_dataset + + def _prepare_dataset( + self, + dataset: Dataset | IterableDataset, + processing_class: PreTrainedTokenizerBase | ProcessorMixin, + args: KTOConfig | None, + dataset_name: str, + ) -> Dataset | IterableDataset: + # Build the kwargs for the `map` function + map_kwargs = {} + if isinstance(dataset, Dataset): # IterableDataset does not support num_proc + map_kwargs["num_proc"] = args.dataset_num_proc + + # Compute that only on the main process for faster data processing. + # see: https://github.com/huggingface/trl/pull/1255 + with PartialState().main_process_first(): + # Extract the prompt if needed + first_example = next(iter(dataset)) + if "prompt" not in first_example: + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Extracting prompt from {dataset_name} dataset" + dataset = dataset.map(extract_prompt, **map_kwargs) + + # Unpair the dataset if needed + first_example = next(iter(dataset)) + if "chosen" in first_example and "rejected" in first_example: + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Unpairing {dataset_name} dataset" + dataset = unpair_preference_dataset(dataset, **map_kwargs) + + # Add EOS token if needed: non-conversational only + first_example = next(iter(dataset)) + if not is_conversational(first_example): + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Adding EOS to {dataset_name} dataset" + + def add_eos(example, eos_token): + if not example["completion"].endswith(eos_token): + example["completion"] = example["completion"] + eos_token + return example + + dataset = dataset.map(add_eos, fn_kwargs={"eos_token": self._tokenizer.eos_token}, **map_kwargs) + + # Tokenize dataset + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Tokenizing {dataset_name} dataset" + + def tokenize_fn(example, processing_class): + if is_conversational(example): + chat_template_kwargs = example.get("chat_template_kwargs", {}) + prompt_ids = self._tokenize( + processing_class, + example["prompt"], + add_generation_prompt=True, + **chat_template_kwargs, + )["input_ids"] + prompt_completion_ids = self._tokenize( + processing_class, + example["prompt"] + example["completion"], + **chat_template_kwargs, + )["input_ids"] + else: + prompt_ids = self._tokenize(processing_class, example["prompt"])["input_ids"] + prompt_completion_ids = self._tokenize( + processing_class, example["prompt"] + example["completion"] + )["input_ids"] + + if not prompt_completion_ids[: len(prompt_ids)] == prompt_ids: + logger.warning( + "Mismatch between tokenized prompt and the start of tokenized prompt+completion. " + "This may be due to unexpected tokenizer behavior, whitespace issues, or special " + "token handling. Verify that the tokenizer is processing text consistently." + ) + + return { + "prompt_ids": prompt_ids, + "completion_ids": prompt_completion_ids[len(prompt_ids) :], + } + + dataset = dataset.map(tokenize_fn, fn_kwargs={"processing_class": processing_class}, **map_kwargs) + + # Get KL datasets if needed + if self.calculate_KL: + # create pairs for estimating the KL term by flipping the matched pairs in each batch of size total_batch_size + # i.e., (x_1, y_1), ..., (x_n, y_n) --> (x_1, y_n), ..., (x_n, y_1) = (x'_1, y'_1), ..., (x'_n, y'_n) + kl_dataset = self._get_kl_dataset(dataset, dataset_name, args) + dataset = concatenate_datasets([dataset, kl_dataset], axis=1) + + # Calculate dataset desirability balance + if dataset_name == "train" and isinstance(dataset, Dataset): # IterableDataset does not support len + num_desirable = max(sum(dataset["label"]), 1) + num_undesirable = max(len(dataset["label"]) - num_desirable, 1) # "label" is binary + + if num_desirable != num_undesirable: + # The lower and upper bounds come from Eq. (8) of https://huggingface.co/papers/2402.01306 + des_weight_lower_bound = round((num_undesirable * self.undesirable_weight / num_desirable) * 1, 2) + des_weight_upper_bound = round( + (num_undesirable * self.undesirable_weight / num_desirable) * 1.33, 2 + ) + und_weight_lower_bound = round((num_desirable * self.desirable_weight / num_undesirable) / 1.33, 2) + und_weight_upper_bound = round((num_desirable * self.desirable_weight / num_undesirable) / 1, 2) + + des_weight_in_range = des_weight_lower_bound <= self.desirable_weight <= des_weight_upper_bound + und_weight_in_range = und_weight_lower_bound <= self.undesirable_weight <= und_weight_upper_bound + + if not (des_weight_in_range or und_weight_in_range): + logger.warning( + "You have different amounts of desirable/positive and undesirable/negative examples but the " + "weights on the desirable and undesirable losses don't seem to be in an ideal range. Based " + f"on your data, we recommend EITHER " + f"desirable_weight in [{des_weight_lower_bound}, {des_weight_upper_bound}] or " + f"undesirable_weight in [{und_weight_lower_bound}, {und_weight_upper_bound}] (but NOT BOTH). " + "See the documentation on how to optimally set these weights.", + ) + return dataset + + def _set_signature_columns_if_needed(self): + # If `self.args.remove_unused_columns` is True, non-signature columns are removed. + # By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids" + # and "attention_mask"). + if self._signature_columns is None: + if self._is_vision_dataset: + self._signature_columns = [ + "prompt", + "completion", + "image", + "images", + "label", + "chat_template_kwargs", + ] + else: + self._signature_columns = [ + "prompt_ids", + "completion_ids", + "KL_completion_ids", + "label", + "ref_logps", + "ref_KL_logps", + ] + + def _get_train_sampler(self, train_dataset: Dataset | None = None) -> Sampler | None: + if self.calculate_KL and Version(transformers.__version__) < Version("5.2.0"): + if train_dataset is None: + train_dataset = self.train_dataset + if train_dataset is None or not has_length(train_dataset): + return None + return SequentialSampler(train_dataset) + return super()._get_train_sampler( + train_dataset + ) # Override training step to add activation offloading context. + + def _precompute_ref_logps(self, dataset: Dataset, name: str, batch_size: int) -> Dataset: + model_hash = hash_module(self.ref_model or self.model) + fingerprint = Hasher.hash((dataset._fingerprint, model_hash, self.calculate_KL)) + cache_file = dataset._get_cache_file_path(fingerprint) + if os.path.exists(cache_file): + return concatenate_datasets([dataset, Dataset.from_file(cache_file)], axis=1) + + dataloader = DataLoader( + dataset, + batch_size=batch_size, + collate_fn=self.data_collator, + num_workers=self.args.dataloader_num_workers, + pin_memory=self.args.dataloader_pin_memory, + shuffle=False, + ) + data_loader = self.accelerator.prepare(dataloader) + ref_logps = [] + ref_KL_logps = [] + for padded_batch in tqdm(iterable=data_loader, desc=f"Computing reference log probs for {name} dataset"): + ref_logp, ref_KL_logp = self.compute_ref_log_probs(padded_batch) + if self.calculate_KL: + ref_logp, ref_KL_logp = self.accelerator.gather_for_metrics((ref_logp, ref_KL_logp)) + ref_KL_logps.append(ref_KL_logp.cpu()) + else: + ref_logp = self.accelerator.gather_for_metrics(ref_logp) + ref_logps.append(ref_logp.cpu()) + + ref_logps = torch.cat(ref_logps) + if self.calculate_KL: + ref_KL_logps = torch.cat(ref_KL_logps) + + if self.accelerator.is_main_process: + + def add_ref_logps(batch, indices): + result = {"ref_logps": ref_logps[indices]} + if self.calculate_KL: + result.update({"ref_KL_logps": ref_KL_logps[indices]}) + return result + + dataset.map( + add_ref_logps, + with_indices=True, + batched=True, + remove_columns=dataset.column_names, + new_fingerprint=fingerprint, + desc=f"Caching reference log probs for {name} dataset", + ) + self.accelerator.wait_for_everyone() + + return concatenate_datasets([dataset, Dataset.from_file(cache_file)], axis=1) + + def compute_ref_log_probs(self, inputs): + """Computes reference log probabilities for a single padded batch.""" + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + if self.ref_model is None: + if is_peft_model(self.model): + model = self.accelerator.unwrap_model(self.model) + with use_adapter(model, adapter_name="ref" if "ref" in model.peft_config else None): + completion_logits = self.model( + inputs["completion_input_ids"], + attention_mask=inputs["completion_attention_mask"], + ).logits + + if self.calculate_KL: + KL_logits = self.model( + inputs["KL_completion_input_ids"], + attention_mask=inputs["KL_completion_attention_mask"], + ).logits + else: + completion_logits = self.model( + inputs["completion_input_ids"], + attention_mask=inputs["completion_attention_mask"], + ).logits + + if self.calculate_KL: + KL_logits = self.model( + inputs["KL_completion_input_ids"], + attention_mask=inputs["KL_completion_attention_mask"], + ).logits + else: + completion_logits = self.ref_model( + inputs["completion_input_ids"], attention_mask=inputs["completion_attention_mask"] + ).logits + + if self.calculate_KL: + KL_logits = self.ref_model( + inputs["KL_completion_input_ids"], + attention_mask=inputs["KL_completion_attention_mask"], + ).logits + + shift_logits = completion_logits[:, :-1, :] + per_token_logps = selective_log_softmax(shift_logits, inputs["completion_input_ids"][:, 1:]) + per_token_logps[inputs["completion_mask"][:, 1:] == 0] = 0.0 + completion_logps = per_token_logps.sum(-1) + + if self.calculate_KL: + shift_KL_logits = KL_logits[:, :-1, :] + KL_per_token_logps = selective_log_softmax(shift_KL_logits, inputs["KL_completion_input_ids"][:, 1:]) + KL_per_token_logps[inputs["KL_completion_mask"][:, 1:] == 0] = 0.0 + KL_logps = KL_per_token_logps.sum(-1) + else: + KL_logps = None + + return completion_logps, KL_logps + + def _compute_kl_logps(self, model, batch): + """Compute KL log probabilities for a given batch.""" + KL_logps = None + if self.calculate_KL: + _non_model_keys = { + "completion_input_ids", + "completion_attention_mask", + "completion_mask", + "KL_completion_mask", + "KL_completion_token_type_ids", + "KL_completion_mm_token_type_ids", + "label", + "ref_logps", + "ref_KL_logps", + } + KL_model_kwargs = {k: v for k, v in batch.items() if k not in _non_model_keys} + KL_model_kwargs["input_ids"] = KL_model_kwargs.pop("KL_completion_input_ids") + KL_model_kwargs["attention_mask"] = KL_model_kwargs.pop("KL_completion_attention_mask") + # KL sequences have different widths from the main completion after flush_left; override token-type + # tensors with the KL-specific ones the collator built for exactly this purpose. + if "KL_completion_token_type_ids" in batch: + KL_model_kwargs["token_type_ids"] = batch["KL_completion_token_type_ids"] + if "KL_completion_mm_token_type_ids" in batch: + KL_model_kwargs["mm_token_type_ids"] = batch["KL_completion_mm_token_type_ids"] + + with torch.no_grad(): + KL_logits = model(**KL_model_kwargs).logits + + shift_KL_logits = KL_logits[:, :-1, :] + KL_per_token_logps = selective_log_softmax(shift_KL_logits, batch["KL_completion_input_ids"][:, 1:]) + KL_per_token_logps[batch["KL_completion_mask"][:, 1:] == 0] = 0.0 + KL_logps = KL_per_token_logps.sum(-1) + return KL_logps + + def _compute_loss_liger(self, model, inputs, return_outputs): + if return_outputs: + raise RuntimeError( + "return_outputs=True is not supported with the Liger KTO loss. The Liger loss computes the loss " + "without materializing logits, so outputs cannot be returned." + ) + mode = "train" if self.model.training else "eval" + batch = {k: (v.to(self.accelerator.device) if isinstance(v, torch.Tensor) else v) for k, v in inputs.items()} + + labels = torch.tensor(batch["label"]) + num_chosen = labels.sum().to(self.accelerator.device) + num_rejected = (len(labels) - num_chosen).to(self.accelerator.device) + + policy_KL_logps = self._compute_kl_logps(model, batch) + ref_KL_logps = self._compute_kl_logps(self.ref_model, batch) + if self.calculate_KL: + kl = (policy_KL_logps - ref_KL_logps).mean().detach() + kl = self.accelerator.gather_for_metrics(kl).mean().clamp(min=0) + else: + kl = torch.zeros(1).to(self.accelerator.device) + + _non_model_keys = { + "completion_mask", + "KL_completion_input_ids", + "KL_completion_attention_mask", + "KL_completion_mask", + "KL_completion_token_type_ids", + "KL_completion_mm_token_type_ids", + "label", + "ref_logps", + "ref_KL_logps", + } + model_kwargs = {k: v for k, v in batch.items() if k not in _non_model_keys} + model_kwargs["input_ids"] = model_kwargs.pop("completion_input_ids") + model_kwargs["attention_mask"] = model_kwargs.pop("completion_attention_mask") + model_kwargs["use_cache"] = False + if self.aux_loss_enabled: + model_kwargs["output_router_logits"] = True + + # `base_model` gives the inner module (skipping `lm_head`) — text decoder for LMs, multimodal wrapper for + # VLMs (so vision-token injection runs before the text decoder). `get_decoder()` won't do: on VLMs it + # returns just the text stack and feeds image-placeholder IDs through it. + # Pre-5.0 transformers VLMs set `base_model_prefix = ""` so `base_model is self` (re-runs `lm_head`). + # Fall back to `.model` there. + if self._is_vlm and Version(transformers.__version__) < Version("5.0.0"): + backbone, ref_backbone = model.model, self.ref_model.model + else: + backbone, ref_backbone = model.base_model, self.ref_model.base_model + + outputs = backbone(**model_kwargs) + + # reference model + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + ref_outputs = ref_backbone(**{k: v for k, v in model_kwargs.items() if k != "output_router_logits"}) + lm_head = model.get_output_embeddings() + ref_lm_head = self.ref_model.get_output_embeddings() + + shift_completion_mask = batch["completion_mask"][:, 1:] + target = batch["completion_input_ids"][:, 1:].clone() + target[shift_completion_mask == 0] = -100 + + ( + loss, + ( + chosen_logps_sum, + rejected_logps_sum, + chosen_logits_sum, + rejected_logits_sum, + chosen_rewards_sum, + rejected_rewards_sum, + ), + ) = self.liger_loss_fn( + _input=outputs.last_hidden_state[:, :-1], + lin_weight=lm_head.weight, + target=target, + bias=lm_head.bias if hasattr(lm_head, "bias") else None, + preference_labels=torch.tensor(batch["label"], dtype=torch.bool).to(self.accelerator.device), + ref_input=ref_outputs.last_hidden_state[:, :-1], + ref_weight=ref_lm_head.weight, + ref_bias=ref_lm_head.bias if hasattr(lm_head, "bias") else None, + kl=kl, + ) + if self.aux_loss_enabled: + loss += self.aux_loss_coef * outputs.aux_loss + + self._metrics[mode]["kl"].append(kl.item()) + + all_num_chosen = self.accelerator.gather_for_metrics(num_chosen).sum().item() + all_num_rejected = self.accelerator.gather_for_metrics(num_rejected).sum().item() + + if all_num_chosen > 0: + self._metrics[mode]["rewards/chosen"].append( + self.accelerator.gather_for_metrics(chosen_rewards_sum.nansum()).nansum().item() / all_num_chosen + ) + self._metrics[mode]["logps/chosen"].append( + self.accelerator.gather_for_metrics(chosen_logps_sum.nansum()).nansum().item() / all_num_chosen + ) + self._metrics[mode]["logits/chosen"].append( + self.accelerator.gather_for_metrics(chosen_logits_sum.nansum()).nansum().item() / all_num_chosen + ) + + if all_num_rejected > 0: + self._metrics[mode]["rewards/rejected"].append( + self.accelerator.gather_for_metrics(rejected_rewards_sum.nansum()).nansum().item() / all_num_rejected + ) + self._metrics[mode]["logps/rejected"].append( + self.accelerator.gather_for_metrics(rejected_logps_sum.nansum()).nansum().item() / all_num_rejected + ) + self._metrics[mode]["logits/rejected"].append( + self.accelerator.gather_for_metrics(rejected_logits_sum.nansum()).nansum().item() / all_num_rejected + ) + + if all_num_chosen > 0 and all_num_rejected > 0: + self._metrics[mode]["rewards/margins"].append( + self._metrics[mode]["rewards/chosen"][-1] - self._metrics[mode]["rewards/rejected"][-1] + ) + + return loss + + def _compute_loss(self, model, inputs, return_outputs): + """Compute the KTO loss and other metrics for the given batch of inputs for train or test.""" + mode = "train" if self.model.training else "eval" + batch = {k: (v.to(self.accelerator.device) if isinstance(v, torch.Tensor) else v) for k, v in inputs.items()} + + labels = torch.tensor(batch["label"]) + num_chosen = labels.sum().to(self.accelerator.device) + num_rejected = (len(labels) - num_chosen).to(self.accelerator.device) + + policy_KL_logps = self._compute_kl_logps(model, batch) + + _non_model_keys = { + "completion_mask", + "KL_completion_input_ids", + "KL_completion_attention_mask", + "KL_completion_mask", + "KL_completion_token_type_ids", + "KL_completion_mm_token_type_ids", + "label", + "ref_logps", + "ref_KL_logps", + } + model_kwargs = {k: v for k, v in batch.items() if k not in _non_model_keys} + model_kwargs["input_ids"] = model_kwargs.pop("completion_input_ids") + model_kwargs["attention_mask"] = model_kwargs.pop("completion_attention_mask") + if self.aux_loss_enabled: + model_kwargs["output_router_logits"] = True + + outputs = model(**model_kwargs) + if self.aux_loss_enabled: + aux_loss = outputs.aux_loss + + shift_logits = outputs.logits[:, :-1, :] + per_token_logps = selective_log_softmax(shift_logits, batch["completion_input_ids"][:, 1:]) + per_token_logps[batch["completion_mask"][:, 1:] == 0] = 0.0 + completion_logps = per_token_logps.sum(-1) + + if completion_logps.shape[0] != len(batch["label"]): + raise ValueError( + "There is a mismatch between the number of examples in this batch and the number of " + "examples for which an output sequence was predicted." + ) + + device = outputs.logits.device + bool_labels = torch.as_tensor(batch["label"], dtype=torch.bool, device=device) + chosen_idx = torch.nonzero(bool_labels, as_tuple=False).view(-1) + rejected_idx = torch.nonzero(~bool_labels, as_tuple=False).view(-1) + + policy_chosen_logps = completion_logps.index_select(0, chosen_idx) + policy_rejected_logps = completion_logps.index_select(0, rejected_idx) + policy_chosen_logits = outputs.logits.index_select(0, chosen_idx) + policy_rejected_logits = outputs.logits.index_select(0, rejected_idx) + + if self.precompute_ref_logps: + ref_chosen_logps = batch["ref_logps"].index_select(0, chosen_idx) + ref_rejected_logps = batch["ref_logps"].index_select(0, rejected_idx) + if self.calculate_KL: + ref_KL_logps = batch["ref_KL_logps"] + else: + ref_KL_logps = None + else: + ref_model_kwargs = {k: v for k, v in model_kwargs.items() if k != "output_router_logits"} + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + if is_peft_model(self.model) and self.ref_model is None: + ref_model_unwrapped = self.accelerator.unwrap_model(self.model) + with use_adapter( + ref_model_unwrapped, adapter_name="ref" if "ref" in ref_model_unwrapped.peft_config else None + ): + ref_KL_logps = self._compute_kl_logps(self.model, batch) + ref_outputs = self.model(**ref_model_kwargs) + else: + ref_KL_logps = self._compute_kl_logps(self.ref_model, batch) + ref_outputs = self.ref_model(**ref_model_kwargs) + ref_shift_logits = ref_outputs.logits[:, :-1, :] + ref_per_token_logps = selective_log_softmax(ref_shift_logits, batch["completion_input_ids"][:, 1:]) + ref_per_token_logps[batch["completion_mask"][:, 1:] == 0] = 0.0 + ref_completion_logps = ref_per_token_logps.sum(-1) + ref_chosen_logps = ref_completion_logps.index_select(0, chosen_idx) + ref_rejected_logps = ref_completion_logps.index_select(0, rejected_idx) + + if self.calculate_KL: + kl = (policy_KL_logps - ref_KL_logps).mean().detach() + kl = self.accelerator.gather_for_metrics(kl).mean().clamp(min=0) + else: + kl = torch.zeros(1).to(policy_chosen_logps.device) + # Chosen losses + if policy_chosen_logps.shape[0] != 0 or ref_chosen_logps.shape[0] != 0: + chosen_logratios = policy_chosen_logps - ref_chosen_logps + + if self.loss_type == "kto": + # Eqn (7) of the KTO paper (https://huggingface.co/papers/2402.01306) + chosen_losses = 1 - F.sigmoid(self.beta * (chosen_logratios - kl)) + elif self.loss_type == "apo_zero_unpaired": + # Unpaired variant of Eqn (7) of the APO paper (https://huggingface.co/papers/2408.06266) + # Use this loss when you believe the chosen outputs are better than your model's default output + chosen_losses = 1 - F.sigmoid(self.beta * chosen_logratios) + + chosen_rewards = self.beta * chosen_logratios.detach() + + else: + # lists can't be empty -- if they are, then accelerate.gather will hang + chosen_losses = torch.Tensor([]).to(self.accelerator.device) + chosen_rewards = torch.Tensor([]).to(self.accelerator.device) + # Rejected losses + if policy_rejected_logps.shape[0] != 0 or ref_rejected_logps.shape[0] != 0: + rejected_logratios = policy_rejected_logps - ref_rejected_logps + + if self.loss_type == "kto": + rejected_losses = 1 - F.sigmoid(self.beta * (kl - rejected_logratios)) + elif self.loss_type == "apo_zero_unpaired": + rejected_losses = F.sigmoid(self.beta * rejected_logratios) + + rejected_rewards = self.beta * rejected_logratios.detach() + else: + # lists can't be empty -- if they are, then accelerate.gather will hang + rejected_losses = torch.Tensor([]).to(self.accelerator.device) + rejected_rewards = torch.Tensor([]).to(self.accelerator.device) + losses = torch.cat( + (self.desirable_weight * chosen_losses, self.undesirable_weight * rejected_losses), + 0, + ) + + self._metrics[mode]["kl"].append(kl.item()) + + all_num_chosen = self.accelerator.gather_for_metrics(num_chosen).sum().item() + all_num_rejected = self.accelerator.gather_for_metrics(num_rejected).sum().item() + + if all_num_chosen > 0: + self._metrics[mode]["rewards/chosen"].append( + self.accelerator.gather_for_metrics(chosen_rewards.nansum()).nansum().item() / all_num_chosen + ) + self._metrics[mode]["logps/chosen"].append( + self.accelerator.gather_for_metrics(policy_chosen_logps.nansum()).nansum().item() / all_num_chosen + ) + self._metrics[mode]["logits/chosen"].append( + self.accelerator.gather_for_metrics(policy_chosen_logits.nansum()).nansum().item() / all_num_chosen + ) + + if all_num_rejected > 0: + self._metrics[mode]["rewards/rejected"].append( + self.accelerator.gather_for_metrics(rejected_rewards.nansum()).nansum().item() / all_num_rejected + ) + self._metrics[mode]["logps/rejected"].append( + self.accelerator.gather_for_metrics(policy_rejected_logps.nansum()).nansum().item() / all_num_rejected + ) + self._metrics[mode]["logits/rejected"].append( + self.accelerator.gather_for_metrics(policy_rejected_logits.nansum()).nansum().item() / all_num_rejected + ) + + if all_num_chosen > 0 and all_num_rejected > 0: + self._metrics[mode]["rewards/margins"].append( + self._metrics[mode]["rewards/chosen"][-1] - self._metrics[mode]["rewards/rejected"][-1] + ) + + loss = losses.nanmean() + if self.aux_loss_enabled: + loss += self.aux_loss_coef * aux_loss + + return (loss, outputs) if return_outputs else loss + + def evaluate( + self, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + ignore_keys: list[str] | None = None, + metric_key_prefix: str = "eval", + ) -> dict[str, float]: + # When a dataset is passed directly to `evaluate` (e.g. a held-out test set), preprocess it the same way + # `__init__` does, so that `evaluate` accepts the same dataset types as the trainer. `_prepare_dataset` is + # idempotent: it skips datasets that are already tokenized. A `str` selects a dataset that was already prepared + # at init time, so it's left untouched. + if not self._is_vision_dataset and eval_dataset is not None and not isinstance(eval_dataset, str): + if isinstance(eval_dataset, dict): + eval_dataset = { + key: self._prepare_dataset(dataset, self.processing_class, self.args, key) + for key, dataset in eval_dataset.items() + } + else: + eval_dataset = self._prepare_dataset(eval_dataset, self.processing_class, self.args, "eval") + # With `precompute_ref_log_probs`, `_compute_loss` reads the reference log-probs from the batch, so they + # must be precomputed here as well, mirroring `__init__`. + if self.precompute_ref_logps: + batch_size = self.args.precompute_ref_batch_size or self.args.per_device_eval_batch_size + if isinstance(eval_dataset, dict): + eval_dataset = { + name: self._precompute_ref_logps(dataset, name, batch_size) + for name, dataset in eval_dataset.items() + } + else: + eval_dataset = self._precompute_ref_logps(eval_dataset, "eval", batch_size) + return super().evaluate( + eval_dataset=eval_dataset, ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix + ) + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + try: + if self.use_liger_kernel: + return self._compute_loss_liger(model, inputs, return_outputs) + return self._compute_loss(model, inputs, return_outputs) + except ValueError as e: + if "Image features and image tokens do not match" in str(e) and self.args.max_length is not None: + raise ValueError( + f"The current `max_length` ({self.args.max_length}) is too short and causes image placeholder " + f"tokens in `input_ids` to be truncated, while the corresponding image features remain intact. " + f"Please increase `max_length` or set it to `None` to disable truncation." + ) from e + raise + + # Override training step to add activation offloading context. + def training_step(self, *args, **kwargs): + with self.maybe_activation_offload_context: + return super().training_step(*args, **kwargs) + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} # average the metrics + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + # During eval, Trainer calls prediction_step. If no labels are present in the inputs, it only runs forward and + # returns logits. We override prediction_step to force compute_loss, because this trainer doesn't involve labels. + def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys: list[str] | None = None): + inputs = self._prepare_inputs(inputs) + with torch.no_grad(), self.compute_loss_context_manager(): + if prediction_loss_only: + loss = self.compute_loss(model, inputs, return_outputs=False) # logits aren't materialized with liger + logits, labels = None, None + else: + loss, outputs = self.compute_loss(model, inputs, return_outputs=True) + logits, labels = outputs.logits, inputs["completion_input_ids"] + return loss, logits, labels + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/merge_model_callback.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/merge_model_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..d49caeda6aeeb95e408c97ebb6fdaf29e553e0b7 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/merge_model_callback.py @@ -0,0 +1,352 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import os + +import torch +from huggingface_hub import HfApi +from transformers import TrainerCallback + +from ..import_utils import is_mergekit_available +from ..trainer.utils import get_config_model_id + + +if is_mergekit_available(): + from mergekit.config import MergeConfiguration + from mergekit.merge import MergeOptions, run_merge + + +# Logger for module-level logging +logger = logging.getLogger(__name__) + + +def upload_model_to_hf(folder_path: str, repo_id: str): + api = HfApi() + # Create the repository if it doesn't exist + repo = api.create_repo(repo_id, repo_type="model") + + # Upload the folder to the specified repository + api.upload_folder( + folder_path=folder_path, + repo_id=repo.repo_id, + repo_type=repo.repo_type, + ) + + +class MergeConfig: + r""" + Configuration class for merging two models using `mergekit`. + + This class provides a structured way to configure and generate merge configurations for various merge methods, such + as `linear`, `ties`, `dare_ties`, and `slerp`. + + Args: + method (`str`, *optional*, defaults to `"linear"`): + Merge method to use. Supported methods include: + + - `"linear"`: Linearly combines two models with specified weights. + - `"ties"`: Combines two models using the TIES method with density parameters. + - `"dare_ties"`: A variant of TIES for domain adaptation. + - `"slerp"`: Combines models using spherical linear interpolation. + + Note: + + For more details about the merge methods and how they are implemented, see the [MergeKit GitHub + repository](https://github.com/arcee-ai/mergekit?tab=readme-ov-file#merge-methods). + + Attributes: + method (`str`): The merge method to use. + policy_model_path (`str` or `None`): Path to the policy model. + target_model_path (`str` or `None`): Path to the target model. + policy_model_weight (`float`): Weight for the policy model (for `linear` and `ties` methods). + target_model_weight (`float`): Weight for the target model (for `linear` and `ties` methods). + policy_model_density (`list[float]`): Density parameters for the policy model (for `ties` and `dare_ties`). + target_model_density (`list[float]`): Density parameters for the target model (for `ties` and `dare_ties`). + normalize (`float` or `None`): Normalization factor for the TIES method. + t_values (`float` or `None`): Interpolation factor for the SLERP method. + dtype (`str`): Data type to use for merging, e.g., `"float16"`. + """ + + def __init__(self, method: str = "linear"): + if not is_mergekit_available(): + raise ImportError("MergeConfig requires the `mergekit` extra. To install, run `pip install mergekit`.") + self.method = method + self.policy_model_path = None + self.target_model_path = None + + # Initialize relevant parameters based on the method + if method == "linear": + self.policy_model_weight = 0.5 + self.target_model_weight = 0.5 + self.dtype = "float16" + elif method == "ties": + self.policy_model_weight = 1.0 + self.policy_model_density = [1.0, 0.7, 0.1] + self.target_model_weight = 1.0 + self.target_model_density = [1.0] + self.normalize = 1.0 + self.dtype = "float16" + elif method == "dare_ties": + self.policy_model_weight = 1.0 + self.policy_model_density = [1.0, 0.7, 0.1] + self.target_model_weight = 1.0 + self.target_model_density = [1.0] + self.normalize = 1.0 + self.dtype = "float16" + elif method == "slerp": + self.t_values = 0.5 + self.dtype = "float16" + else: + raise ValueError(f"Unsupported merge method: {method}") + + def create_merge_config_linear(self) -> "MergeConfiguration": + """ + Creates a merge configuration for a linear merge of two models with specified weights. + """ + # Create the merge configuration dictionary + merge_config_dict = { + "dtype": self.dtype, + "merge_method": "linear", + "models": [ + {"model": self.policy_model_path, "parameters": {"weight": self.policy_model_weight}}, + {"model": self.target_model_path, "parameters": {"weight": self.target_model_weight}}, + ], + } + + # Create the MergeConfiguration from the dictionary + merge_config = MergeConfiguration.model_validate(merge_config_dict) + + return merge_config + + def create_merge_config_ties(self) -> "MergeConfiguration": + """ + Creates a merge configuration for a TIES merge of two models, with specified weights and densities. + """ + # Create the TIES merge configuration dictionary + merge_config_dict = { + "merge_method": "ties", + "slices": None, # Optional slices if needed + "models": [ + { + "model": { + "model": {"path": self.target_model_path, "revision": None}, + "lora": None, + "override_architecture": None, + }, + "parameters": {"density": self.target_model_density, "weight": self.target_model_weight}, + }, + { + "model": { + "model": {"path": self.policy_model_path, "revision": None}, + "lora": None, + "override_architecture": None, + }, + "parameters": {"density": self.policy_model_density, "weight": self.policy_model_weight}, + }, + ], + "parameters": {"normalize": self.normalize}, + "base_model": { + "model": {"path": self.policy_model_path, "revision": None}, + "lora": None, + "override_architecture": None, + }, + "dtype": self.dtype, + "tokenizer_source": None, + "tokenizer": None, + "chat_template": None, + "out_dtype": None, + } + + # Create the MergeConfiguration from the dictionary + merge_config = MergeConfiguration.model_validate(merge_config_dict) + + return merge_config + + def create_merge_config_dare_ties(self) -> "MergeConfiguration": + """ + Creates a merge configuration for a DARE TIES merge of two models, with specified weights and densities. + """ + # Create the DARE TIES merge configuration dictionary + merge_config_dict = { + "merge_method": "dare_ties", + "slices": None, # Optional slices if needed + "models": [ + { + "model": { + "model": {"path": self.target_model_path, "revision": None}, + "lora": None, + "override_architecture": None, + }, + "parameters": {"density": self.target_model_density, "weight": self.target_model_weight}, + }, + { + "model": { + "model": {"path": self.policy_model_path, "revision": None}, + "lora": None, + "override_architecture": None, + }, + "parameters": {"density": self.policy_model_density, "weight": self.policy_model_weight}, + }, + ], + "parameters": {"normalize": self.normalize}, + "base_model": { + "model": {"path": self.policy_model_path, "revision": None}, + "lora": None, + "override_architecture": None, + }, + "dtype": self.dtype, + "tokenizer_source": None, + "tokenizer": None, + "chat_template": None, + "out_dtype": None, + } + + # Create the MergeConfiguration from the dictionary + merge_config = MergeConfiguration.model_validate(merge_config_dict) + + return merge_config + + def create_merge_config_slerp(self) -> "MergeConfiguration": + """ + Creates a merge configuration for a SLERP merge of a model with a base model. + """ + + # Create the SLERP merge configuration dictionary + merge_config_dict = { + "merge_method": "slerp", + "slices": None, # Optional slices if needed + "models": [ + { + "model": { + "model": {"path": self.target_model_path, "revision": None}, + "lora": None, + "override_architecture": None, + }, + "parameters": None, # No specific parameters for SLERP model + } + ], + "parameters": { + "t": self.t_values # Set the t values for SLERP + }, + "base_model": { + "model": {"path": self.policy_model_path, "revision": None}, + "lora": None, + "override_architecture": None, + }, + "dtype": self.dtype, + "tokenizer_source": None, + "tokenizer": None, + "chat_template": None, + "out_dtype": None, + } + + # Create the MergeConfiguration from the dictionary + merge_config = MergeConfiguration.model_validate(merge_config_dict) + + return merge_config + + def create(self) -> "MergeConfiguration": + if self.method == "linear": + return self.create_merge_config_linear() + elif self.method == "ties": + return self.create_merge_config_ties() + elif self.method == "dare_ties": + return self.create_merge_config_dare_ties() + elif self.method == "slerp": + return self.create_merge_config_slerp() + + +def merge_models(config: "MergeConfiguration", out_path: str): + """ + Merge two models using mergekit + + Args: + config (`MergeConfiguration`): The merge configuration. + out_path (`str`): The output path for the merged model. + """ + if not is_mergekit_available(): + raise ImportError("merge_models requires the `mergekit` extra. To install, run `pip install mergekit`.") + run_merge( + config, + out_path=out_path, + options=MergeOptions( + device="auto", + cuda=torch.cuda.is_available(), + copy_tokenizer=True, + lazy_unpickle=False, + low_cpu_memory=False, + ), + ) + + +class MergeModelCallback(TrainerCallback): + r""" + A [`~transformers.TrainerCallback`] that merges the policy model (the model being trained) with another model based + on a merge configuration. + + Args: + merge_config ([`experimental.merge_model_callback.MergeConfig`], *optional*): + Configuration used for the merging process. If not provided, the default + [`~experimental.merge_model_callback.MergeConfig`] is used. + merge_at_every_checkpoint (`bool`, *optional*, defaults to `False`): + Whether to merge the model at every checkpoint. + push_to_hub (`bool`, *optional*, defaults to `False`): + Whether to push the merged model to the Hub after merging. + + Example: + + ```python + >>> from trl.experimental.merge_model_callback import MergeConfig, MergeModelCallback + + >>> config = MergeConfig() + >>> merge_callback = MergeModelCallback(config) + >>> trainer = DPOTrainer(..., callbacks=[merge_callback]) + ``` + """ + + def __init__( + self, + merge_config: "MergeConfig | None" = None, + merge_at_every_checkpoint: bool = False, + push_to_hub: bool = False, + ): + if not is_mergekit_available(): + raise ImportError( + "MergeModelCallback requires the `mergekit` extra. To install, run `pip install mergekit`." + ) + self.merge_config = merge_config or MergeConfig() + self.merge_at_every_checkpoint = merge_at_every_checkpoint + self.push_to_hub = push_to_hub + + def _merge_and_maybe_push(self, output_dir, global_step, model): + checkpoint_path = os.path.join(output_dir, f"checkpoint-{global_step}") + self.merge_config.policy_model_path = checkpoint_path + if self.merge_config.target_model_path is None: + self.merge_config.target_model_path = get_config_model_id(model.config) + merge_path = os.path.join(checkpoint_path, "merged") + + merge_models(self.merge_config.create(), merge_path) + + if self.push_to_hub: + repo_name = f"{output_dir}_checkpoint-{global_step}_merged" + upload_model_to_hf(merge_path, repo_name) + + def on_save(self, args, state, control, model=None, **kwargs): + if self.merge_at_every_checkpoint: + self._merge_and_maybe_push(args.output_dir, state.global_step, model) + + def on_train_end(self, args, state, control, model=None, **kwargs): + if not self.merge_at_every_checkpoint: + self._merge_and_maybe_push(args.output_dir, state.global_step, model) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/minillm/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/minillm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..07bc38f0ef9973010a3eed3c9adf4ef5137ec6b1 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/minillm/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .minillm_config import MiniLLMConfig +from .minillm_trainer import MiniLLMTrainer + + +__all__ = ["MiniLLMConfig", "MiniLLMTrainer"] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/minillm/minillm_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/minillm/minillm_config.py new file mode 100644 index 0000000000000000000000000000000000000000..678868aabb8aa78a50eb53282ca390364674b82d --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/minillm/minillm_config.py @@ -0,0 +1,137 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.base_config import _BaseConfig +from ...trainer.grpo_config import GRPOConfig + + +@dataclass +class MiniLLMConfig(GRPOConfig): + """ + Configuration class for [`MiniLLMTrainer`]. + + This class includes only the parameters that are specific to MiniLLM training. For a full list of training + arguments, please refer to the [`~transformers.TrainingArguments`] and [`GRPOConfig`] documentation. + + Args: + teacher_model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the teacher model + from a string. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. + rkl_advantage (`bool`, *optional*, defaults to `True`): + Whether to add the reverse KL advantage to the reward advantage. + single_step_decomposition (`bool`, *optional*, defaults to `True`): + Whether to use single-step decomposition for the KL divergence computation. + kd_temperature (`float`, *optional*, defaults to `1.0`): + Temperature for knowledge distillation. Higher temperatures produce softer probability distributions over + classes. + gamma (`float`, *optional*, defaults to `0.0`): + Discount factor for future rewards in reinforcement learning. + length_normalization (`bool`, *optional*, defaults to `True`): + Whether to apply length normalization to the rewards. + """ + + _VALID_DICT_FIELDS = GRPOConfig._VALID_DICT_FIELDS + ["teacher_model_init_kwargs"] + + teacher_model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the " + "teacher model from a string." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropouts in `model`."}, + ) + rkl_advantage: bool = field( + default=True, + metadata={"help": "Whether to add the reverse KL advantage to the reward advantage."}, + ) + single_step_decomposition: bool = field( + default=True, + metadata={"help": "Whether to use single-step decomposition for the KL divergence computation."}, + ) + kd_temperature: float = field( + default=1.0, + metadata={ + "help": "Temperature for knowledge distillation. Higher temperatures produce softer probability " + "distributions over classes." + }, + ) + gamma: float = field( + default=0.0, + metadata={"help": "Discount factor for future rewards in reinforcement learning."}, + ) + length_normalization: bool = field( + default=True, + metadata={"help": "Whether to apply length normalization to the rewards."}, + ) + + def __post_init__(self): + # We do not use the post_init of GRPOConfig because: + # 1. num_generations can be < 2 in MiniLLMConfig. Scale_rewards must be set to "none" to avoid nan. + _BaseConfig.__post_init__(self) + + self.scale_rewards = {True: "group", False: "none"}.get(self.scale_rewards, self.scale_rewards) + if self.num_generations == 1: + self.scale_rewards = "none" + + num_processes = self.world_size + # The current default effective batch size + if self.generation_batch_size is None and self.steps_per_generation is None: + self.steps_per_generation = self.gradient_accumulation_steps + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + elif self.generation_batch_size is not None and self.steps_per_generation is None: + # Just ensure the value is divisible by the global batch size + if self.generation_batch_size % (self.per_device_train_batch_size * num_processes) != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by the global batch size " + f"({self.per_device_train_batch_size * num_processes})." + ) + self.steps_per_generation = self.generation_batch_size // ( + self.per_device_train_batch_size * num_processes + ) + elif self.generation_batch_size is None and self.steps_per_generation is not None: + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + else: + raise ValueError( + "'generation_batch_size' and 'steps_per_generation' can not be both configured at the same time" + ) + + if self.do_eval and self.eval_strategy != "no": + # Determine the number of generations to use for evaluation + num_generations = self.num_generations_eval or self.num_generations + + # Just ensure the value is divisible by the global batch size + if (self.per_device_eval_batch_size * num_processes) % num_generations != 0: + raise ValueError( + f"The global eval batch size ({self.per_device_eval_batch_size} * {num_processes}) must be " + f"divisible by the number of generations used for evaluation ({num_generations})." + ) + + # The generation batch must contain full prompt groups (no partials), so it must be divisible by + # num_generations. + if self.generation_batch_size % self.num_generations != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by num_generations " + f"({self.num_generations})." + ) + + if self.delta is not None and self.use_liger_kernel: + raise ValueError("Liger kernel does not support two-sided GRPO loss yet.") diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/minillm/minillm_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/minillm/minillm_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..646f1355426e3a008cfc3473702d96ec7691e506 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/minillm/minillm_trainer.py @@ -0,0 +1,411 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import textwrap + +import torch +import torch.nn as nn +import torch.nn.functional as F +import transformers +from datasets import Dataset, IterableDataset +from packaging.version import Version +from transformers import ( + AutoModelForCausalLM, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, +) +from transformers.utils import is_peft_available + +from ...models import prepare_deepspeed +from ...trainer.grpo_trainer import GRPOTrainer, RewardFunc, RolloutFunc +from ...trainer.utils import disable_dropout_in_model, get_config_model_id +from ..utils import empty_cache +from .minillm_config import MiniLLMConfig + + +if is_peft_available(): + from peft import PeftConfig + + +def dummy_reward_func(completions: list, **kwargs): + # placeholder reward function when no reward function is provided + return [1.0 for _ in completions] + + +class MiniLLMTrainer(GRPOTrainer): + """ + Trainer for the Knowledge Distillation of Language Models (MiniLLM) method. This algorithm was initially proposed + in the paper [Knowledge Distillation of Large Language Models](https://huggingface.co/papers/2306.08543). + + Example: + + ```python + >>> from datasets import load_dataset + >>> from trl.experimental.minillm import MiniLLMTrainer + + >>> dataset = load_dataset("trl-lib/tldr", split="train") + + >>> trainer = MiniLLMTrainer( + ... model="Qwen/Qwen3-0.6B", + ... teacher_model="Qwen/Qwen3-1.7B", + ... train_dataset=dataset, + ... ) + >>> trainer.train() + ``` + + Args: + model (`str | PreTrainedModel`): + Model to be trained. Can be either: + + - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using [`~transformers.AutoModelForCausalLM.from_pretrained`] with the keyword arguments in + `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported. + teacher_model (`PreTrainedModel | nn.Module | str`): + Teacher model used for knowledge distillation. Instantiated similarly to `model`. + reward_funcs (`RewardFunc | list[RewardFunc]`, *optional*): + Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward + functions with the prompts and completions and sum the rewards. Can be either: + + - A single reward function, such as: + - A string: The *model ID* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using [`~transformers.AutoModelForSequenceClassification.from_pretrained`] with `num_labels=1` and the + keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object: Only sequence classification models are supported. + - A custom reward function: The function is provided with the prompts and the generated completions, + plus any additional columns in the dataset. It should return a list of rewards. Custom reward + functions can also return `None` when the reward is not applicable to those samples. This is useful + for multi-task training where different reward functions apply to different types of samples. When a + reward function returns `None` for a sample, that reward function is excluded from the reward + calculation for that sample. For more details, see [Using a custom reward + function](#using-a-custom-reward-function). + + The trainer's state is also passed to the reward function. The trainer's state is an instance of + [`~transformers.TrainerState`] and can be accessed by accessing the `trainer_state` argument to the + reward function's signature. + - A list of reward functions, where each item can independently be any of the above types. Mixing different + types within the list (e.g., a string model ID and a custom reward function) is allowed. + args ([`experimental.minillm.MiniLLMConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset is + ignored. The format of the samples can be either: + + - [Standard](dataset_formats#standard): Each sample contains plain text. + - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role + and content). + eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`): + Dataset to use for evaluation. It must meet the same requirements as `train_dataset`. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. The padding side must be set to "left". If `None`, the + processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A + padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token, + `tokenizer.eos_token` will be used as the default. + reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*): + Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either: + + - A single processing class: Used when `reward_funcs` contains only one reward function. + - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`. + If set to `None`, or if an element of the list corresponding to a [`~transformers.PreTrainedModel`] is + `None`, the tokenizer for the model is automatically loaded using + [`~transformers.AutoTokenizer.from_pretrained`]. For elements in `reward_funcs` that are custom reward + functions (not [`~transformers.PreTrainedModel`]), the corresponding entries in `reward_processing_classes` + are ignored. + callbacks (list of [`~transformers.TrainerCallback`], *optional*): + List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed + in [here](https://huggingface.co/docs/transformers/main_classes/callback). + + If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`] + method. + optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`, *optional*, defaults to `(None, None)`): + A tuple containing the optimizer and the scheduler to use. Will default to an instance of [`AdamW`] on your + model and a scheduler given by [`get_linear_schedule_with_warmup`] controlled by `args`. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration used to wrap the model. If `None`, the model is not wrapped. + rollout_func (`RolloutFunc`, *optional*): + Function to use for generating completions. It must take prompts, args, and processing_class as parameters + and return a dict with `"prompt_ids"`, `"completion_ids"`, and `"logprobs"` fields. Any other fields that + are forwarded to the reward functions. This feature is experimental and may change or be removed at any + time without prior notice. + """ + + _tag_names = ["trl", "minillm"] + _name = "MiniLLM" + _paper = { + "title": "MiniLLM: Knowledge Distillation of Large Language Models", + "id": "2306.08543", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @inproceedings{ + gu2024minillm, + title={{MiniLLM: Knowledge Distillation of Large Language Models}}, + author={Yuxian Gu and Li Dong and Furu Wei and Minlie Huang}, + booktitle={The Twelfth International Conference on Learning Representations}, + year={2024}, + url={https://openreview.net/forum?id=5h0qf7IBZZ} + }"""), + } + + def __init__( + self, + model: str | PreTrainedModel, + teacher_model: PreTrainedModel | nn.Module | str, + reward_funcs: RewardFunc | list[RewardFunc] | None = None, + args: MiniLLMConfig | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + peft_config: "PeftConfig | None" = None, + rollout_func: RolloutFunc | None = None, + ): + if reward_funcs is None: + reward_funcs = [dummy_reward_func] + + # Args + if args is None: + model_name = model if isinstance(model, str) else get_config_model_id(model.config) + model_name = model_name.split("/")[-1] + args = MiniLLMConfig(f"{model_name}-MiniLLM") + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model, + reward_funcs, + args=args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + reward_processing_classes=reward_processing_classes, + callbacks=callbacks, + optimizers=optimizers, + peft_config=peft_config, + rollout_func=rollout_func, + ) + + if args.teacher_model_init_kwargs is None: + teacher_model_init_kwargs = {} + elif not isinstance(teacher_model, str): + raise ValueError( + "You passed teacher_model_init_kwargs to the MiniLLMConfig, but your teacher_model is already instantiated." + ) + else: + teacher_model_init_kwargs = args.teacher_model_init_kwargs + teacher_model_init_kwargs["dtype"] = ( + teacher_model_init_kwargs["dtype"] + if teacher_model_init_kwargs["dtype"] in ["auto", None] + else getattr(torch, teacher_model_init_kwargs["dtype"]) + ) + + if isinstance(teacher_model, str): + teacher_model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + teacher_model = AutoModelForCausalLM.from_pretrained(teacher_model, **teacher_model_init_kwargs) + + # Disable dropout in the model + if args.disable_dropout: + disable_dropout_in_model(self.model) + + if self.is_deepspeed_enabled: + self.teacher_model = prepare_deepspeed(teacher_model, self.accelerator) + else: + self.teacher_model = self.accelerator.prepare_model(teacher_model, evaluation_mode=True) + + self.temperature = args.temperature + self.kd_temperature = args.kd_temperature + self.single_step_decomposition = args.single_step_decomposition + self.rkl_advantage = args.rkl_advantage + self.gamma = args.gamma + self.length_normalization = args.length_normalization + + def _single_step_decomposition_loss( + self, + student_log_probs: torch.Tensor, + teacher_log_probs: torch.Tensor, + mask: torch.Tensor | None = None, + reduction: str = "batchmean", + ): + """ + Compute the MiniLLM loss for knowledge distillation using F.kl_div. See Eq. (1) of + https://huggingface.co/papers/2306.08543 for the definition. + + Args: + student_log_probs: + Per-token log-probabilities from the student, of shape (batch_size, sequence_length) + teacher_log_probs: + Per-token log-probabilities from the teacher, of shape (batch_size, sequence_length) + mask: + Optional boolean tensor of shape (batch_size, sequence_length) selecting the tokens to include in the + loss (e.g. excluding padding) + reduction: + Specifies the reduction to apply to the output: 'batchmean' (default), 'sum' or 'mean'; any other value + returns the unreduced per-token loss + + Returns: + loss: Scalar tensor with the single-step KL regularization loss (unreduced if `reduction` is not one of the + above) + """ + reg_loss = F.kl_div( + teacher_log_probs, student_log_probs, reduction="none", log_target=True + ) # (batch_size, sequence_length) + + # Masking + if mask is not None: + reg_loss = reg_loss[mask] + + # Apply reduction + if reduction == "batchmean": + return reg_loss.sum() / mask.sum() if mask is not None else reg_loss.sum() / reg_loss.size(0) + elif reduction == "sum": + return reg_loss.sum() + elif reduction == "mean": + return reg_loss.mean() + else: + return reg_loss + + def _compute_advantage( + self, + student_log_probs_on_labels: torch.Tensor, + teacher_log_probs_on_labels: torch.Tensor, + mask: torch.Tensor | None = None, + ) -> torch.Tensor: + r"""Compute the advantage for Reverse KL Divergence. + + Mostly following [this + implementation](https://github.com/microsoft/LMOps/blob/e210d2c026b9958617887762400778ace81172e6/minillm/minillm/losses.py#L37-L49). + + $$ \text{rewards}_t = \text{teacher\_log\_probs\_on\_labels}_t - \text{student\_log\_probs\_on\_labels}_t $$ + + If length normalization is enabled: + + $$ \text{lengths}_t = \sum_{i=t}^{T} \gamma^{i-t} $$ + + $$ \text{advantages}_t = \frac{\sum_{i=t}^{T} \gamma^{i-t} R_i}{\text{lengths}_t} $$ + + Otherwise: + + $$ \text{advantages}_t = \sum_{i=t}^{T} \gamma^{i-t} R_i $$ + + Args: + student_log_probs_on_labels: Log probabilities of the student model on the labels. + Shape: (batch_size, sequence_length) + teacher_log_probs_on_labels: Log probabilities of the teacher model on the labels. + Shape: (batch_size, sequence_length) + mask: Optional mask to apply to the log probabilities. Shape: (batch_size, sequence_length) + Returns: + advantage: Computed advantage. Shape: (batch_size, sequence_length) + """ + response_length = student_log_probs_on_labels.size(1) + if mask is None: + mask = torch.ones_like(student_log_probs_on_labels) + mask = mask.float() + student_log_probs_on_labels = student_log_probs_on_labels * mask + teacher_log_probs_on_labels = teacher_log_probs_on_labels * mask + + rewards = teacher_log_probs_on_labels - student_log_probs_on_labels # (batch_size, sequence_length) + + if self.gamma > 0.0: + gamma_pow = torch.pow(self.gamma, torch.arange(response_length, device=rewards.device)) + + advantages = rewards * gamma_pow + advantages = advantages.flip(1).cumsum(dim=1).flip(1) + + if self.length_normalization: + mask = torch.where(mask < 0.5, 1e-4, mask) + lengths = mask * gamma_pow + lengths = lengths.flip(1).cumsum(dim=1).flip(1) + advantages = advantages / lengths + else: + advantages = rewards + + return advantages + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + input_ids = torch.cat([inputs["prompt_ids"], inputs["completion_ids"]], dim=1) + attention_mask = torch.cat([inputs["prompt_mask"], inputs["completion_mask"]], dim=1) + labels = input_ids.clone() + labels[attention_mask == 0] = -100 + + # Compute student output + student_outputs = model(input_ids=input_ids, attention_mask=attention_mask, use_cache=False) + + # Compute teacher output in eval mode + self.teacher_model.eval() + with torch.no_grad(): + teacher_outputs = self.teacher_model(input_ids=input_ids, attention_mask=attention_mask, use_cache=False) + + # Slice the logits for the generated tokens using the inputs["prompts"] lengths + prompt_lengths = inputs["prompt_ids"].shape[1] + student_logits = student_outputs.logits[:, prompt_lengths - 1 : -1, :] + teacher_logits = teacher_outputs.logits[:, prompt_lengths - 1 : -1, :] + shifted_labels = input_ids[:, prompt_lengths:] + + # Apply temperature scaling + student_logits = student_logits / self.kd_temperature + teacher_logits = teacher_logits / self.kd_temperature + + # Compute log probabilities for student and probabilities for teacher + student_log_probs = F.log_softmax(student_logits, dim=-1) + teacher_log_probs = F.log_softmax(teacher_logits, dim=-1) + + student_log_probs_on_labels = torch.gather( + student_log_probs, dim=-1, index=shifted_labels.unsqueeze(-1) + ).squeeze(-1) + teacher_log_probs_on_labels = torch.gather( + teacher_log_probs, dim=-1, index=shifted_labels.unsqueeze(-1) + ).squeeze(-1) + + mask = shifted_labels != -100 + + if self.rkl_advantage: + reverse_kl_advantage = self._compute_advantage( + student_log_probs_on_labels=student_log_probs_on_labels, + teacher_log_probs_on_labels=teacher_log_probs_on_labels, + mask=mask, + ) + + inputs["advantages"] = inputs["advantages"].unsqueeze(1) + reverse_kl_advantage + + # Compute GRPO loss on verifiable reward + loss = self._compute_loss(model, inputs) + + # Compute loss + if self.single_step_decomposition: + single_step_decomposition_loss = self._single_step_decomposition_loss( + student_log_probs=student_log_probs, + teacher_log_probs=teacher_log_probs, + mask=mask, + ) + + loss += single_step_decomposition_loss + + # Empty cache + empty_cache() + + # Return loss + return (loss, student_outputs) if return_outputs else loss diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/nash_md/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/nash_md/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5b80c1515bed13913e9497e35e6f79552deb40dc --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/nash_md/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .nash_md_config import NashMDConfig +from .nash_md_trainer import NashMDTrainer + + +__all__ = ["NashMDConfig", "NashMDTrainer"] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/nash_md/nash_md_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/nash_md/nash_md_config.py new file mode 100644 index 0000000000000000000000000000000000000000..2d52d08ecbe7bde752f9b1ae3455c56bf31e445d --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/nash_md/nash_md_config.py @@ -0,0 +1,46 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field + +from ..online_dpo import OnlineDPOConfig + + +@dataclass +class NashMDConfig(OnlineDPOConfig): + r""" + Configuration class for the [`experimental.nash_md.NashMDTrainer`]. + + Subclass of [`experimental.online_dpo.OnlineDPOConfig`] we can use all its arguments and add the following: + + Parameters: + mixture_coef (`float` or `list[float]`, *optional*, defaults to `0.5`): + Logit mixture coefficient for the model and reference model. If a list of floats is provided then the + mixture coefficient is selected for each new epoch and the last coefficient is used for the rest of the + epochs. + """ + + mixture_coef: list[float] = field( + default_factory=lambda: [0.5], + metadata={ + "help": "Logit mixture coefficient for the model and reference model. If a list of floats is provided " + "then the mixture coefficient is selected for each new epoch and the last coefficient is used for the " + "rest of the epochs." + }, + ) + + def __post_init__(self): + super().__post_init__() + if hasattr(self.mixture_coef, "__len__") and len(self.mixture_coef) == 1: + self.mixture_coef = self.mixture_coef[0] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/nash_md/nash_md_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/nash_md/nash_md_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..fd2f7c816c38135d376e4ac99f96d5a88a579a91 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/nash_md/nash_md_trainer.py @@ -0,0 +1,509 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import textwrap +from collections.abc import Callable +from typing import Any + +import torch +import torch.nn as nn +import torch.nn.functional as F +from datasets import Dataset, IterableDataset +from transformers import ( + BaseImageProcessor, + FeatureExtractionMixin, + GenerationMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, +) +from transformers.trainer_utils import EvalPrediction +from transformers.training_args import OptimizerNames +from transformers.utils import is_peft_available + +from ...data_utils import maybe_apply_chat_template +from ...models.utils import unwrap_model_for_generation +from ...trainer.utils import selective_log_softmax +from ..online_dpo import OnlineDPOTrainer +from ..utils import empty_cache, get_reward, truncate_right +from .nash_md_config import NashMDConfig + + +if is_peft_available(): + from peft import PeftConfig, PeftModel + + +class GeometricMixtureWrapper(GenerationMixin): + """ + Geometric Mixture generation wrapper that samples from the logits of two model's geometric mixture. + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be wrapped. + ref_model ([`~transformers.PreTrainedModel`]): The reference model. + generation_config ([`~transformers.GenerationConfig`]): The generation config. + mixture_coef (`float`, *optional* - default: 0.5): The mixture coefficient. + """ + + main_input_name = "input_ids" + _supports_cache_class = False + _supports_static_cache = False + _is_stateful = False + + def __init__(self, model, ref_model, generation_config, mixture_coef=0.5, device=None): + super().__init__() + + self.model = model + self.config = model.config + self.ref_model = ref_model + self.generation_config = generation_config + self.mixture_coef = mixture_coef + self.device = device + if hasattr(self.model, "_is_stateful"): + self._is_stateful = self.model._is_stateful + + def __call__(self, *args, **kwargs): + return self.forward(*args, **kwargs) + + @torch.inference_mode() + def forward(self, *args, **kwargs): + model_outputs = self.model(*args, **kwargs) + model_logits = model_outputs.logits + ref_model_logits = self.ref_model(*args, **kwargs).logits + + model_outputs.logits = torch.nn.functional.log_softmax( + self.mixture_coef * ref_model_logits + (1 - self.mixture_coef) * model_logits, dim=-1 + ) + + return model_outputs + + def prepare_inputs_for_generation(self, *args, **kwargs): + # turn off cache in the generation config + kwargs["use_cache"] = False + model_inputs = self.model.prepare_inputs_for_generation(*args, **kwargs) + _ = self.ref_model.prepare_inputs_for_generation(*args, **kwargs) + + return model_inputs + + def _validate_model_class(self): + self.model._validate_model_class() + + def _validate_model_kwargs(self, model_kwargs): + return self.model._validate_model_kwargs(model_kwargs) + + +class NashMDTrainer(OnlineDPOTrainer): + """ + Trainer for the Nash-MD method. + + It is implemented as a subclass of [`experimental.online_dpo.OnlineDPOTrainer`]. + + Args: + model ([`~transformers.PreTrainedModel`]): + The model to train, preferably an `AutoModelForCausalLM`. + ref_model ([`~transformers.PreTrainedModel`]): + Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation + and loss. If no reference model is provided, the trainer will create a reference model with the same + architecture as the model to be optimized. + reward_funcs ([`~transformers.PreTrainedModel`]): + The reward model to score completions with, preferably an + [`~transformers.AutoModelForSequenceClassification`]. + args ([`experimental.nash_md.NashMDConfig`]): + The NashMD config arguments to use for training. + data_collator ([`~transformers.DataCollator`]): + The data collator to use for training. If None is specified, the default data collator + ([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the + maximum length of the sequences in the batch, given a dataset of paired sequences. + train_dataset ([`~datasets.Dataset`]): + The dataset to use for training. + eval_dataset ([`~datasets.Dataset`]): + The dataset to use for evaluation. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + peft_config ([`~peft.PeftConfig`], *optional*): + The peft config to use for training. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to + metric values. + callbacks (`list[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + """ + + _tag_names = ["trl", "nash-md"] + _name = "Nash-MD" + _paper = { + "title": "Nash Learning from Human Feedback", + "id": "2312.00886", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @inproceedings{munos2024nash, + title = {{Nash Learning from Human Feedback}}, + author = {R{\'{e}}mi Munos and Michal Valko and Daniele Calandriello and Mohammad Gheshlaghi Azar and Mark Rowland and Zhaohan Daniel Guo and Yunhao Tang and Matthieu Geist and Thomas Mesnard and C{\\^{o}}me Fiegel and Andrea Michi and Marco Selvi and Sertan Girgin and Nikola Momchev and Olivier Bachem and Daniel J. Mankowitz and Doina Precup and Bilal Piot}, + year = 2024, + booktitle = {Forty-first International Conference on Machine Learning, {ICML} 2024, Vienna, Austria, July 21-27, 2024}, + publisher = {OpenReview.net}, + url = {https://openreview.net/forum?id=Y5AmNYiyCQ} + }"""), + } + + def __init__( + self, + model: PreTrainedModel | nn.Module = None, + ref_model: PreTrainedModel | nn.Module = None, + reward_funcs: PreTrainedModel | nn.Module | None = None, + args: NashMDConfig | None = None, + data_collator: Callable | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + processing_class: PreTrainedTokenizerBase + | BaseImageProcessor + | FeatureExtractionMixin + | ProcessorMixin + | None = None, + peft_config: "PeftConfig | None" = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + ) -> None: + super().__init__( + model=model, + ref_model=ref_model, + reward_funcs=reward_funcs, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + reward_processing_classes=processing_class, + peft_config=peft_config, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + self._mixture_coef = self.args.mixture_coef + + # Overwrite the stats dictionary to include NashMD specific statistics + self.stats = { + # Remove "non_score_reward", "rlhf_reward", "scores_margin" + # Add "mixture_coef" + "loss/kl": [], + "objective/entropy": [], + "loss/score": [], + "rewards/probabilities": [], + "rewards/accuracies": [], + "rewards/margins": [], + "logps/chosen": [], + "logps/rejected": [], + "val/model_contain_eos_token": [], + "val/ref_contain_eos_token": [], + "rewards/chosen": [], + "rewards/rejected": [], + "beta": [], + "mixture_coef": [], + } + if len(self.reward_funcs) != 1: + raise ValueError("NashMDTrainer only supports one reward function/model.") + self.reward_funcs = self.reward_funcs[0] + + @property + def mixture_coef(self): + if isinstance(self._mixture_coef, list): + epoch = self.state.epoch + return self._mixture_coef[epoch] if epoch < len(self._mixture_coef) else self._mixture_coef[-1] + else: + return self._mixture_coef + + def _generate_completions(self, model, prompts): + # Generate completions from the policy model. + with ( + unwrap_model_for_generation( + model, + self.accelerator, + generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762 + ) as unwrapped_policy_for_gen_ctx + ): + model_output = unwrapped_policy_for_gen_ctx.generate( + input_ids=prompts["input_ids"], + attention_mask=prompts["attention_mask"], + generation_config=self.generation_config, + ) + + # Get the DDP/FSDP unwrapped version of the main model. + # This will be the policy model for GeometricMixtureWrapper (PEFT adapters active if PEFT is used). + policy_model_for_gmw = self.accelerator.unwrap_model(model) + + # Determine the correct reference model for GeometricMixtureWrapper. + # This also needs to be DDP/FSDP unwrapped. + ref_model_for_gmw: torch.nn.Module + if self.ref_model is None: + # No explicit ref_model is provided. + # Use the base of the main `model` if it's a PEFT model. + # policy_model_for_gmw is already DDP-unwrapped. + if is_peft_available() and isinstance(policy_model_for_gmw, PeftModel): + ref_model_for_gmw = policy_model_for_gmw.get_base_model() + else: + # Not a PEFT model (or PEFT not available), or already a base model. + # Use the DDP-unwrapped policy model itself as the reference. + ref_model_for_gmw = policy_model_for_gmw + else: + # An explicit ref_model is provided. Unwrap it for DDP/FSDP. + ref_model_for_gmw = self.accelerator.unwrap_model(self.ref_model) + + # Both models given to GeometricMixtureWrapper (policy_model_for_gmw and ref_model_for_gmw) are DDP-unwrapped. + with torch.no_grad(): # Ensure no_grad context for mixture model generation + mixture_model = GeometricMixtureWrapper( + model=policy_model_for_gmw, + ref_model=ref_model_for_gmw, + generation_config=self.generation_config, + mixture_coef=self.mixture_coef, + device=self.accelerator.device, + ) + + # TODO: use self._override_model_generation_config for both models? + mixture_output = mixture_model.generate( + input_ids=prompts["input_ids"], + attention_mask=prompts["attention_mask"], + generation_config=self.generation_config, + ) + + return model_output, mixture_output + + def _process_completions(self, model_output, mixture_output, prompts): + context_length = prompts["input_ids"].shape[1] + + # Process model completions + model_completion_ids = model_output[:, context_length:] + model_completion_ids, model_completion_mask = truncate_right( + model_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id + ) + model_data = { + "input_ids": torch.cat((prompts["input_ids"], model_completion_ids), dim=1), + "attention_mask": torch.cat((prompts["attention_mask"], model_completion_mask), dim=1), + "raw": prompts["raw"], + } + + # Process reference model completions + mixture_completion_ids = mixture_output[:, context_length:] + mixture_completion_ids, mixture_completion_mask = truncate_right( + mixture_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id + ) + mixture_data = { + "input_ids": torch.cat((prompts["input_ids"], mixture_completion_ids), dim=1), + "attention_mask": torch.cat((prompts["attention_mask"], mixture_completion_mask), dim=1), + "raw": prompts["raw"], + } + + return model_data, mixture_data + + def _compute_rewards(self, model_data, mixture_data, context_length): + with torch.no_grad(): + _, model_scores, _ = get_reward( + self.reward_funcs, model_data["input_ids"], self.processing_class.pad_token_id, context_length + ) + _, mixture_scores, _ = get_reward( + self.reward_funcs, mixture_data["input_ids"], self.processing_class.pad_token_id, context_length + ) + + # Apply EOS penalty if needed + if self.args.missing_eos_penalty is not None: + model_contain_eos = torch.any(model_data["input_ids"] == self.processing_class.eos_token_id, dim=-1) + mixture_contain_eos = torch.any(mixture_data["input_ids"] == self.processing_class.eos_token_id, dim=-1) + model_scores[~model_contain_eos] -= self.args.missing_eos_penalty + mixture_scores[~mixture_contain_eos] -= self.args.missing_eos_penalty + + return model_scores, mixture_scores + + def _compute_logprobs(self, model, model_data, context_length): + def compute_logprobs_for_data(m, data): + output = m(data["input_ids"], attention_mask=data["attention_mask"]) + logits = output.logits[:, context_length - 1 : -1] + token_logprobs = selective_log_softmax(logits, data["input_ids"][:, context_length:]) + return token_logprobs + + # Compute logprobs for model completions under the model + model_logprobs_model_data = compute_logprobs_for_data(model, model_data) + + # Compute logprobs of model completions under the reference model + with torch.no_grad(): + if self.ref_model is None: + with model.disable_adapter(): + ref_logprobs_model_data = compute_logprobs_for_data(model, model_data) + else: + ref_logprobs_model_data = compute_logprobs_for_data(self.ref_model, model_data) + + # Mask padding tokens + model_padding_mask = model_data["attention_mask"][:, context_length:] == 0 + model_logprobs_model_data = model_logprobs_model_data.masked_fill(model_padding_mask, 0.0) + ref_logprobs_model_data = ref_logprobs_model_data.masked_fill(model_padding_mask, 0.0) + + return (model_logprobs_model_data, ref_logprobs_model_data) + + def _compute_losses( + self, + model_logprobs_model_data, + ref_logprobs_model_data, + probability, + ): + # reinforce score where 0.5 is a control variate + score = (probability - 0.5) * model_logprobs_model_data.sum(1) + + # kl divergence via reinforce + with torch.no_grad(): + log_ratio = model_logprobs_model_data - ref_logprobs_model_data + kl_div_log = log_ratio.sum(1) + kl_div_loss = (log_ratio * model_logprobs_model_data).sum(1) + + # final loss + loss = self.beta * kl_div_loss - score + + return loss.mean(), score, kl_div_log + + def _log_statistics( + self, + model_data, + mixture_data, + model_logprobs_model_data, + ref_logprobs_model_data, + probability, + score, + kl_div, + context_length, + model_scores, + mixture_scores, + ): + # Helper function to gather and compute mean + def gather_mean(tensor): + return self.accelerator.gather_for_metrics(tensor).mean().item() + + # Log score + self.stats["loss/score"].append(gather_mean(score)) + # Log KL divergence + self.stats["loss/kl"].append(gather_mean(kl_div)) + + # Log logprobs + model_logprobs_model_data_sum = model_logprobs_model_data.sum(1) + ref_logprobs_model_data_sum = ref_logprobs_model_data.sum(1) + + self.stats["logps/chosen"].append(gather_mean(model_logprobs_model_data_sum)) + self.stats["logps/rejected"].append(gather_mean(ref_logprobs_model_data_sum)) + + # Log rewards + self.stats["rewards/chosen"].append(gather_mean(model_scores)) + self.stats["rewards/rejected"].append(gather_mean(mixture_scores)) + + # Log probabilities + self.stats["rewards/probabilities"].append(gather_mean(probability)) + + # Calculate entropy for model data + entropy_model_data = -model_logprobs_model_data.sum(1) + self.stats["objective/entropy"].append(gather_mean(entropy_model_data)) + + # Calculate margins + margin = model_logprobs_model_data_sum - ref_logprobs_model_data_sum + self.stats["rewards/margins"].append(gather_mean(margin)) + + # Calculate accuracy + accuracy = (margin > 0).float() + self.stats["rewards/accuracies"].append(gather_mean(accuracy)) + + # Log EOS token statistics + model_eos = (model_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1) + mixture_eos = (mixture_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1) + self.stats["val/model_contain_eos_token"].append(gather_mean(model_eos.float())) + self.stats["val/ref_contain_eos_token"].append(gather_mean(mixture_eos.float())) + + # Log beta and mixture coef + self.stats["beta"].append(self.beta) + self.stats["mixture_coef"].append(self.mixture_coef) + + def training_step( + self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None + ) -> torch.Tensor: + model.train() + + # Apply chat template and tokenize the input + batch_size = len(next(iter(inputs.values()))) + prompts = inputs["prompt"] + inputs = [{k: v[i] for k, v in inputs.items()} for i in range(batch_size)] + inputs = [maybe_apply_chat_template(x, self.processing_class) for x in inputs] + inputs = [self.tokenize_row(x, self.model.config.is_encoder_decoder, self.processing_class) for x in inputs] + inputs = self.data_collator(inputs) + + # need the prompt_ only + inputs = self._prepare_inputs(inputs) + context_length = inputs["prompt_input_ids"].shape[1] + prompts = { + "input_ids": inputs["prompt_input_ids"], + "attention_mask": inputs["prompt_attention_mask"], + "raw": prompts, + } + del inputs + + # Sample completions from both the model and the reference model + model_output, mixture_output = self._generate_completions(model, prompts) + + # Process model completions + model_data, mixture_data = self._process_completions(model_output, mixture_output, prompts) + + # Compute rewards + model_scores, mixture_scores = self._compute_rewards(model_data, mixture_data, context_length) + # probability of the model data vs the mixture data + probability = F.sigmoid(model_scores - mixture_scores) + + # Compute logprobs + model_logprobs_model_data, ref_logprobs_model_data = self._compute_logprobs(model, model_data, context_length) + + # Compute loss + loss, score, kl_div = self._compute_losses(model_logprobs_model_data, ref_logprobs_model_data, probability) + + # Log everything + self._log_statistics( + model_data, + mixture_data, + model_logprobs_model_data.detach(), + ref_logprobs_model_data, + probability, + score.detach(), + kl_div.detach(), + context_length, + model_scores, + mixture_scores, + ) + + if ( + self.args.torch_empty_cache_steps is not None + and self.state.global_step % self.args.torch_empty_cache_steps == 0 + ): + empty_cache() + + kwargs = {} + # For LOMO optimizers you need to explicitly use the learning rate + if self.args.optim in [OptimizerNames.LOMO, OptimizerNames.ADALOMO]: + kwargs["learning_rate"] = self._get_learning_rate() + + if self.args.n_gpu > 1: + loss = loss.mean() # mean() to average on multi-gpu parallel training + + self.accelerator.backward(loss, **kwargs) + + return loss.detach() / self.args.gradient_accumulation_steps diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/online_dpo/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/online_dpo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2a109cabc240f871544e5ccc56ee5616794c0ba9 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/online_dpo/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .online_dpo_config import OnlineDPOConfig +from .online_dpo_trainer import OnlineDPOTrainer + + +__all__ = ["OnlineDPOConfig", "OnlineDPOTrainer"] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/online_dpo/online_dpo_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/online_dpo/online_dpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..8d28fe107ed916d7de2c09989e957487e5972793 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/online_dpo/online_dpo_config.py @@ -0,0 +1,390 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class OnlineDPOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`experimental.online_dpo.OnlineDPOTrainer`]. + + This class includes only the parameters that are specific to Online DPO training. For a full list of training + arguments, please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this + class may differ from those in [`~transformers.TrainingArguments`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + reward_model_path (`str`, *optional*): + Path to the reward model. + max_new_tokens (`int`, *optional*, defaults to `64`): + Maximum number of tokens to generate per completion. + max_length (`int`, *optional*, defaults to `512`): + Maximum total length of the sequence (prompt + completion) used to compute log probabilities. If the + sequence exceeds this limit, the leftmost tokens will be truncated to preserve as much of the completion as + possible. + temperature (`float`, *optional*, defaults to `0.9`): + Temperature for sampling. The higher the temperature, the more random the completions. + missing_eos_penalty (`float`, *optional*): + Penalty applied to the score when the model fails to generate an EOS token. This is useful to encourage to + generate completions shorter than the maximum length (`max_new_tokens`). The penalty must be a positive + value. + beta (`float` or `list[float]`, *optional*, defaults to `0.1`): + Parameter controlling the deviation from the reference model. Higher β means less deviation from the + reference model. For the IPO loss (`loss_type="ipo"`), β is the regularization parameter denoted by τ in + the [paper](https://huggingface.co/papers/2310.12036). If a list of floats is provided then the β is + selected for each new epoch and the last β is used for the rest of the epochs. + loss_type (`str`, *optional*, defaults to `"sigmoid"`): + Type of loss to use. Possible values are: + + - `"sigmoid"`: sigmoid loss from the original [DPO](https://huggingface.co/papers/2305.18290) paper. + - `"ipo"`: IPO loss from the [IPO](https://huggingface.co/papers/2310.12036) paper. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model and reference model. + + > Parameters that control generation + + top_p (`float`, *optional*, defaults to `1.0`): + Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to + `1.0` to consider all tokens. + top_k (`int`, *optional*, defaults to `0`): + Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is + disabled and all tokens are considered. + min_p (`float`, *optional*): + Minimum token probability, which will be scaled by the probability of the most likely token. It must be a + value between `0.0` and `1.0`. Typical values are in the `0.01-0.2` range. + repetition_penalty (`float`, *optional*, defaults to `1.0`): + Float that penalizes new tokens based on whether they appear in the prompt and the generated text so far. + Values > `1.0` encourage the model to use new tokens, while values < `1.0` encourage the model to repeat + tokens. + cache_implementation (`str`, *optional*): + Implementation of the cache method for faster generation when `use_vllm` is set to `False`. + generation_kwargs (`dict[str, Any]`, *optional*): + Additional keyword arguments to pass to [`~transformers.GenerationConfig`] (if using transformers) or + `SamplingParams` (if using vLLM) when sampling completions. This can be used to further customize the + generation behavior, such as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that conflict + with the other generation parameters (like `min_p`, `top_p`, etc.), they will override them. + + > Parameters that control generation acceleration powered by vLLM + + use_vllm (`bool`, *optional*, defaults to `False`): + Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for generation + instead of the default model.generate(). Requires `vllm` to be installed. + vllm_model_impl (`str`, *optional*, defaults to `"vllm"`): + Model implementation to use for vLLM. Must be one of `"transformers"` or `"vllm"`. `"transformers"`: Use + the `transformers` backend for model implementation. `"vllm"`: Use the `vllm` library for model + implementation. + vllm_mode (`str`, *optional*, defaults to `"colocate"`): + Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `"server"` or + `"colocate"`. + + - `"server"`: The trainer will send generation requests to a separate vLLM server. Make sure a TRL vLLM + server is running (start with `trl vllm-serve`). + - `"colocate"`: vLLM will run in the same process and share the training GPUs. This avoids the need for a + separate server but may cause resource contention with training. + vllm_structured_outputs_regex (`str`, *optional*): + Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled. + + > Parameters that control the vLLM server (only used when `vllm_mode` is `"server"`) + + vllm_server_base_url (`str`, *optional*): + Base URL for the vLLM server (e.g., `"http://localhost:8000"`). If provided, `vllm_server_host` and + `vllm_server_port` are ignored. + vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`): + Host of the vLLM server to connect to. Ignored if `vllm_server_base_url` is provided. + vllm_server_port (`int`, *optional*, defaults to `8000`): + Port of the vLLM server to connect to. Ignored if `vllm_server_base_url` is provided. + vllm_server_timeout (`float`, *optional*, defaults to `240.0`): + Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up after the + timeout, a `ConnectionError` is raised. + vllm_group_port (`int`, *optional*, defaults to `51216`): + Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port + is occupied, there is no need to change it. + + > Parameters that control colocated vLLM execution (only used when `vllm_mode` is `"colocate"`) + + vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.55`): + Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set to + `"colocate"`. If you are using `vllm_mode="server"`, this parameter must be passed separately when + launching the vLLM server via the `--vllm_gpu_memory_utilization` flag. + vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`): + Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set to + `"colocate"`. If you are using `vllm_mode="server"`, this parameter must be passed separately when + launching the vLLM server via the `--vllm_tensor_parallel_size` flag. + vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`): + Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but + waking the engine adds host–device transfer latency. + + > Other parameters + + ds3_gather_for_generation (`bool`, *optional*, defaults to `True`): + This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation, + improving generation speed. However, disabling this option allows training models that exceed the VRAM + capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible + with vLLM generation. + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a + string. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to allow loading models that ship custom Python code from the Hub. Forwarded to + [`~transformers.AutoModelForCausalLM.from_pretrained`]. Also applied to reward-model and reward-tokenizer + loads. + reward_weights (`list[float]`, *optional*): + Weights for combining multiple reward functions. Must match the number of reward functions. If `None`, all + reward functions are equally weighted. + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `5e-7` instead of `5e-5`. + > - `remove_unused_columns`: Defaults to `False` instead of `True`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=5e-7, + metadata={"help": "The initial learning rate for AdamW."}, + ) + remove_unused_columns: bool = field( + default=False, + metadata={"help": "Whether or not to automatically remove the columns unused by the model forward method."}, + ) + + reward_model_path: str | None = field( + default=None, + metadata={"help": "Path to the reward model."}, + ) + max_new_tokens: int = field( + default=64, + metadata={"help": "Maximum number of tokens to generate per completion."}, + ) + max_length: int = field( + default=512, + metadata={ + "help": "Maximum total length of the sequence (prompt + completion) used to compute log probabilities. If " + "the sequence exceeds this limit, the leftmost tokens will be truncated to preserve as much of the " + "completion as possible." + }, + ) + temperature: float = field( + default=0.9, + metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."}, + ) + top_p: float = field( + default=1.0, + metadata={ + "help": "Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. " + "Set to 1.0 to consider all tokens." + }, + ) + top_k: int = field( + default=0, + metadata={ + "help": "Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, " + "top-k-filtering is disabled and all tokens are considered." + }, + ) + min_p: float | None = field( + default=None, + metadata={ + "help": "Minimum token probability, which will be scaled by the probability of the most likely token. It " + "must be a value between 0.0 and 1.0. Typical values are in the 0.01-0.2 range." + }, + ) + repetition_penalty: float = field( + default=1.0, + metadata={ + "help": "Float that penalizes new tokens based on whether they appear in the prompt and the generated " + "text so far. Values > 1.0 encourage the model to use new tokens, while values < 1.0 encourage the model " + "to repeat tokens." + }, + ) + generation_kwargs: dict | None = field( + default=None, + metadata={ + "help": "Additional keyword arguments to pass to `GenerationConfig` (if using transformers) or " + "`SamplingParams` (if using vLLM) when sampling completions. This can be used to further customize the " + "generation behavior, such as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that " + "conflict with the other generation parameters (like `min_p`, `top_p`, etc.), they will override them." + }, + ) + cache_implementation: str | None = field( + default=None, + metadata={"help": "Implementation of the cache method for faster generation when use_vllm is set to False."}, + ) + missing_eos_penalty: float | None = field( + default=None, + metadata={ + "help": "Penalty applied to the score when the model fails to generate an EOS token. This is useful to " + "encourage to generate completions shorter than the maximum length (`max_new_tokens`). The penalty must be " + "a positive value." + }, + ) + beta: list[float] = field( + default_factory=lambda: [0.1], + metadata={ + "help": "Parameter controlling the deviation from the reference model. Higher β means less deviation from " + "the reference model. For the IPO loss (`loss_type='ipo'`), β is the regularization parameter denoted by " + "τ in the [paper](https://huggingface.co/papers/2310.12036). If a list of floats is provided then the β " + "is selected for each new epoch and the last β is used for the rest of the epochs." + }, + ) + loss_type: str = field( + default="sigmoid", + metadata={ + "help": "Type of loss to use.", + "choices": ["sigmoid", "ipo"], + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the model."}, + ) + use_vllm: bool = field( + default=False, + metadata={ + "help": "Whether to use vLLM for generating completions. Requires vLLM to be installed " + "(`pip install trl[vllm]`)." + }, + ) + vllm_model_impl: str = field( + default="vllm", + metadata={ + "help": "Model implementation to use for vLLM. Must be one of `transformers` or `vllm`. `transformers`: " + "Use the `transformers` backend for model implementation. `vllm`: Use the `vllm` library for " + "model implementation." + }, + ) + vllm_structured_outputs_regex: str | None = field( + default=None, + metadata={"help": "Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled."}, + ) + vllm_gpu_memory_utilization: float | None = field( + default=0.55, + metadata={ + "help": "Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set " + "to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when " + "launching the vLLM server via the `--vllm_gpu_memory_utilization` flag.", + }, + ) + vllm_mode: str = field( + default="colocate", + metadata={ + "help": "Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `'server'` or " + "`'colocate'`. `'server'`: The trainer will send generation requests to a separate vLLM server. Make sure " + "a TRL vLLM server is running (start with `trl vllm-serve`). `'colocate'`: vLLM will run in the same " + "process and share the training GPUs. This avoids the need for a separate server but may cause resource " + "contention with training.", + }, + ) + vllm_server_base_url: str | None = field( + default=None, + metadata={ + "help": "Base URL for the vLLM server (e.g., 'http://localhost:8000'). If provided, `vllm_server_host` " + "and `vllm_server_port` are ignored.", + }, + ) + vllm_server_host: str = field( + default="0.0.0.0", + metadata={"help": "Host of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."}, + ) + vllm_server_port: int = field( + default=8000, + metadata={"help": "Port of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."}, + ) + vllm_server_timeout: float = field( + default=240.0, + metadata={ + "help": "Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up " + "after the timeout, a `ConnectionError` is raised.", + }, + ) + vllm_group_port: int = field( + default=51216, + metadata={ + "help": "Port number for the weight update group. This is used to communicate with the vLLM server. " + "Unless the port is occupied, there is no need to change it.", + }, + ) + vllm_tensor_parallel_size: int = field( + default=1, + metadata={ + "help": "Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set " + "to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when " + "launching the vLLM server via the `--vllm_tensor_parallel_size` flag.", + }, + ) + vllm_enable_sleep_mode: bool = field( + default=False, + metadata={ + "help": "Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory " + "usage low, but waking the engine adds host–device transfer latency." + }, + ) + ds3_gather_for_generation: bool = field( + default=True, + metadata={ + "help": "This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for " + "generation, improving generation speed. However, disabling this option allows training models that " + "exceed the VRAM capacity of a single GPU, albeit at the cost of slower generation. Disabling this option " + "is not compatible with vLLM generation." + }, + ) + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model " + "from a string." + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": "Whether to allow loading models that ship custom Python code from the Hub. Forwarded to " + "`AutoModelForCausalLM.from_pretrained`. Also applied to reward-model and reward-tokenizer loads." + }, + ) + reward_weights: list[float] | None = field( + default=None, + metadata={ + "help": "Weights for combining multiple reward functions. Must match the number of reward functions. " + "If None, all reward functions are equally weighted." + }, + ) + + def __post_init__(self): + super().__post_init__() + + if hasattr(self.beta, "__len__") and len(self.beta) == 1: + self.beta = self.beta[0] + + if self.max_new_tokens >= self.max_length: + warnings.warn( + f"The configuration has `max_new_tokens` ({self.max_new_tokens}) >= `max_length` ({self.max_length}). " + "This will cause prompts to be truncated or completely removed in the forward pass. " + "To preserve prompts, ensure e.g. `max_length > max_new_tokens + 512`. ", + stacklevel=3, + ) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/online_dpo/online_dpo_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/online_dpo/online_dpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..f6da8910935a76a7f3eb8b2ca2f0e4913dfe0c84 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/online_dpo/online_dpo_trainer.py @@ -0,0 +1,1354 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import re +import textwrap +from collections.abc import Callable +from contextlib import nullcontext +from pathlib import Path +from typing import Any + +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.data +import transformers +from accelerate.logging import get_logger +from accelerate.utils import broadcast_object_list, gather_object, is_peft_model +from datasets import Dataset +from packaging.version import Version +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from torch.utils.data import IterableDataset +from transformers import ( + AutoModelForCausalLM, + AutoModelForSequenceClassification, + AutoTokenizer, + DataCollator, + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, + is_bitsandbytes_available, +) +from transformers.models.auto.modeling_auto import MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES +from transformers.trainer_utils import EvalPrediction +from transformers.training_args import OptimizerNames +from transformers.utils import is_peft_available, is_sagemaker_mp_enabled + +from ...data_utils import apply_chat_template, is_conversational, maybe_apply_chat_template +from ...extras.profiling import profiling_context +from ...generation.vllm_client import VLLMClient +from ...import_utils import is_vllm_available +from ...models.utils import prepare_deepspeed, prepare_fsdp, unwrap_model_for_generation +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import disable_dropout_in_model, ensure_master_addr_port, get_config_model_id +from ..utils import DPODataCollatorWithPadding, create_reference_model, empty_cache, prepare_peft_model, truncate_right +from .online_dpo_config import OnlineDPOConfig + + +if is_peft_available(): + from peft import PeftConfig + + +if is_sagemaker_mp_enabled(): + from smdistributed.modelparallel import __version__ as SMP_VERSION + + IS_SAGEMAKER_MP_POST_1_10 = Version(SMP_VERSION) >= Version("1.10") + +else: + IS_SAGEMAKER_MP_POST_1_10 = False + + +if Version(transformers.__version__) >= Version("5.2.0"): + from transformers.trainer_pt_utils import nested_gather + + +if is_vllm_available(): + from vllm import LLM, SamplingParams + from vllm.sampling_params import StructuredOutputsParams + +if is_bitsandbytes_available(): + import bitsandbytes as bnb + +logger = get_logger(__name__) + +# A reward function can be a string, interpreted as a model ID and loaded as a pretrained model, a pretrained model, or +# a callable that returns a list of floats (the rewards). The callable receives prompts, completions, and additional +# arguments from the trainer (refer to the trainer's source for details). To ensure forward compatibility, it should +# accept **kwargs. +RewardFunc = str | PreTrainedModel | Callable[..., list[float | None]] + + +class OnlineDPOTrainer(_BaseTrainer): + r""" + Initialize OnlineDPOTrainer. + + Args: + model (`str | nn.Module | PreTrainedModel`): + Model to be trained. Can be either: + + - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using [`~transformers.AutoModelForCausalLM.from_pretrained`] with the keyword arguments in + `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported. + ref_model ([`~transformers.PreTrainedModel`] or `torch.nn.Module` or `None`): + The reference model to use for training. If None is specified, the reference model will be created from the + model. + reward_funcs (`RewardFunc | list[RewardFunc]`): + Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward + functions with the prompts and completions and sum the rewards. Can be either: + + - A single reward function: Can be a string (path to model), a [`~transformers.PreTrainedModel`], or a + custom callable function. + - A list of reward functions: Must all be of compatible types. + args ([`experimental.online_dpo.OnlineDPOConfig`]): + The online DPO config arguments to use for training. + data_collator ([`~transformers.DataCollator`]): + The data collator to use for training. If None is specified, the default data collator + ([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the + maximum length of the sequences in the batch, given a dataset of paired sequences. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + The dataset to use for training. + eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`): + The dataset to use for evaluation. + processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*): + Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either: + + - A single processing class: Used when `reward_funcs` contains only one reward function. + - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`. + + If set to `None`, the tokenizer for each model-based reward function is automatically loaded using + [`~transformers.AutoTokenizer.from_pretrained`]. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration used to wrap the model. If `None`, the model is not wrapped. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to + metric values. + callbacks (`list[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + """ + + _tag_names = ["trl", "online-dpo"] + _name = "Online DPO" + _paper = { + "title": "Direct Language Model Alignment from Online AI Feedback", + "id": "2402.04792", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{guo2024direct, + title = {{Direct Language Model Alignment from Online AI Feedback}}, + author = {Shangmin Guo and Biao Zhang and Tianlin Liu and Tianqi Liu and Misha Khalman and Felipe Llinares and Alexandre Ram{\'{e}} and Thomas Mesnard and Yao Zhao and Bilal Piot and Johan Ferret and Mathieu Blondel}, + year = 2024, + eprint = {arXiv:2402.04792} + }"""), + } + + def __init__( + self, + model: PreTrainedModel | nn.Module | str, + ref_model: PreTrainedModel | nn.Module | None = None, + reward_funcs: RewardFunc | list[RewardFunc] | None = None, + args: OnlineDPOConfig | None = None, + data_collator: DataCollator | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None, + peft_config: "PeftConfig | None" = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + ) -> None: + if train_dataset is None: + raise ValueError("`train_dataset` is required") + + if ref_model is model: + raise ValueError( + "`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the " + "same as `model`, either omit the `ref_model` argument or pass `None`." + ) + + self.ref_model = ref_model + + if reward_funcs is None: + raise ValueError("`reward_funcs` must be provided.") + + # Handle reward_funcs + if not isinstance(reward_funcs, list): + reward_funcs = [reward_funcs] + self.reward_func_names = [] + + # Process reward functions (convert strings to models, collect names) + model_init_kwargs = args.model_init_kwargs or {} + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + for i, reward_func in enumerate(reward_funcs): + if isinstance(reward_func, str): + # Load model from string path + reward_funcs[i] = AutoModelForSequenceClassification.from_pretrained( + reward_func, num_labels=1, **model_init_kwargs + ) + if isinstance(reward_funcs[i], nn.Module): + self.reward_func_names.append(get_config_model_id(reward_funcs[i].config).split("/")[-1]) + else: + self.reward_func_names.append(reward_funcs[i].__name__) + self.reward_funcs = reward_funcs + + # Handle reward processing classes for reward_funcs + if reward_processing_classes is None: + reward_processing_classes = [None] * len(reward_funcs) + elif not isinstance(reward_processing_classes, list): + reward_processing_classes = [reward_processing_classes] + else: + if len(reward_processing_classes) != len(reward_funcs): + raise ValueError("The number of reward processing classes must match the number of reward functions.") + + self.reward_processing_classes = [] + for reward_processing_class_i, reward_func in zip(reward_processing_classes, reward_funcs, strict=True): + if isinstance(reward_func, PreTrainedModel): + if reward_processing_class_i is None: + reward_processing_class_i = AutoTokenizer.from_pretrained( + reward_func.config._name_or_path, trust_remote_code=args.trust_remote_code + ) + if reward_processing_class_i.pad_token_id is None: + reward_processing_class_i.pad_token = reward_processing_class_i.eos_token + # Set pad token ID on reward model config + reward_func.config.pad_token_id = reward_processing_class_i.pad_token_id + self.reward_processing_classes.append(reward_processing_class_i) + + # Handle reward_weights + if args.reward_weights is not None: + if len(args.reward_weights) != len(self.reward_funcs): + raise ValueError( + f"Number of reward weights ({len(args.reward_weights)}) must match number of reward " + f"functions ({len(self.reward_funcs)})" + ) + self.reward_weights = torch.tensor(args.reward_weights, dtype=torch.float32) + else: + self.reward_weights = torch.ones(len(self.reward_funcs), dtype=torch.float32) + + if args is None: + raise ValueError("`args` must be provided.") + + # Check that the processing_class is provided + if processing_class is None: + raise ValueError("`processing_class` must be provided.") + + model_init_kwargs = args.model_init_kwargs or {} + if isinstance(model, str): + model_id = model + + # Handle dtype in model_init_kwargs + dtype = model_init_kwargs.get("dtype", "auto") + if isinstance(dtype, torch.dtype) or dtype == "auto" or dtype is None: + pass + elif isinstance(dtype, str): + dtype = getattr(torch, dtype) + model_init_kwargs["dtype"] = dtype + else: + raise ValueError( + "Invalid `dtype` passed to `OnlineDPOConfig`. Expected either 'auto' or a string " + f"representing a `torch.dtype` (e.g., 'float32'), but got {dtype}." + ) + model_init_kwargs["device_map"] = model_init_kwargs.get("device_map", "auto") + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + + model = AutoModelForCausalLM.from_pretrained(model_id, **model_init_kwargs) + else: + if args.model_init_kwargs is not None: + raise ValueError( + "You passed `model_init_kwargs` to the `OnlineDPOConfig`, but your model is already instantiated. " + "This argument can only be used when the `model` argument is a string." + ) + self.is_encoder_decoder = model.config.is_encoder_decoder + self.is_vision_model = model.config.model_type in MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES.keys() + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if peft_config is not None or is_peft_model(model): + model = prepare_peft_model(model, peft_config, args) + + # Enable gradient checkpointing if requested + if args.gradient_checkpointing: + model = self._enable_gradient_checkpointing(model, args) + + # Disable dropout in the model and reference model + if args.disable_dropout: + disable_dropout_in_model(model) + if self.ref_model is not None: + disable_dropout_in_model(self.ref_model) + + # Handle the ref_model + # Usually, the user wants the ref model to be the initial version of the model. When using PEFT, it's easy to + # get the ref model, as it's just the model with a disabled adapter. When not using PEFT, we need to create + # the ref model from the model by copying it and disable the gradients and set it in evaluation mode. + if ref_model is None: # No ref model provided, the most common case + if peft_config is None: + self.ref_model = create_reference_model(model) # copy, disable gradients, set eval mode + else: + self.ref_model = None # we don't need a ref model here, we can just disable the adapter. + else: # rare case, the user provided a ref model + self.ref_model = ref_model + self.ref_model.eval() + + # Disable the gradient and set the reward model in eval mode + if reward_funcs is not None: + for reward_func in reward_funcs: + if isinstance(reward_func, PreTrainedModel): + reward_func.eval() + + self.max_length = args.max_length + + self.stats = { + "objective/kl": [], + "objective/entropy": [], + "objective/non_score_reward": [], + "rewards/chosen": [], + "rewards/rejected": [], + "rewards/accuracies": [], + "rewards/margins": [], + "logps/chosen": [], + "logps/rejected": [], + "val/contain_eos_token": [], + "beta": [], + } + if self.reward_funcs is not None: + self.stats["objective/rlhf_reward"] = [] + self.stats["objective/scores_margin"] = [] + self.stats["objective/scores"] = [] + + # Store generation parameters for later use + self.use_vllm = args.use_vllm + self.num_generations = 2 # Generate 2 completions per prompt for Online DPO + self.temperature = args.temperature + self.top_p = args.top_p + self.top_k = args.top_k + self.min_p = args.min_p + self.repetition_penalty = args.repetition_penalty + self.vllm_mode = args.vllm_mode if args.use_vllm else None + self.vllm_gpu_memory_utilization = args.vllm_gpu_memory_utilization + self.vllm_tensor_parallel_size = args.vllm_tensor_parallel_size + self.vllm_model_impl = args.vllm_model_impl + + # Handle pad token for processors or tokenizers + if isinstance(processing_class, ProcessorMixin): + self._tokenizer = processing_class.tokenizer + elif isinstance(processing_class, PreTrainedTokenizerBase): + self._tokenizer = processing_class + else: + raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`") + + if self._tokenizer.pad_token is None: + self._tokenizer.pad_token = self._tokenizer.eos_token + + # Vision tokens for VLM support + self.image_token_id = getattr(processing_class, "image_token_id", None) + self.vision_start_token_id = getattr(processing_class, "vision_start_token_id", None) + self.vision_end_token_id = getattr(processing_class, "vision_end_token_id", None) + # Get the image token string for token collapsing + self.image_token = None + if self.image_token_id is not None: + self.image_token = self._tokenizer.decode([self.image_token_id]) + + # Define the collator if not provided + if data_collator is None: + data_collator = DPODataCollatorWithPadding(pad_token_id=self._tokenizer.pad_token_id) + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + self._beta = args.beta + + # Set up generation configuration and vLLM after super().__init__ + if self.use_vllm: + if not is_vllm_available(): + raise ImportError( + "vLLM is not available and `use_vllm` is set to True. Please install vLLM with " + "`pip install trl[vllm]` to use it." + ) + + if self.vllm_mode == "server": + if self.accelerator.is_main_process: + if args.vllm_server_base_url is not None: + base_url = args.vllm_server_base_url + else: + base_url = f"http://{args.vllm_server_host}:{args.vllm_server_port}" + self.vllm_client = VLLMClient( + base_url=base_url, group_port=args.vllm_group_port, connection_timeout=args.vllm_server_timeout + ) + + # Determine device type (supports cuda, xpu, etc.) + accelerator_type = torch.accelerator.current_accelerator().type + current_device = getattr(torch, accelerator_type).current_device() + self.vllm_client.init_communicator(device=current_device) + else: + self.vllm_client = None + elif self.vllm_mode == "colocate": + # vLLM dynamically adjusts the size of the key-value cache based on available GPU memory at instantiation. + # A larger cache size improves speed, so we would expect gpu_memory_utilization=1. + # However, at this stage, the optimizer's weights are not yet loaded onto the GPU; they will be loaded + # after the first optimizer step and remain in GPU memory throughout training. So we must reserve enough + # space for them. + # Configure vLLM parameters + vllm_quantization = None + if is_bitsandbytes_available(): + for _, module in model.named_modules(): + if isinstance(module, bnb.nn.Linear4bit): + vllm_quantization = "bitsandbytes" + break + elif isinstance(module, bnb.nn.Linear8bitLt): + raise ValueError("vLLM does not support in-flight 8-bit quantization.") + vllm_kwargs = { + "model": model.name_or_path, + "tensor_parallel_size": self.vllm_tensor_parallel_size, + "gpu_memory_utilization": self.vllm_gpu_memory_utilization, + "model_impl": self.vllm_model_impl, + "max_num_seqs": self.args.per_device_train_batch_size * self.vllm_tensor_parallel_size, + "max_model_len": args.max_length + args.max_new_tokens, # max_length includes prompt + completion + "distributed_executor_backend": "external_launcher", + # Feed identical seed for tp groups to ensure sampling results are the same across workers + "seed": self.accelerator.process_index // self.vllm_tensor_parallel_size, + # Latest vLLM v1 memory profiler is misled by the high default value (i.e., 32768) + "max_num_batched_tokens": 4096, + "enable_sleep_mode": self.args.vllm_enable_sleep_mode, + "quantization": vllm_quantization, + } + + # vLLM requires the environment variables to be set for distributed training. + os.environ["RANK"] = str(self.accelerator.process_index) + os.environ["LOCAL_RANK"] = str(self.accelerator.local_process_index) + os.environ["WORLD_SIZE"] = str(self.accelerator.num_processes) + # Ensure distributed rendezvous variables are set without colliding across concurrent runs + ensure_master_addr_port() + + self.llm = LLM(**vllm_kwargs) + if self.args.vllm_enable_sleep_mode: + self.llm.sleep(level=2) + else: + raise ValueError(f"vllm_mode must be either 'server' or 'colocate', got '{self.vllm_mode}'.") + # vLLM specific sampling arguments + self.structured_outputs_regex = args.vllm_structured_outputs_regex + self._last_loaded_step = -1 # tag to avoid useless loading during grad accumulation + + # Set up vLLM generation config + generation_kwargs = { + "n": 2, # 2 generations per prompt for Online DPO + "repetition_penalty": self.repetition_penalty, + "temperature": self.temperature, + "top_p": self.top_p, + "top_k": self.top_k, + "min_p": 0.0 if self.min_p is None else self.min_p, + "max_tokens": args.max_new_tokens, + "detokenize": False, # to avoid vllm to decode (we don't need it) + } + if args.generation_kwargs is not None: + generation_kwargs.update(args.generation_kwargs) + if self.structured_outputs_regex is not None: + if generation_kwargs.get("structured_outputs") is not None: + logger.warning( + "Both `vllm_structured_outputs_regex` and `generation_kwargs['structured_outputs']` are set; " + "`vllm_structured_outputs_regex` takes precedence." + ) + generation_kwargs["structured_outputs"] = StructuredOutputsParams(regex=self.structured_outputs_regex) + elif isinstance(structured_outputs_kwargs := generation_kwargs.get("structured_outputs"), dict): + generation_kwargs["structured_outputs"] = StructuredOutputsParams(**structured_outputs_kwargs) + self.generation_config = SamplingParams(**generation_kwargs) + + # When using vLLM, the main process is responsible for loading the model weights. This can cause process + # desynchronization and seems to lead to DeepSpeed hanging during initialization. To prevent this, we + # synchronize all processes after vLLM has been fully initialized. + self.accelerator.wait_for_everyone() + else: + # Set up transformers generation config + generation_kwargs = { + "max_new_tokens": args.max_new_tokens, + "do_sample": True, + "pad_token_id": self._tokenizer.pad_token_id, + "bos_token_id": self._tokenizer.bos_token_id, + "eos_token_id": self._tokenizer.eos_token_id, + "temperature": self.temperature, + "top_k": self.top_k, + "top_p": self.top_p, + "repetition_penalty": self.repetition_penalty, + "use_cache": True if not self.args.gradient_checkpointing else False, + } + # Add min_p if supported + if self.min_p is not None: + generation_kwargs["min_p"] = self.min_p + if args.generation_kwargs is not None: + generation_kwargs.update(args.generation_kwargs) + # Remove None values + generation_kwargs = {k: v for k, v in generation_kwargs.items() if v is not None} + self.generation_config = GenerationConfig(**generation_kwargs) + # Keep training-specific generation kwargs to overwrite model's original generation config + self.generation_kwargs = generation_kwargs + + if self.ref_model is not None: + if self.is_deepspeed_enabled: + self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator) + elif self.is_fsdp_enabled: + self.ref_model = prepare_fsdp(self.ref_model, self.accelerator) + else: + self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True) + if self.reward_funcs is not None: + for i, reward_func in enumerate(self.reward_funcs): + if isinstance(reward_func, PreTrainedModel): + if self.is_deepspeed_enabled: + self.reward_funcs[i] = prepare_deepspeed(reward_func, self.accelerator) + else: + # set device placement to True to make `prepare_model` move `reward_func` to device when using fsdp + self.reward_funcs[i] = self.accelerator.prepare_model( + reward_func, evaluation_mode=True, device_placement=True + ) + + @property + def beta(self): + if isinstance(self._beta, list): + epoch = self.state.epoch + return self._beta[epoch] if epoch < len(self._beta) else self._beta[-1] + else: + return self._beta + + @staticmethod + def tokenize_row(feature, is_encoder_decoder: bool, tokenizer: PreTrainedTokenizerBase) -> dict[str, Any]: + """Tokenize a single row from a DPO specific dataset.""" + if not is_encoder_decoder: + batch = tokenizer(feature["prompt"], add_special_tokens=False) + # Add BOS token to head of prompt. Avoid adding if it's already there + if tokenizer.bos_token_id is not None: + prompt_len_input_ids = len(batch["input_ids"]) + if prompt_len_input_ids == 0 or tokenizer.bos_token_id != batch["input_ids"][0]: + batch["input_ids"] = [tokenizer.bos_token_id] + batch["input_ids"] + batch["attention_mask"] = [1] + batch["attention_mask"] + else: + batch = tokenizer(feature["prompt"], add_special_tokens=True) + batch = {f"prompt_{key}": value for key, value in batch.items()} + return batch + + def _enable_gradient_checkpointing(self, model: PreTrainedModel, args: OnlineDPOConfig) -> PreTrainedModel: + """Enables gradient checkpointing for the model.""" + # Ensure use_cache is disabled + model.config.use_cache = False + + # Enable gradient checkpointing on the base model for PEFT + if is_peft_model(model): + model.base_model.gradient_checkpointing_enable() + # Enable gradient checkpointing for non-PEFT models + else: + model.gradient_checkpointing_enable() + + model.enable_input_require_grads() + return model + + def _generate_vllm(self, prompts, images=None): + eos_token_id = self._tokenizer.eos_token_id + pad_token_id = self._tokenizer.pad_token_id + + # Generate completion_ids and prompt_ids based on mode + if self.vllm_mode == "server": + completion_ids, prompt_ids = self._generate_vllm_server(prompts, images) + elif self.vllm_mode == "colocate": + completion_ids, prompt_ids = self._generate_vllm_colocate(prompts, images) + + # Shared padding, masking, and tensor conversion logic + max_prompt_length = max(len(ids) for ids in prompt_ids) + prompt_mask = [[0] * (max_prompt_length - len(ids)) + [1] * len(ids) for ids in prompt_ids] + prompt_ids = [[pad_token_id] * (max_prompt_length - len(ids)) + ids for ids in prompt_ids] + max_tokens = self.generation_config.max_tokens + completion_mask = [[1] * len(ids) + [0] * (max_tokens - len(ids)) for ids in completion_ids] + completion_ids = [ + ids + [eos_token_id] if ids[-1] != eos_token_id and len(ids) < max_tokens else ids + for ids in completion_ids + ] + completion_ids = [ids + [pad_token_id] * (max_tokens - len(ids)) for ids in completion_ids] + + # Convert to tensors + prompt_ids = torch.tensor(prompt_ids, device=self.accelerator.device) + prompt_mask = torch.tensor(prompt_mask, device=self.accelerator.device) + completion_ids = torch.tensor(completion_ids, device=self.accelerator.device) + completion_mask = torch.tensor(completion_mask, device=self.accelerator.device) + + return prompt_ids, prompt_mask, completion_ids, completion_mask + + def _generate_vllm_server(self, prompts, images=None): + """Generate completions using vLLM server mode""" + has_images = images is not None + + # Update vLLM server weights if needed + if hasattr(self, "_last_loaded_step") and self.state.global_step != self._last_loaded_step: + self._move_model_to_vllm() + self._last_loaded_step = self.state.global_step + elif not hasattr(self, "_last_loaded_step"): + self._move_model_to_vllm() + self._last_loaded_step = self.state.global_step + + # Apply chat template if conversational + if is_conversational({"prompt": prompts[0]}): + prompts_text = [apply_chat_template({"prompt": p}, self.processing_class)["prompt"] for p in prompts] + else: + prompts_text = prompts + # Gather all prompts to main process + all_prompts = gather_object(prompts_text) + if has_images: + all_images = gather_object(images) + + if self.accelerator.is_main_process: + # Since 'prompts' contains 'num_generations' duplicates, we first take unique prompts, and generate + # num_generations outputs for each one. This is faster than generating outputs for each duplicate + # prompt individually. + ordered_set_of_prompts = all_prompts[:: self.num_generations] + if has_images: + ordered_set_of_images = [ + [img] if img is not None else None for img in all_images[:: self.num_generations] + ] + else: + ordered_set_of_images = None + completion_ids = self.vllm_client.generate( + prompts=ordered_set_of_prompts, + images=ordered_set_of_images, + n=self.num_generations, + repetition_penalty=self.repetition_penalty, + temperature=self.temperature, + top_p=self.top_p, + top_k=-1 if self.top_k is None else self.top_k, + min_p=0.0 if self.min_p is None else self.min_p, + max_tokens=self.generation_config.max_tokens, + structured_outputs_regex=self.structured_outputs_regex + if hasattr(self, "structured_outputs_regex") + else None, + generation_kwargs=self.args.generation_kwargs, + )["completion_ids"] + # Flatten: each prompt generates 2 completions + completion_ids = [[comp_id] for prompt_completions in completion_ids for comp_id in prompt_completions] + else: + completion_ids = [None] * (len(all_prompts) * 2) + + # Broadcast completions to all processes + completion_ids = broadcast_object_list(completion_ids, from_process=0) + + # Each process takes its slice + process_slice = slice( + self.accelerator.process_index * len(prompts) * 2, + (self.accelerator.process_index + 1) * len(prompts) * 2, + ) + completion_ids = completion_ids[process_slice] + + # Create prompt_ids by tokenizing locally + prompt_inputs = self.processing_class( + text=prompts_text, + return_tensors="pt", + padding=True, + padding_side="left", + add_special_tokens=False, + ) + prompt_ids = [] + for prompt_tokens in prompt_inputs["input_ids"]: + prompt_ids.extend([prompt_tokens.tolist(), prompt_tokens.tolist()]) # 2 copies for 2 completions + return completion_ids, prompt_ids + + def _generate_vllm_colocate(self, prompts, images=None): + """Generate completions using vLLM colocate mode""" + if self.args.vllm_enable_sleep_mode: + # wake up colocated vLLM instances if needed + torch.cuda.empty_cache() # required to avoid OOM in some cases + self.llm.wake_up(tags=["weights"]) + + # Update model weights if needed - only after gradient accumulation completes + if self.state.global_step != self._last_loaded_step: + self._move_model_to_vllm() + self._last_loaded_step = self.state.global_step + + # Apply chat template if conversational + if is_conversational({"prompt": prompts[0]}): + prompts_text = [apply_chat_template({"prompt": p}, self.processing_class)["prompt"] for p in prompts] + else: + prompts_text = prompts + + # Prepare vLLM inputs with images if available + if images is not None: + vllm_inputs = [] + for prompt, image in zip(prompts_text, images, strict=True): + if image is not None: + vllm_inputs.append({"prompt": prompt, "multi_modal_data": {"image": image}}) + else: + vllm_inputs.append(prompt) + else: + vllm_inputs = prompts_text + + if self.args.vllm_enable_sleep_mode: + self.llm.wake_up(tags=["kv_cache"]) + + outputs = self.llm.generate(vllm_inputs, self.generation_config, use_tqdm=False) + + completion_ids = [list(output.outputs[i].token_ids) for i in range(2) for output in outputs] + prompt_ids = [list(output.prompt_token_ids) for _ in range(2) for output in outputs] + if self.args.vllm_enable_sleep_mode: + self.llm.sleep(level=2) + + return completion_ids, prompt_ids + + def _sync_fsdp2_params_to_vllm(self, module: nn.Module): + # For FSDP2, module.state_dict() already covers all parameters, so no need for recursion + for name, param in module.state_dict().items(): + # When using PEFT, we need to recover the original parameter name + name = name.removeprefix("base_model.model.").replace(".base_layer", "") + # Skip PEFT layers: they don’t exist in vLLM, and they are merged already. + if is_peft_model(module) and module.prefix in name: + continue + # When module to save, remove its prefix and discard the original module + if "original_module" in name: + continue + name = self._fix_param_name_to_vllm(name, extra_prefixes=["modules_to_save.default."]) + + if param.is_cpu: + param = param.to(torch.device("cuda")) + param = param.full_tensor() + + if self.vllm_mode == "server" and self.accelerator.is_main_process: + self.vllm_client.update_named_param(name, param) + elif self.vllm_mode == "colocate": + llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model + llm_model.load_weights([(name, param)]) + + def _move_model_to_vllm(self): + # For DeepSpeed ZeRO-3 and FSDP, we need to gather all parameters before operations + deepspeed_plugin = self.accelerator.state.deepspeed_plugin + zero_stage_3 = deepspeed_plugin is not None and deepspeed_plugin.zero_stage == 3 + if zero_stage_3: + import deepspeed + + gather_if_zero3 = deepspeed.zero.GatheredParameters + else: + gather_if_zero3 = nullcontext + + if is_peft_model(self.model): + # With PEFT and FSDP/DeepSpeed ZeRO Stage 3, we must gather the full model at once before merging, as + # merging adapters in a sharded manner is not supported. + # TODO: does this work with FSDP? + with gather_if_zero3(list(self.model.parameters())): + self.model.merge_adapter() + + # Update vLLM weights while parameters are gathered + if self.is_fsdp_enabled: # note if using FSDP, gather_if_zero3 is nullcontext + # Update vLLM weights while parameters are gathered + # For PEFT with FSDP we need to use the memory efficient post-order traversal + fsdp_plugin = getattr(self.accelerator.state, "fsdp_plugin", None) + fsdp_version = getattr(fsdp_plugin, "fsdp_version", 1) if fsdp_plugin else 1 + if fsdp_version == 1: + self._sync_fsdp1_params_to_vllm( + self.model + ) # use memory-efficient post-order traversal for FSDP + elif fsdp_version == 2: + self._sync_fsdp2_params_to_vllm(self.model) + else: + # DeepSpeed ZeRO-3 with PEFT + for name, param in self.model.named_parameters(): + # When using PEFT, we need to recover the original parameter name + name = name.removeprefix("base_model.model.").replace(".base_layer", "") + # Skip PEFT layers: they don’t exist in vLLM, and they are merged already. + if self.model.prefix in name: + continue + # When module to save, remove its prefix and discard the original module + if "original_module" in name: + continue + name = self._fix_param_name_to_vllm(name, extra_prefixes=["modules_to_save.default."]) + + if self.vllm_mode == "server" and self.accelerator.is_main_process: + self.vllm_client.update_named_param(name, param.data) + elif self.vllm_mode == "colocate": + llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model + llm_model.load_weights([(name, param.data)]) + # Unmerge adapters while parameters are still gathered + self.model.unmerge_adapter() + # Parameters will automatically be repartitioned when exiting the context + else: + # For non-PEFT models, simply gather (if needed) and update each parameter individually. + if self.is_fsdp_enabled: + fsdp_plugin = getattr(self.accelerator.state, "fsdp_plugin", None) + fsdp_version = getattr(fsdp_plugin, "fsdp_version", 1) if fsdp_plugin else 1 + if fsdp_version == 1: + self._sync_fsdp1_params_to_vllm(self.model) # use memory-efficient post-order traversal for FSDP + elif fsdp_version == 2: + self._sync_fsdp2_params_to_vllm(self.model) + else: + for name, param in self.model.named_parameters(): + name = self._fix_param_name_to_vllm(name) + with gather_if_zero3([param]): + if self.vllm_mode == "server" and self.accelerator.is_main_process: + self.vllm_client.update_named_param(name, param.data) + elif self.vllm_mode == "colocate": + llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model + llm_model.load_weights([(name, param.data)]) + + # Reset cache on vLLM + if self.vllm_mode == "server" and self.accelerator.is_main_process: + self.vllm_client.reset_prefix_cache() + elif self.vllm_mode == "colocate": + self.llm.reset_prefix_cache() + + def _sync_fsdp1_params_to_vllm(self, module: nn.Module, prefix: str = "", visited=None): + """Memory-efficient post-order traversal of FSDP modules to extract full parameters and sync with vLLM.""" + # For FSDP1, we need to recurse into children and also use summon_full_params + if visited is None: + visited = set() + for child_name, child_module in module.named_children(): + child_prefix = f"{prefix}.{child_name}" if prefix else child_name + self._sync_fsdp1_params_to_vllm( + child_module, prefix=child_prefix, visited=visited + ) # recurse into the child + + if isinstance(module, FSDP): + with FSDP.summon_full_params(module, recurse=False, writeback=False): + for param_name, param in module.named_parameters(): + full_name = f"{prefix}.{param_name}" if prefix else param_name + full_name = self._fix_param_name_to_vllm(full_name, extra_prefixes=["_fsdp_wrapped_module."]) + + if full_name in visited: + continue # skip FSDP subtrees already traversed + visited.add(full_name) + + if self.vllm_mode == "server" and self.accelerator.is_main_process: + self.vllm_client.update_named_param(full_name, param.data) + elif self.vllm_mode == "colocate": + llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model + llm_model.load_weights([(full_name, param.data)]) + + def _fix_param_name_to_vllm(self, name, extra_prefixes: list[str] | None = None): + """Clean parameter names for vLLM compatibility""" + extra_prefixes = extra_prefixes or [] + prefixes = ["_checkpoint_wrapped_module."] + extra_prefixes + for prefix in prefixes: + name = name.replace(prefix, "") + return name + + def process_vision_row( + self, features: dict[str, list | torch.Tensor], processing_class=None + ) -> dict[str, list[int]]: + """ + Process a vision row for VLM models (adapted from DPO trainer) + """ + processor = processing_class or self.processing_class + processed_features = processor(images=[features["image"]], text=features["prompt"], add_special_tokens=False) + + prompt_input_ids = processed_features["input_ids"][0] + + # Create the output dict with required fields + output = { + "prompt_input_ids": prompt_input_ids, + "prompt_attention_mask": processed_features["attention_mask"][0], + } + + # Add vision-specific fields + if "pixel_values" in processed_features: + output["pixel_values"] = processed_features["pixel_values"][0] + if "pixel_attention_mask" in processed_features: + output["pixel_attention_mask"] = processed_features["pixel_attention_mask"][0] + if "image_sizes" in processed_features: + output["image_sizes"] = processed_features["image_sizes"][0] + + return output + + def _generate(self, model, prompts, images=None): + """Generate completions using the model""" + device = next(model.parameters()).device + eos_token_id = self._tokenizer.eos_token_id + pad_token_id = self._tokenizer.pad_token_id + + # Apply chat template and tokenize the input + inputs = [{"prompt": prompt} for prompt in prompts] + + # Add images if provided (VLM support) + if images is not None: + for i, image in enumerate(images): + inputs[i]["image"] = image + + # Apply chat template to get text prompts + prompts_text = [maybe_apply_chat_template(x, self.processing_class)["prompt"] for x in inputs] + + # Handle image token collapsing/removal + # The chat template sometimes inserts a single image token into the prompt text. However, when this text is + # later tokenized, the single image token string is expanded into multiple image token IDs, depending on the + # image size. We need to handle this properly. + if self.image_token is not None and images is not None: + escaped_img_token = re.escape(self.image_token) + # Search for the image token in the chat template + if hasattr(self.processing_class, "chat_template") and self.processing_class.chat_template: + if re.search(escaped_img_token, self.processing_class.chat_template): + # Collapse repeated image tokens back into a single token + prompts_text = [ + re.sub(rf"({escaped_img_token})+", self.image_token, text) for text in prompts_text + ] + else: + # If the chat template doesn't use the image token, remove all instances + if self.vision_end_token_id is not None: + escaped_eoi_token = re.escape(self._tokenizer.decode([self.vision_end_token_id])) + prompts_text = [ + re.sub(rf"({escaped_img_token})+{escaped_eoi_token}", "", text) for text in prompts_text + ] + else: + # If vision_end_token_id is None, just remove the image tokens + prompts_text = [re.sub(rf"({escaped_img_token})+", "", text) for text in prompts_text] + + # Prepare kwargs for processing class + kwargs = {} + if images is not None: + kwargs = {"images": [[img] for img in images]} + + # Process inputs using the processing class (handles both VLM and LLM) + prompt_inputs = self.processing_class( + text=prompts_text, + return_tensors="pt", + padding=True, + padding_side="left", + add_special_tokens=False, + **kwargs, + ) + + prompt_inputs = {k: v.to(device) for k, v in prompt_inputs.items()} + # Convert vision inputs to model's dtype for proper computation + if "pixel_values" in prompt_inputs: + # Handle DataParallel wrapped models + model_dtype = getattr(model, "dtype", None) + if model_dtype is None and hasattr(model, "module"): + model_dtype = model.module.dtype + if model_dtype is not None: + prompt_inputs["pixel_values"] = prompt_inputs["pixel_values"].to(model_dtype) + + # Sample 2 completions per prompt of size `max_new_tokens` from the model + prompt_ids = prompt_inputs["input_ids"].repeat(2, 1) + prompt_mask = prompt_inputs["attention_mask"].repeat(2, 1) + + # Prepare vision inputs if available + vision_generation_kwargs = {} + if self.is_vision_model and images is not None: + if "pixel_values" in prompt_inputs: + vision_generation_kwargs["pixel_values"] = prompt_inputs["pixel_values"].repeat(2, 1, 1, 1) + if "pixel_attention_mask" in prompt_inputs: + vision_generation_kwargs["pixel_attention_mask"] = prompt_inputs["pixel_attention_mask"].repeat(2, 1) + if "image_sizes" in prompt_inputs: + vision_generation_kwargs["image_sizes"] = prompt_inputs["image_sizes"].repeat(2, 1) + if "image_grid_thw" in prompt_inputs: + vision_generation_kwargs["image_grid_thw"] = prompt_inputs["image_grid_thw"].repeat(2, 1) + + with ( + profiling_context(self, "transformers.generate"), + unwrap_model_for_generation( + model, + self.accelerator, + gather_deepspeed3_params=self.args.ds3_gather_for_generation, + generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762 + ) as unwrapped_model, + torch.no_grad(), + FSDP.summon_full_params(self.model_wrapped, recurse=False) if self.is_fsdp_enabled else nullcontext(), + ): + # Setup cache implementation if specified + if self.args.cache_implementation is not None: + unwrapped_model.generation_config.cache_implementation = self.args.cache_implementation + + # Standard generation + output = unwrapped_model.generate( + input_ids=prompt_ids, + attention_mask=prompt_mask, + generation_config=self.generation_config, + **vision_generation_kwargs, + ) + + completion_ids = output[:, prompt_ids.size(1) :] + completion_ids, completion_mask = truncate_right(completion_ids, eos_token_id, pad_token_id) + + return prompt_ids, prompt_mask, completion_ids, completion_mask + + def _calculate_rewards_from_functions(self, prompts, completions, completion_ids_list, **reward_kwargs): + """ + Calculate rewards using reward functions + """ + device = self.accelerator.device + rewards_per_func = torch.zeros(len(prompts), len(self.reward_funcs), device=device) + + # Add trainer state to reward kwargs for dynamic reward shaping + reward_kwargs["trainer_state"] = self.state + + for i, (reward_func, reward_processing_class) in enumerate( + zip(self.reward_funcs, self.reward_processing_classes, strict=True) + ): + if isinstance(reward_func, nn.Module): # Model-based reward function + # Handle conversational vs text input + if is_conversational({"prompt": prompts[0]}): + messages = [{"messages": p + c} for p, c in zip(prompts, completions, strict=True)] + texts = [apply_chat_template(x, reward_processing_class)["text"] for x in messages] + else: + texts = [p + c for p, c in zip(prompts, completions, strict=True)] + + # Tokenize and get reward scores + reward_inputs = reward_processing_class( + text=texts, return_tensors="pt", padding=True, padding_side="right", add_special_tokens=False + ) + reward_inputs = {k: v.to(device) for k, v in reward_inputs.items()} + + with torch.inference_mode(): + rewards_per_func[:, i] = reward_func(**reward_inputs).logits[:, 0] # Shape (B*G,) + else: + # Custom reward function + output_reward_func = reward_func( + prompts=prompts, completions=completions, completion_ids=completion_ids_list, **reward_kwargs + ) + # Convert None values to NaN + output_reward_func = [reward if reward is not None else torch.nan for reward in output_reward_func] + rewards_per_func[:, i] = torch.tensor(output_reward_func, dtype=torch.float32, device=device) + + # Weight and sum across all reward functions + if self.reward_weights is not None: + total_rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1) + else: + total_rewards = rewards_per_func.nansum(dim=1) + + return total_rewards + + def _forward(self, model, prompt_ids, prompt_mask, completion_ids, completion_mask, vision_inputs=None): + # Get the number of tokens to truncate from prompt + num_tokens_to_truncate = max(prompt_ids.size(1) + completion_ids.size(1) - self.max_length, 0) + + # Truncate left to avoid oom + prompt_ids = prompt_ids[:, num_tokens_to_truncate:] + prompt_mask = prompt_mask[:, num_tokens_to_truncate:] + + # Concat the prompt and completion + prompt_completion_ids = torch.cat((prompt_ids, completion_ids), dim=1) + prompt_completion_mask = torch.cat((prompt_mask, completion_mask), dim=1) + + # Prepare model kwargs with vision inputs if available + model_kwargs = {"attention_mask": prompt_completion_mask} + if vision_inputs is not None: + if "pixel_values" in vision_inputs: + model_kwargs["pixel_values"] = vision_inputs["pixel_values"] + if "pixel_attention_mask" in vision_inputs: + model_kwargs["pixel_attention_mask"] = vision_inputs["pixel_attention_mask"] + if "image_sizes" in vision_inputs: + model_kwargs["image_sizes"] = vision_inputs["image_sizes"] + if "image_grid_thw" in vision_inputs: + model_kwargs["image_grid_thw"] = vision_inputs["image_grid_thw"] + + # Get the logprobs of the completions from the model + output = model(prompt_completion_ids, **model_kwargs) + + # There is 1 offset, because the model predicts the next token + prompt_len = prompt_ids.size(1) + start_idx = prompt_len - 1 if prompt_len > 0 else 0 + # Only slice off the last logit when we have a prompt, otherwise we need all logits + end_idx = -1 if prompt_len > 0 else None + logits = output.logits[:, start_idx:end_idx] + + # Take the completion tokens logprob + logprobs = torch.take_along_dim(logits.log_softmax(dim=-1), completion_ids.unsqueeze(-1), dim=2).squeeze(-1) + return logprobs + + def training_step( + self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None + ) -> torch.Tensor: + model.train() + + prompts = inputs["prompt"] + batch_size = len(prompts) + + # Handle images for VLM support + has_images = "image" in inputs + images = None + if has_images: + images = inputs["image"] + # Convert conversational prompts to include image tokens + for prompt in prompts: + if isinstance(prompt, list): + for message in prompt: + if not isinstance(message, dict): + continue + content = message.get("content") + role = message.get("role") + if isinstance(content, str): + if role == "user": + message["content"] = [{"type": "image"}, {"type": "text", "text": content}] + elif role == "system": + message["content"] = [{"type": "text", "text": content}] + + if self.args.use_vllm: + prompt_ids, prompt_mask, completion_ids, completion_mask = self._generate_vllm(prompts, images) + else: + prompt_ids, prompt_mask, completion_ids, completion_mask = self._generate(model, prompts, images) + + contain_eos_token = torch.any(completion_ids == self._tokenizer.eos_token_id, dim=-1) + + # Extract vision inputs if available for VLM support + vision_inputs = None + if has_images and self.is_vision_model and not self.args.use_vllm: + # For vision models with transformers generation, we need to prepare vision inputs + # Process the images to get vision inputs that can be passed through the forward pass + vision_inputs = {} + kwargs = {"images": [[img] for img in images]} + processed = self.processing_class( + text=[""] * len(images), # Dummy text for vision processing + return_tensors="pt", + **kwargs, + ) + # Handle DataParallel wrapped models + model_device = getattr(model, "device", None) + model_dtype = getattr(model, "dtype", None) + if model_device is None and hasattr(model, "module"): + model_device = model.module.device + model_dtype = model.module.dtype + # Move vision tensors to device and convert to model dtype + # Need to duplicate for 2 completions per prompt + if "pixel_values" in processed: + vision_inputs["pixel_values"] = ( + processed["pixel_values"].to(model_device, dtype=model_dtype).repeat(2, 1, 1, 1) + ) + if "pixel_attention_mask" in processed: + vision_inputs["pixel_attention_mask"] = processed["pixel_attention_mask"].to(model_device).repeat(2, 1) + if "image_sizes" in processed: + vision_inputs["image_sizes"] = processed["image_sizes"].to(model_device).repeat(2, 1) + if "image_grid_thw" in processed: + vision_inputs["image_grid_thw"] = processed["image_grid_thw"].to(model_device).repeat(2, 1) + + logprobs = self._forward(model, prompt_ids, prompt_mask, completion_ids, completion_mask, vision_inputs) + with torch.no_grad(): + if self.ref_model is not None: + ref_logprobs = self._forward( + self.ref_model, prompt_ids, prompt_mask, completion_ids, completion_mask, vision_inputs + ) + else: # peft case: we just need to disable the adapter + with self.model.disable_adapter(): + ref_logprobs = self._forward( + self.model, prompt_ids, prompt_mask, completion_ids, completion_mask, vision_inputs + ) + + # Decode the completions, and format them if the input is conversational + device = logprobs.device + completions = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + if is_conversational({"prompt": prompts[0]}): + completions = [[{"role": "assistant", "content": completion}] for completion in completions] + + # Get the reward from reward functions + # First create completion_ids_list for custom reward functions + completion_ids_list = [completion_ids[i].tolist() for i in range(completion_ids.shape[0])] + + # Extract additional fields from inputs for reward functions + reward_kwargs = {} + keys = [key for key in inputs if key not in ["prompt"]] + for key in keys: + if isinstance(inputs[key], (list, tuple)): + # Repeat input fields to match number of completions (2 per prompt) + reward_kwargs[key] = inputs[key] * 2 + else: + reward_kwargs[key] = inputs[key] + + # Calculate rewards using reward functions + rewards = self._calculate_rewards_from_functions( + prompts=2 * prompts, completions=completions, completion_ids_list=completion_ids_list, **reward_kwargs + ) + + # Apply missing EOS penalty if configured + if self.args.missing_eos_penalty is not None: + rewards[~contain_eos_token] -= self.args.missing_eos_penalty + + # Split rewards into chosen/rejected pairs + first_half, second_half = rewards.split(batch_size) + mask = first_half >= second_half + + batch_range = torch.arange(batch_size, device=device) + chosen_indices = batch_range + (~mask * batch_size) + rejected_indices = batch_range + (mask * batch_size) + + # Build tensor so that the first half is the chosen examples and the second half the rejected examples + cr_indices = torch.cat((chosen_indices, rejected_indices), dim=0) # cr = chosen and rejected + cr_logprobs = logprobs[cr_indices] + cr_ref_logprobs = ref_logprobs[cr_indices] + + # mask out the padding tokens + padding_mask = ~completion_mask.bool() + cr_padding_mask = padding_mask[cr_indices] + + cr_logprobs_sum = (cr_logprobs * ~cr_padding_mask).sum(1) + cr_ref_logprobs_sum = (cr_ref_logprobs * ~cr_padding_mask).sum(1) + + # Split the chosen and rejected examples + chosen_logprobs_sum, rejected_logprobs_sum = torch.split(cr_logprobs_sum, batch_size) + chosen_ref_logprobs_sum, rejected_ref_logprobs_sum = torch.split(cr_ref_logprobs_sum, batch_size) + pi_logratios = chosen_logprobs_sum - rejected_logprobs_sum + ref_logratios = chosen_ref_logprobs_sum - rejected_ref_logprobs_sum + + logits = pi_logratios - ref_logratios + + if self.args.loss_type == "sigmoid": + losses = -F.logsigmoid(self.beta * logits) + elif self.args.loss_type == "ipo": + losses = (logits - 1 / (2 * self.beta)) ** 2 + else: + raise NotImplementedError(f"invalid loss type {self.args.loss_type}") + + loss = losses.mean() + + # Log everything + if self.reward_funcs is not None: + # When using reward_funcs, we have rewards instead of scores + scores_margin = rewards[chosen_indices] - rewards[rejected_indices] + self.stats["objective/scores_margin"].append( + self.accelerator.gather_for_metrics(scores_margin.mean()).mean().item() + ) + self.stats["objective/scores"].append(self.accelerator.gather_for_metrics(rewards.mean()).mean().item()) + self.stats["val/contain_eos_token"].append(contain_eos_token.float().mean().item()) + self.stats["logps/chosen"].append(self.accelerator.gather_for_metrics(chosen_logprobs_sum).mean().item()) + self.stats["logps/rejected"].append(self.accelerator.gather_for_metrics(rejected_logprobs_sum).mean().item()) + + kl = logprobs - ref_logprobs + mean_kl = kl.sum(1).mean() + self.stats["objective/kl"].append(self.accelerator.gather_for_metrics(mean_kl).mean().item()) + non_score_reward = (-self.beta * kl).sum(1) + mean_non_score_reward = non_score_reward.mean() + self.stats["objective/non_score_reward"].append( + self.accelerator.gather_for_metrics(mean_non_score_reward).mean().item() + ) + if self.reward_funcs is not None: + # Calculate RLHF reward by combining rewards with non_score_reward + rlhf_reward = rewards + non_score_reward + self.stats["objective/rlhf_reward"].append(self.accelerator.gather_for_metrics(rlhf_reward).mean().item()) + + mean_entropy = -logprobs.sum(1).mean() + self.stats["objective/entropy"].append(self.accelerator.gather_for_metrics(mean_entropy).mean().item()) + chosen_rewards = self.beta * (chosen_logprobs_sum - chosen_ref_logprobs_sum) + gathered_chosen_rewards = self.accelerator.gather_for_metrics(chosen_rewards) + self.stats["rewards/chosen"].append(gathered_chosen_rewards.mean().item()) + rejected_rewards = self.beta * (rejected_logprobs_sum - rejected_ref_logprobs_sum) + gathered_rejected_rewards = self.accelerator.gather_for_metrics(rejected_rewards) + self.stats["rewards/rejected"].append(gathered_rejected_rewards.mean().item()) + margin = gathered_chosen_rewards - gathered_rejected_rewards + self.stats["rewards/margins"].append(margin.mean().item()) + accuracy = margin > 0 + self.stats["rewards/accuracies"].append(accuracy.float().mean().item()) + self.stats["beta"].append(self.beta) + + if ( + self.args.torch_empty_cache_steps is not None + and self.state.global_step % self.args.torch_empty_cache_steps == 0 + ): + empty_cache() + + kwargs = {} + + # For LOMO optimizers you need to explicitly use the learning rate + if self.args.optim in [OptimizerNames.LOMO, OptimizerNames.ADALOMO]: + kwargs["learning_rate"] = self._get_learning_rate() + + if self.args.n_gpu > 1: + loss = loss.mean() # mean() to average on multi-gpu parallel training + + self.accelerator.backward(loss, **kwargs) + + return loss.detach() / self.args.gradient_accumulation_steps + + # Same as Trainer._maybe_log_save_evaluate but log our metrics + def _maybe_log_save_evaluate( + self, tr_loss, grad_norm, model, trial, epoch, ignore_keys_for_eval, start_time, learning_rate=None + ): + if self.control.should_log and self.state.global_step > self._globalstep_last_logged: + logs: dict[str, float] = {} + + # all_gather + mean() to get average loss over all processes + if Version(transformers.__version__) >= Version("5.2.0"): + tr_loss_scalar = nested_gather(tr_loss, self.args.parallel_mode).mean().item() + else: + tr_loss_scalar = self._nested_gather(tr_loss).mean().item() + + # reset tr_loss to zero + tr_loss -= tr_loss + + logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4) + if grad_norm is not None: + logs["grad_norm"] = grad_norm.detach().item() if isinstance(grad_norm, torch.Tensor) else grad_norm + if learning_rate is not None: + logs["learning_rate"] = learning_rate + else: + logs["learning_rate"] = self._get_learning_rate() + + # Add our metrics + for key, val in self.stats.items(): + logs[key] = sum(val) / len(val) + self.stats = {key: [] for key in self.stats} # reset stats + + self._total_loss_scalar += tr_loss_scalar + self._globalstep_last_logged = self.state.global_step + self.store_flos() + self.log(logs, start_time) + + metrics = None + if self.control.should_evaluate: + metrics = self._evaluate(trial, ignore_keys_for_eval) + is_new_best_metric = self._determine_best_metric(metrics=metrics, trial=trial) + + if self.args.save_strategy == "best": + self.control.should_save = is_new_best_metric + + if self.control.should_save: + self._save_checkpoint(model, trial) + self.control = self.callback_handler.on_save(self.args, self.state, self.control) + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/openenv/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/openenv/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4325e17f284102bd02848b432cd9d9ffedd32f58 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/openenv/__init__.py @@ -0,0 +1,18 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .utils import generate_rollout_completions + + +__all__ = ["generate_rollout_completions"] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/openenv/utils.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/openenv/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f8f4d573854a4fa9cf93fb8f7a354d54c7fad0c9 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/openenv/utils.py @@ -0,0 +1,214 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any + +import torch + +from ...data_utils import is_conversational +from ...extras.profiling import profiling_context +from ...import_utils import is_vllm_available + + +if is_vllm_available(): + from vllm import SamplingParams + from vllm.sampling_params import StructuredOutputsParams + + +def _build_base_generation_kwargs( + trainer, + overrides: dict[str, Any] | None = None, +) -> dict[str, Any]: + """Build base generation kwargs common to both colocate and server modes.""" + generation_kwargs: dict[str, Any] = { + "n": 1, + "temperature": trainer.temperature, + "top_k": trainer.top_k, + "min_p": 0.0 if trainer.min_p is None else trainer.min_p, + "max_tokens": trainer.max_completion_length, + } + if trainer.repetition_penalty is not None: + generation_kwargs["repetition_penalty"] = trainer.repetition_penalty + if trainer.top_p is not None: + generation_kwargs["top_p"] = trainer.top_p + + if trainer.args.generation_kwargs is not None: + generation_kwargs.update(trainer.args.generation_kwargs) + + if overrides is not None: + generation_kwargs.update(overrides) + + generation_kwargs = {key: value for key, value in generation_kwargs.items() if value is not None} + + if generation_kwargs.get("n", 1) != 1: + raise ValueError("generate_rollout_completions expects n=1.") + + return generation_kwargs + + +def _build_colocate_sampling_params( + trainer, + overrides: dict[str, Any] | None = None, + *, + logprobs: bool = True, +) -> "SamplingParams": + """Build SamplingParams for colocate mode.""" + generation_kwargs = _build_base_generation_kwargs(trainer, overrides) + + # Add colocate-specific parameters + if trainer.vllm_generation.structured_outputs_regex: + generation_kwargs["structured_outputs"] = StructuredOutputsParams( + regex=trainer.vllm_generation.structured_outputs_regex + ) + if logprobs: + generation_kwargs["logprobs"] = 0 + + return SamplingParams(**generation_kwargs) + + +def _build_server_generation_kwargs( + trainer, + overrides: dict[str, Any] | None = None, +) -> dict[str, Any]: + """Build generation kwargs for server mode.""" + return _build_base_generation_kwargs(trainer, overrides) + + +def generate_rollout_completions( + trainer, + prompts: list[str], + *, + generation_overrides: dict[str, Any] | None = None, + as_chat: bool | None = None, +) -> list[dict[str, Any]]: + """ + Generate completions for custom rollouts when vLLM is running in colocate or server mode. + + Returns one result per prompt, containing prompt and completion token ids along with per-token log probabilities + and the generated text. + """ + + if not prompts: + return [] + + if not trainer.use_vllm: + raise RuntimeError("Custom rollouts require vLLM to call generate_rollout_completions.") + + if trainer.vllm_mode == "server": + return _generate_rollout_completions_server(trainer, prompts, generation_overrides, as_chat) + elif trainer.vllm_mode == "colocate": + return _generate_rollout_completions_colocate(trainer, prompts, generation_overrides, as_chat) + else: + raise ValueError(f"vllm_mode must be 'server' or 'colocate', got '{trainer.vllm_mode}'") + + +def _generate_rollout_completions_server( + trainer, + prompts: list[str], + generation_overrides: dict[str, Any] | None = None, + as_chat: bool | None = None, +) -> list[dict[str, Any]]: + """Generate completions using vLLM server mode.""" + generation_kwargs = _build_server_generation_kwargs(trainer, generation_overrides) + + if as_chat is None: + as_chat = prompts and is_conversational({"prompt": prompts[0]}) + + with profiling_context(trainer, "vLLM.generate_rollout_server"): + if as_chat: + # Prompts are raw message dicts; use .chat() so the vLLM server applies the chat template + output = trainer.vllm_generation.vllm_client.chat( + messages=prompts, + **generation_kwargs, + chat_template_kwargs=trainer.chat_template_kwargs, + tools=trainer.tools or None, + chat_template=trainer.chat_template, + ) + else: + output = trainer.vllm_generation.vllm_client.generate(prompts=prompts, **generation_kwargs) + + # Format results to match colocate output format + results: list[dict[str, Any]] = [] + for i in range(len(prompts)): + results.append( + { + "prompt_ids": output["prompt_ids"][i], + "completion_ids": list(output["completion_ids"][i]), + "logprobs": list(output["logprobs"][i]), + "text": trainer.processing_class.decode(output["completion_ids"][i], skip_special_tokens=True), + } + ) + + return results + + +def _generate_rollout_completions_colocate( + trainer, + prompts: list[str], + generation_overrides: dict[str, Any] | None = None, + as_chat: bool | None = None, +) -> list[dict[str, Any]]: + """Generate completions using vLLM colocate mode.""" + sampling_params = _build_colocate_sampling_params(trainer, generation_overrides) + prompts_for_generation = prompts + original_size = len(prompts) + + if trainer.vllm_tensor_parallel_size > 1: + gathered_prompts = [None for _ in range(trainer.vllm_tensor_parallel_size)] + torch.distributed.all_gather_object(gathered_prompts, prompts, group=trainer.vllm_generation.tp_group) + prompts_for_generation = [prompt for group_prompts in gathered_prompts for prompt in group_prompts] + + if as_chat is None: + as_chat = prompts_for_generation and is_conversational({"prompt": prompts_for_generation[0]}) + + if trainer.args.vllm_enable_sleep_mode: + trainer.vllm_generation.llm.wake_up(tags=["kv_cache"]) + # Work around for https://github.com/vllm-project/vllm/issues/29341 + trainer.vllm_generation.llm.collective_rpc("reload_weights") + + with profiling_context(trainer, "vLLM.generate_rollout"): + if as_chat: + vllm_outputs = trainer.vllm_generation.llm.chat( + prompts_for_generation, sampling_params=sampling_params, use_tqdm=False + ) + else: + vllm_outputs = trainer.vllm_generation.llm.generate( + prompts_for_generation, sampling_params=sampling_params, use_tqdm=False + ) + + results: list[dict[str, Any]] = [] + for request in vllm_outputs: + if not request.outputs: + results.append({"prompt_ids": request.prompt_token_ids, "completion_ids": [], "logprobs": [], "text": ""}) + continue + sequence = request.outputs[0] + logprobs = [next(iter(token_logprob.values())).logprob for token_logprob in sequence.logprobs] + results.append( + { + "prompt_ids": request.prompt_token_ids, + "completion_ids": sequence.token_ids, + "logprobs": logprobs, + "text": sequence.text, + } + ) + + if trainer.vllm_tensor_parallel_size > 1: + local_rank_in_group = torch.distributed.get_rank(group=trainer.vllm_generation.tp_group) + tp_slice = slice(local_rank_in_group * original_size, (local_rank_in_group + 1) * original_size) + results = results[tp_slice] + + if trainer.args.vllm_enable_sleep_mode: + trainer.vllm_generation.llm.sleep(level=2) + + return results diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/openreward/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/openreward/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eae7806a5a213157f814cead9b2d76158ea07bb4 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/openreward/__init__.py @@ -0,0 +1,18 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from ._spec import OpenRewardSpec + + +__all__ = ["OpenRewardSpec"] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/openreward/_spec.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/openreward/_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..8545ab5a0fb2e0328d8d9a1d921d46b6f65d5446 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/openreward/_spec.py @@ -0,0 +1,359 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""User-facing spec object for the OpenReward × TRL integration. + +The user constructs **one** ``OpenRewardSpec`` (a thin specification holding the env target + a few options) and reads +three properties off of it — ``.train_dataset``, ``.environment_factory``, ``.reward_funcs`` — each of which plugs +directly into the matching ``GRPOTrainer`` kwarg: + +```python +>>> from trl import GRPOConfig, GRPOTrainer +>>> from trl.experimental.openreward import OpenRewardSpec + +>>> spec = OpenRewardSpec("Eigent/SETA", num_tasks=64) + +>>> trainer = GRPOTrainer( +... model="Qwen/Qwen3-4B", +... args=GRPOConfig(num_generations=2, max_steps=5, max_tool_calling_iterations=20), +... train_dataset=spec.train_dataset, +... environment_factory=spec.environment_factory, +... reward_funcs=spec.reward_funcs, +... ) +>>> trainer.train() +``` + +Backed by the official ``openreward`` SDK (lazy-imported); install with ``pip install trl[openreward]``. +""" + +from __future__ import annotations + +import logging +import os +from collections.abc import Callable +from functools import cached_property +from typing import Any + +from .environment import _import_openreward, _RolloutEnvironment, _spec_to_dict + + +logger = logging.getLogger(__name__) + + +def _tool_specs_from_session_list_tools(out: Any) -> list[Any]: + """Normalise ``session.list_tools()`` / ``environment.list_tools()`` to a flat list. + + The client SDK (``openreward.api``) returns ``list[ToolSpec]`` directly. + """ + return list(out) + + +def _to_spec(task) -> dict[str, Any]: + """Normalise an SDK ``Task`` (or already-a-dict) to its task_spec dict.""" + if isinstance(task, dict): + return task + return task.task_spec + + +def _outcome_only_reward_func(environments, **_): + """Default reward function: last non-null reward in each rollout's trajectory. + + Suitable for sparse-outcome envs (e.g. SETA, where only `submit_solution` returns a non-null reward). Override by + passing a different callable to ``reward_funcs=``. + """ + return [env.reward for env in environments] + + +class OpenRewardSpec: + """Single spec object that wires an ORS environment into a TRL trainer. + + Args: + target (`str`): + Either an openreward.ai catalog name (`"Eigent/SETA"`) or a URL pointing at any ORS server + (`"https://you-seta.hf.space"`, `"http://localhost:8080"`). Auto-detected by the presence of `://` in the + string. + num_tasks (`int`, *optional*): + Cap on the number of tasks pulled into the dataset. ``None`` uses every task the env exposes. + split (`str`, *optional*, defaults to `"train"`): + Which split's task list to draw from. + indices (`list[int]`, *optional*): + Specific task indices to train on. Mutually exclusive with ``num_tasks``. Useful for debugging or + curriculum subsets. + api_key (`str`, *optional*): + ``OPENREWARD_API_KEY`` override. Only used when ``target`` is a catalog name. + secrets (`dict[str, str]`, *optional*): + Per-session secrets forwarded to ``env.session(secrets=)``. + env_name (`str`, *optional*): + Override for the env name to look up on the server. Rarely needed. + include_metadata (`bool`, *optional*, defaults to `True`): + Fold per-task metadata (`difficulty`, `category`, `tags`, ...) into the dataset rows so reward funcs can + read them via TRL's ``inputs`` argument. + discover_task_tools (`bool`, *optional*, defaults to `True`): + If ``True``, opens a short-lived ORS session and uses ``session.list_tools()`` so task-specific tools + (``GET …/task_tools`` per ORS — e.g. ``@tool(shared=False)`` and ``list_task_tools()``) are bound for GRPO. + If probe fails, falls back to ``environment.list_tools()`` only. Set ``False`` to skip the extra session + (shared tools only / offline quirks). + task_tools_discovery_index (`int`, *optional*): + Task index used only for the discovery session when set; **overrides** multi-index probing below. When + omitted and ``indices=`` is set, discovery opens one probe session per **distinct** entry in ``indices`` + (sorted) and **merges** tool specs by name so task-specific tools from every listed task are bound. When + omitted and ``num_tasks`` / full-list mode is used, probes task ``0`` only. Ignored when + ``discover_task_tools=False``. + """ + + def __init__( + self, + target: str, + *, + num_tasks: int | None = None, + split: str = "train", + indices: list[int] | None = None, + api_key: str | None = None, + secrets: dict[str, str] | None = None, + env_name: str | None = None, + include_metadata: bool = True, + discover_task_tools: bool = True, + task_tools_discovery_index: int | None = None, + ) -> None: + if num_tasks is not None and indices is not None: + raise ValueError("Provide num_tasks or indices, not both.") + + self._target = target + self._is_url = "://" in target + self._num_tasks = num_tasks + self._split = split + self._indices = indices + self._api_key = api_key + self._secrets = secrets + self._env_name = env_name + self._include_metadata = include_metadata + self._discover_task_tools = discover_task_tools + self._task_tools_discovery_index = task_tools_discovery_index + + # ── public surface ────────────────────────────────────────────── + + @cached_property + def train_dataset(self): + """A `datasets.Dataset` derived from the env's task list. + + Plugs directly into TRL's ``train_dataset=`` slot. Built lazily on first access. Has at minimum: + - `prompt`: empty user message (TRL appends the env's prompt). + - `task_index`: int passed to the adapter's `reset()`. + - per-task metadata columns (when `include_metadata=True`). + """ + from datasets import Dataset + + env = self._sdk_env + + # When the user asked for a specific subset (`num_tasks` cap or + # explicit `indices`), fetch only those — `list_tasks` returns + # the whole split (1376 entries for SETA, etc.) and is slow on + # the platform. Per-index `get_task` is fast and cheap. + if self._indices is not None: + indexes = list(self._indices) + task_specs = [_to_spec(env.get_task(self._split, i)) for i in indexes] + elif self._num_tasks is not None: + n_total = env.num_tasks(self._split) + n = min(self._num_tasks, n_total) + indexes = list(range(n)) + task_specs = [_to_spec(env.get_task(self._split, i)) for i in indexes] + else: + # No cap — fetch everything in one shot. + try: + tasks = env.list_tasks(self._split) + except Exception: # noqa: BLE001 + n = env.num_tasks(self._split) + tasks = [env.get_task(self._split, i) for i in range(n)] + task_specs = [_to_spec(t) for t in tasks] + indexes = list(range(len(task_specs))) + + rows: dict[str, list[Any]] = { + "prompt": [[{"role": "user", "content": ""}] for _ in indexes], + "task_index": indexes, + } + + if self._include_metadata and task_specs: + metadata_keys: set[str] = set() + for spec in task_specs: + if isinstance(spec, dict): + metadata_keys.update(spec.keys()) + # Never let a task-spec key overwrite our reserved row columns + # (e.g. an env that exposes a `prompt` task-spec field would + # otherwise replace our chat-format prompt with a raw string). + metadata_keys -= rows.keys() + for key in sorted(metadata_keys): + rows[key] = [s.get(key) if isinstance(s, dict) else None for s in task_specs] + + return Dataset.from_dict(rows) + + @cached_property + def environment_factory(self) -> Callable[[], _RolloutEnvironment]: + """Zero-arg callable that returns a fresh ``_RolloutEnvironment``. + + Plugs directly into TRL's ``environment_factory=`` slot. TRL calls this once per rollout at trainer + construction time, so each rollout has an isolated ORS session. Reuses the spec's already-discovered SDK env + + tool specs to skip per-env HTTP at trainer init. + """ + # Pre-fetch tool specs once at the spec level. ORS exposes shared tools on GET /tools and the full + # shared+task-specific set on GET /task_tools (session-scoped). GRPO inspects methods before reset(), so we + # must bind every tool the episode will see — use session.list_tools() when discover_task_tools=True. + env = self._sdk_env + tool_specs = self._discovered_tool_specs(env) + client = self._sdk_client + + # Each spec gets its own `_RolloutEnvironment` subclass so two specs + # for different envs (different tool sets) never clobber each other's + # bound methods on the shared parent class. + rollout_cls = type(f"_RolloutEnvironment_{id(self):x}", (_RolloutEnvironment,), {}) + + kwargs = { + "split": self._split, + "secrets": self._effective_secrets(), + "env_name": self._env_name, + "_client": client, + "_env": env, + "_tool_specs": tool_specs, + } + if self._is_url: + kwargs["base_url"] = self._target + else: + kwargs["name"] = self._target + if self._api_key: + kwargs["api_key"] = self._api_key + + kwargs = {k: v for k, v in kwargs.items() if v is not None} + + def _make() -> _RolloutEnvironment: + return rollout_cls(**kwargs) + + return _make + + @property + def reward_funcs(self) -> Callable[..., list[float]]: + """Default outcome-only reward function (last non-null reward per rollout). + + Plugs directly into TRL's ``reward_funcs=`` slot. Stable identity — module-level function, picklable for + multi-process workers. + """ + return _outcome_only_reward_func + + # ── internals ─────────────────────────────────────────────────── + + def _effective_secrets(self) -> dict[str, str] | None: + """Auto-forward ``OPENREWARD_API_KEY`` as the conventional ``api_key`` + per-session secret on platform mode (most envs need it).""" + if self._secrets is not None or self._is_url: + return self._secrets + key = self._api_key or os.environ.get("OPENREWARD_API_KEY") + return {"api_key": key} if key else None + + def _task_tools_probe_indices(self) -> list[int]: + """Pick task indices for ``session.list_tools()`` discovery (ORS ``/task_tools``).""" + if self._task_tools_discovery_index is not None: + return [self._task_tools_discovery_index] + if self._indices is not None: + return sorted(set(self._indices)) + return [0] + + def _discovered_tool_specs(self, env): + """Return ToolSpec list for binding on `_RolloutEnvironment`. + + Prefer ``session.list_tools()`` (ORS ``/task_tools``) so task-specific tools match what the OpenReward SDK + exposes during rollouts. Fall back to ``environment.list_tools()`` on failure or when disabled. + """ + shared = env.list_tools() + shared = _tool_specs_from_session_list_tools(shared) + if not self._discover_task_tools: + return shared + + try: + n = env.num_tasks(self._split) + except Exception as e: # noqa: BLE001 + logger.warning("OpenRewardSpec: num_tasks failed (%s); using shared tools only.", e) + return shared + + if n <= 0: + return shared + + probe_indices = self._task_tools_probe_indices() + bad = [idx for idx in probe_indices if idx < 0 or idx >= n] + if bad: + logger.warning( + "OpenRewardSpec: task tool probe index(es) %s out of range for split=%r (num_tasks=%s); ignoring them.", + bad, + self._split, + n, + ) + probe_indices = [idx for idx in probe_indices if 0 <= idx < n] + if not probe_indices: + logger.warning("OpenRewardSpec: no valid task indices for tool discovery; using shared tools only.") + return shared + + secrets = self._effective_secrets() + merged: list[Any] = [] + seen: dict[str, Any] = {} + any_probe_ok = False + + for idx in probe_indices: + try: + with env.session(split=self._split, index=idx, secrets=secrets) as sess: + specs = _tool_specs_from_session_list_tools(sess.list_tools()) + except Exception as e: # noqa: BLE001 + logger.warning( + "OpenRewardSpec: session tool discovery failed for task_index=%s (%s); skipping.", + idx, + e, + ) + continue + any_probe_ok = True + for spec in specs: + d = _spec_to_dict(spec) + name = d["name"] + if name not in seen: + seen[name] = spec + merged.append(spec) + elif _spec_to_dict(seen[name]) != d: + logger.warning( + "OpenRewardSpec: tool %r has differing schemas across probe tasks; keeping first.", + name, + ) + + if not any_probe_ok: + logger.warning("OpenRewardSpec: all task tool probes failed; using shared tools only.") + return shared + return merged + + @cached_property + def _sdk_client(self): + """The shared ``openreward.OpenReward`` client used by `dataset` and `factory`.""" + openreward = _import_openreward() + kwargs: dict[str, Any] = {} + if self._api_key: + kwargs["api_key"] = self._api_key + elif not self._is_url and "OPENREWARD_API_KEY" in os.environ: + kwargs["api_key"] = os.environ["OPENREWARD_API_KEY"] + if self._is_url: + kwargs["base_url"] = self._target + return openreward.OpenReward(**kwargs) + + @cached_property + def _sdk_env(self): + """The shared SDK ``Environment`` handle.""" + if self._is_url: + # Self-hosted single-env URL — pass any name; the SDK redirects. + # Fallback to "env" matches `_RolloutEnvironment.__init__`. + target = self._env_name or "env" + else: + target = self._target + return self._sdk_client.environments.get(target) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/openreward/environment.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/openreward/environment.py new file mode 100644 index 0000000000000000000000000000000000000000..7b969ee1c2c0b2a9ebacd6bb62f00d0ebff74fff --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/openreward/environment.py @@ -0,0 +1,404 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""TRL `environment_factory` adapter for any ORS-compliant server. + +Wraps the official ``openreward`` SDK so platform quirks (X-Secrets encoding, ephemeral session for discovery, +sticky-routing subdomain, SSE chunk reassembly, ping keepalive, …) are handled by code that ships with the spec. Our +job is only to expose the SDK's per-rollout session as a TRL-compatible class with dynamically-bound tool methods. + +Install: ``pip install trl[openreward]``. +""" + +from __future__ import annotations + +import logging +import os +import re +from typing import Any + + +logger = logging.getLogger(__name__) + + +def _import_openreward(): + """Lazy-import the openreward package with a friendly error message.""" + try: + import openreward + + return openreward + except ImportError as e: + raise ImportError( + "trl.experimental.openreward requires the `openreward` package. " + "Install with `pip install trl[openreward]`." + ) from e + + +# ── JSON Schema → Python type mapping (used by dynamic tool binding) ── + +_JSON_TYPE_TO_PY: dict[str, str] = { + "string": "str", + "integer": "int", + "number": "float", + "boolean": "bool", + "array": "list", + "object": "dict", +} + +_PY_TYPE_OBJECTS: dict[str, type] = { + "str": str, + "int": int, + "float": float, + "bool": bool, + "list": list, + "dict": dict, +} + +_PY_TYPE_FROM_VALUE: dict[type, str] = { + bool: "bool", + int: "int", + float: "float", + str: "str", + list: "list", + dict: "dict", +} + + +def _resolve_param_type(pdef: dict[str, Any]) -> str: + """Pick the best Python type name for one JSON-Schema property. + + Handles primitive ``"type"``, Pydantic's ``anyOf``/``oneOf`` form for ``Optional[T]``, and falls back to the type + of ``default``. Critical because transformers' tool-schema generator uses our Python annotations to build the + schema the model sees. + """ + t = pdef.get("type") + if isinstance(t, str) and t in _JSON_TYPE_TO_PY: + return _JSON_TYPE_TO_PY[t] + for key in ("anyOf", "oneOf"): + for opt in pdef.get(key) or []: + if isinstance(opt, dict): + inner = opt.get("type") + if isinstance(inner, str) and inner in _JSON_TYPE_TO_PY and inner != "null": + return _JSON_TYPE_TO_PY[inner] + if "default" in pdef and pdef["default"] is not None: + for value_type, name in _PY_TYPE_FROM_VALUE.items(): + if isinstance(pdef["default"], value_type): + return name + return "str" + + +# ──────────────────────────────────────────────────────────────────── + + +class _RolloutEnvironment: + """Per-rollout TRL adapter backed by the ``openreward`` SDK. + + **Internal class.** Users don't construct this directly; they create an :class:`OpenRewardSpec` and pass + ``spec.environment_factory`` to ``GRPOTrainer``. TRL's trainer then constructs one instance of this per rollout + slot. + + The tool surface is built once at construction by reading the env's tools and binding one Python method per ORS + tool — so swapping the URL or env name is the only thing needed to train against a different environment. + + Args: + name (`str`, *optional*): + openreward.ai catalog name (e.g. ``"Eigent/SETA"``). Mutually exclusive with `base_url`. Requires + ``OPENREWARD_API_KEY`` (env var or `api_key=`). + base_url (`str`, *optional*): + Direct URL of an ORS server (HF Space, local Docker, etc.). Mutually exclusive with `name`. + env_name (`str`, *optional*): + Name to look up on the server. Defaults to the canonical name parsed from `name`/`base_url`. + split (`str`, *optional*, defaults to `"train"`): + Split passed to ``env.session(split=, index=)``. + api_key (`str`, *optional*): + Override for ``OPENREWARD_API_KEY``. Only used with `name=`. + secrets (`dict[str, str]`, *optional*): + Per-session secrets. Forwarded to ``env.session(secrets=)``; the SDK encodes them and adds platform-domain + entries. + timeout (`float`, *optional*): + Reserved for future use. The SDK manages its own timeouts. + + Attributes: + reward (`float`): + Last non-null reward in the trajectory (outcome-only convention). + rewards (`list[float | None]`): + Per-step reward sequence in tool-call order. + metadata (`list[dict | None]`): + Per-step ``ToolOutput.metadata`` dicts. + finished (`bool`): + True after a tool returned ``finished: true``. + last_output (`str`): + Joined text of the most recent tool result. + """ + + def __init__( + self, + *, + name: str | None = None, + base_url: str | None = None, + env_name: str | None = None, + split: str = "train", + api_key: str | None = None, + secrets: dict[str, str] | None = None, + timeout: float | None = None, + _client: Any = None, + _env: Any = None, + _tool_specs: list[Any] | None = None, + ) -> None: + if (name is None) == (base_url is None): + raise ValueError("Provide exactly one of: name, base_url.") + + # Reuse a pre-built client/env when the spec has already discovered + # them (saves N HTTP calls at trainer init); otherwise build fresh. + if _client is None: + openreward = _import_openreward() + client_kwargs: dict[str, Any] = {} + if api_key: + client_kwargs["api_key"] = api_key + elif name and "OPENREWARD_API_KEY" in os.environ: + client_kwargs["api_key"] = os.environ["OPENREWARD_API_KEY"] + if base_url: + client_kwargs["base_url"] = base_url + self._client = openreward.OpenReward(**client_kwargs) + else: + self._client = _client + + if _env is None: + target = name if name is not None else env_name or "" + if base_url and not target: + # Self-hosted single-env URL — pass any name; SDK redirects. + target = "env" + self._env = self._client.environments.get(target) + else: + self._env = _env + + self._split = split + self._secrets = secrets + self._session_cm = None # the SDK context manager itself, retained for clean teardown + self._session = None # the entered Session object + + # Episode state — read by the trainer's reward_func. + self.reward: float = 0.0 + self.rewards: list[float | None] = [] + self.metadata: list[dict[str, Any] | None] = [] + self.finished: bool = False + self.last_output: str = "" + + # Bind one Python method per server-side tool. Pre-fetched specs + # come from the spec object; otherwise we ask the SDK ourselves. + specs = _tool_specs if _tool_specs is not None else self._env.list_tools() + for spec in specs: + _bind_tool_method(self.__class__, _spec_to_dict(spec)) + + # ── TRL contract ───────────────────────────────────────────────── + + def reset( + self, + *, + task_index: int = 0, + task_spec: dict[str, Any] | None = None, + **_: Any, + ) -> str: + """Open a fresh ORS session for this rollout. + + Closes any prior session, starts a new one via the SDK's ``env.session(...)`` context manager, fetches the + prompt, and returns its text (which TRL appends to the user message). + """ + self._teardown_session() + self.reward = 0.0 + self.rewards = [] + self.metadata = [] + self.finished = False + self.last_output = "" + + if task_spec is not None: + from openreward.api.environments.client import Task + + task = Task( + server_name=self._env.server, + environment_name=self._env.name, + task_spec=task_spec, + namespace=self._env.namespace, + ) + cm = self._env.session(task=task, secrets=self._secrets) + else: + cm = self._env.session(split=self._split, index=int(task_index), secrets=self._secrets) + + # Retain the context manager itself so `_teardown_session` can call + # its __exit__; calling __exit__ on the entered Session alone leaves + # the CM's exit logic (which deletes the env state + sid) unrun. + self._session_cm = cm + self._session = cm.__enter__() + prompt = self._session.get_prompt() + return _join_text_blocks(prompt) + + # Leading underscore so TRL's tool collector at grpo_trainer.py:502-506 + # excludes this from the model's tool surface. + def _close(self) -> None: + """Tear down the active session (best-effort).""" + self._teardown_session() + + # ── helpers ────────────────────────────────────────────────────── + + def _teardown_session(self) -> None: + if self._session_cm is None: + return + try: + # Exit the SDK's Session context manager — this deletes both + # the per-rollout env state and the sid on the server. + self._session_cm.__exit__(None, None, None) + except Exception as e: # noqa: BLE001 + logger.debug("session teardown failed: %s", e) + self._session_cm = None + self._session = None + + def _call_ors_tool(self, tool_name: str, tool_input: dict[str, Any]) -> str: + """Invoke a server-side tool and update episode state.""" + if self._session is None: + raise RuntimeError("Cannot call a tool before reset() opens a session.") + + try: + out = self._session.call_tool(tool_name, tool_input) + except Exception as e: # noqa: BLE001 + self.rewards.append(None) + self.metadata.append(None) + self.last_output = f"Error: {e}" + return self.last_output + + # `out` is `openreward.api.environments.types.ToolOutput` — a stable dataclass + # with `blocks: list`, `reward: Optional[float]`, `metadata: Optional[dict]`, `finished: bool`. + text = _join_text_blocks(out.blocks or []) or "(no output)" + + step_reward: float | None = None + if out.reward is not None: + try: + step_reward = float(out.reward) + except (TypeError, ValueError): + step_reward = None + self.rewards.append(step_reward) + if step_reward is not None: + self.reward = step_reward # last-non-null wins (outcome-only convention) + + self.metadata.append(out.metadata if isinstance(out.metadata, dict) else None) + self.finished = bool(out.finished) + self.last_output = text + return text + + +# ── dynamic tool binding ───────────────────────────────────────────── + + +_VALID_TOOL_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") + + +def _bind_tool_method(cls: type, spec: dict[str, Any]) -> None: + """Generate a typed Python method for one ORS tool spec. + + Signature comes from the JSON Schema; docstring is Google-style so ``transformers.utils.get_json_schema`` (used by + vLLM) can produce a correct tool schema for the model. + + Untrusted text from the server (tool name, descriptions) is never spliced raw into the generated source — the name + is validated against a Python-identifier regex and the description / per-param descriptions are passed through + ``repr()`` before being interpolated, so a tool description containing triple quotes can't break binding. + """ + tool_name = spec["name"] + if not _VALID_TOOL_NAME.match(tool_name): + logger.warning("skipping tool with non-identifier name: %r", tool_name) + return + if tool_name in cls.__dict__: + # Already bound by an earlier instance — idempotent skip. + return + + description = spec.get("description") or f"Call the {tool_name} tool." + schema = spec.get("input_schema") or {} + properties: dict[str, dict[str, Any]] = schema.get("properties") or {} + required: set[str] = set(schema.get("required") or []) + + # Required params must come before optional ones in Python — sort. + required_props = [(n, p) for n, p in properties.items() if n in required] + optional_props = [(n, p) for n, p in properties.items() if n not in required] + + params_src: list[str] = [] + annotations: dict[str, type] = {} + args_doc_lines: list[str] = [] + for pname, pdef in required_props + optional_props: + if not _VALID_TOOL_NAME.match(pname): + logger.warning("skipping tool %r — non-identifier param name: %r", tool_name, pname) + return + py_type = _resolve_param_type(pdef) + annotations[pname] = _PY_TYPE_OBJECTS[py_type] + if pname in required: + params_src.append(f"{pname}: {py_type}") + else: + default = pdef.get("default", None) + params_src.append(f"{pname}: {py_type} = {default!r}") + pdesc = pdef.get("description") or pdef.get("title") or pname + args_doc_lines.append(f" {pname}: {pdesc}") + + # Build the docstring as a single repr-quoted string so triple-quotes / quotes / newlines in the description or + # arg text can never close out the generated docstring early. + docstring = description + (("\n\n Args:\n" + "\n".join(args_doc_lines)) if args_doc_lines else "") + src = ( + f"def {tool_name}(self, {', '.join(params_src)}) -> str:\n" + f" {docstring!r}\n" + f" _kwargs = dict(locals()); _kwargs.pop('self', None)\n" + f" return self._call_ors_tool({tool_name!r}, _kwargs)\n" + ) + ns: dict[str, Any] = {} + exec(src, ns) + fn = ns[tool_name] + fn.__qualname__ = f"{cls.__name__}.{tool_name}" + fn.__annotations__ = {**annotations, "return": str} + setattr(cls, tool_name, fn) + + +# ── small utilities ────────────────────────────────────────────────── + + +def _spec_to_dict(spec: Any) -> dict[str, Any]: + """Normalise SDK ``ToolSpec`` and dict shapes to the same dict form. + + ``openreward.api.environments.types.ToolSpec`` is a stable dataclass with ``name``, ``description``, + ``input_schema`` fields, so direct attribute access is safe. + """ + if isinstance(spec, dict): + return spec + return { + "name": spec.name, + "description": spec.description, + "input_schema": spec.input_schema or {}, + } + + +def _join_text_blocks(blocks: list[Any]) -> str: + """Concatenate the ``text`` field of every text block in order. + + Accepts both SDK ``TextBlock`` dataclasses and plain dicts. Both shapes expose a ``type`` discriminator (`"text"` + vs `"image"`); non-text blocks are skipped so e.g. ``ImageBlock`` doesn't trip up the join. + """ + if not blocks: + return "" + parts: list[str] = [] + for b in blocks: + if isinstance(b, dict): + if b.get("type") != "text": + continue + text = b.get("text") + else: + if b.type != "text": + continue + text = b.text + if text: + parts.append(str(text)) + return "\n".join(parts) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/orpo/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/orpo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..88abd9e1826eae8a0d201b84a048614059b9e264 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/orpo/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .orpo_config import ORPOConfig +from .orpo_trainer import ORPOTrainer + + +__all__ = ["ORPOConfig", "ORPOTrainer"] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/orpo/orpo_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/orpo/orpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..78c98788824b7ce4fbfb8676dcb6fd89e488de2a --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/orpo/orpo_config.py @@ -0,0 +1,134 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class ORPOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`experimental.orpo.ORPOTrainer`]. + + This class includes only the parameters that are specific to ORPO training. For a full list of training arguments, + please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may + differ from those in [`~transformers.TrainingArguments`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + max_length (`int` or `None`, *optional*, defaults to `1024`): + Maximum length of the sequences (prompt + completion) in the batch. This argument is required if you want + to use the default data collator. + max_completion_length (`int`, *optional*): + Maximum length of the completion. This argument is required if you want to use the default data collator + and your model is an encoder-decoder. + beta (`float`, *optional*, defaults to `0.1`): + Parameter controlling the relative ratio loss weight in the ORPO loss. In the + [paper](https://huggingface.co/papers/2403.07691), it is denoted by λ. In the + [code](https://github.com/xfactlab/orpo), it is denoted by `alpha`. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. + padding_value (`int`, *optional*): + Padding value to use. If `None`, the padding value of the tokenizer is used. + generate_during_eval (`bool`, *optional*, defaults to `False`): + If `True`, generates and logs completions from the model to W&B or Comet during evaluation. + is_encoder_decoder (`bool`, *optional*): + When using the `model_init` argument (callable) to instantiate the model instead of the `model` argument, + you need to specify if the model returned by the callable is an encoder-decoder model. + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a + string. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to allow loading models that ship custom Python code from the Hub. Forwarded to + [`~transformers.AutoModelForCausalLM.from_pretrained`]. + dataset_num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `1e-6` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=1e-6, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + max_length: int | None = field( + default=1024, + metadata={"help": "Maximum length of the sequences (prompt + completion) in the batch."}, + ) + max_completion_length: int | None = field( + default=None, + metadata={ + "help": "Maximum length of the completion. This argument is required if you want to use the default data " + "collator and your model is an encoder-decoder." + }, + ) + beta: float = field( + default=0.1, + metadata={ + "help": "Parameter controlling the relative ratio loss weight in the ORPO loss. In the paper, it is " + "denoted by λ." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the model."}, + ) + padding_value: int | None = field( + default=None, + metadata={"help": "Padding value to use. If `None`, the padding value of the tokenizer is used."}, + ) + generate_during_eval: bool = field( + default=False, + metadata={"help": "If `True`, generates and logs completions from the model to W&B during evaluation."}, + ) + is_encoder_decoder: bool | None = field( + default=None, + metadata={ + "help": "When using the `model_init` argument (callable) to instantiate the model instead of the `model` " + "argument, you need to specify if the model returned by the callable is an encoder-decoder model." + }, + ) + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model " + "from a string." + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": "Whether to allow loading models that ship custom Python code from the Hub. Forwarded to " + "`AutoModelForCausalLM.from_pretrained`." + }, + ) + dataset_num_proc: int | None = field( + default=None, + metadata={"help": "Number of processes to use for processing the dataset."}, + ) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/orpo/orpo_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/orpo/orpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..2208baf98e984b75b23f1f39465ed0c3ba732a83 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/orpo/orpo_trainer.py @@ -0,0 +1,1042 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import random +import textwrap +from collections import defaultdict +from collections.abc import Callable +from contextlib import nullcontext +from pathlib import Path +from typing import Any, Literal + +import numpy as np +import pandas as pd +import torch +import torch.nn as nn +import torch.nn.functional as F +import transformers +from accelerate import PartialState +from accelerate.logging import get_logger +from accelerate.utils import is_peft_model +from datasets import Dataset +from packaging.version import Version +from torch import autocast +from torch.utils.data import DataLoader +from transformers import ( + AutoModelForCausalLM, + BaseImageProcessor, + DataCollator, + FeatureExtractionMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, + is_comet_available, + is_torch_xla_available, + is_wandb_available, +) +from transformers.trainer_utils import EvalLoopOutput +from transformers.utils import is_peft_available, is_torch_fx_proxy + +from ...data_utils import maybe_apply_chat_template, maybe_extract_prompt +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import disable_dropout_in_model, log_table_to_comet_experiment, selective_log_softmax +from ..utils import ( + DPODataCollatorWithPadding, + add_bos_token_if_needed, + add_eos_token_if_needed, + pad_to_length, + peft_module_casting_to_bf16, +) +from .orpo_config import ORPOConfig + + +if is_peft_available(): + from peft import PeftConfig, get_peft_model, prepare_model_for_kbit_training + + +if is_wandb_available(): + import wandb + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + + +logger = get_logger(__name__) + + +def log1mexp(x: torch.FloatTensor) -> torch.FloatTensor: + """Numerically stable computation of log(1-exp(x)).""" + # branch at -ln 2 ~ -0.693 to avoid cancellation + t = -0.6931471805599453 + return torch.where(x < t, torch.log1p(-torch.exp(x)), torch.log(-torch.expm1(x))) + + +class ORPOTrainer(_BaseTrainer): + r""" + Initialize ORPOTrainer. + + Args: + model ([`~transformers.PreTrainedModel`]): + The model to train, preferably an [`~transformers.AutoModelForSequenceClassification`]. + args ([`experimental.orpo.ORPOConfig`]): + The ORPO config arguments to use for training. + data_collator ([`~transformers.DataCollator`]): + The data collator to use for training. If None is specified, the default data collator + ([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the + maximum length of the sequences in the batch, given a dataset of paired sequences. + train_dataset ([`~datasets.Dataset`]): + The dataset to use for training. + eval_dataset ([`~datasets.Dataset`]): + The dataset to use for evaluation. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + model_init (`Callable[[], transformers.PreTrainedModel]`): + The model initializer to use for training. If None is specified, the default model initializer will be + used. + callbacks (`list[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + peft_config ([`~peft.PeftConfig`], *optional*): + The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in + a PEFT model. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to + metric values. + """ + + _tag_names = ["trl", "orpo"] + _name = "ORPO" + _paper = { + "title": "ORPO: Monolithic Preference Optimization without Reference Model", + "id": "2403.07691", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{hong2024orpo, + title = {{ORPO: Monolithic Preference Optimization without Reference Model}}, + author = {Jiwoo Hong and Noah Lee and James Thorne}, + year = 2024, + eprint = {arXiv:2403.07691} + }"""), + } + + def __init__( + self, + model: PreTrainedModel | nn.Module | str | None = None, + args: ORPOConfig | None = None, + data_collator: DataCollator | None = None, + train_dataset: Dataset | None = None, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + processing_class: PreTrainedTokenizerBase + | BaseImageProcessor + | FeatureExtractionMixin + | ProcessorMixin + | None = None, + model_init: Callable[[], PreTrainedModel] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + peft_config: "PeftConfig | None" = None, + compute_metrics: Callable[[EvalLoopOutput], dict] | None = None, + ): + if train_dataset is None: + raise ValueError("`train_dataset` is required") + + if args.model_init_kwargs is None: + model_init_kwargs = {} + elif not isinstance(model, str): + raise ValueError("You passed model_kwargs to the ORPOTrainer. But your model is already instantiated.") + else: + model_init_kwargs = args.model_init_kwargs + dtype = model_init_kwargs.get("dtype", "auto") + if dtype is not None: + # Convert to `torch.dtype` if an str is passed + if isinstance(dtype, str) and dtype != "auto": + dtype = getattr(torch, dtype) + if dtype != "auto" and not isinstance(dtype, torch.dtype): + raise ValueError( + f"Invalid `dtype` passed to the ORPOConfig. Expected a string with either `torch.dtype` or 'auto', but got {dtype}." + ) + model_init_kwargs["dtype"] = dtype + model_init_kwargs["device_map"] = model_init_kwargs.get("device_map", "auto") + + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + + if isinstance(model, str): + model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs) + + # PEFT + # Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16` + # has been called in order to properly call autocast if needed. + self._peft_has_been_casted_to_bf16 = False + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first " + "merge and unload the existing adapter, save the resulting base model, and then pass that base " + "model along with the new `peft_config` to the trainer." + ) + + if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False): + _support_gc_kwargs = hasattr( + args, "gradient_checkpointing_kwargs" + ) and "gradient_checkpointing_kwargs" in list( + inspect.signature(prepare_model_for_kbit_training).parameters + ) + + prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing} + + if _support_gc_kwargs: + prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs + + model = prepare_model_for_kbit_training(model, **prepare_model_kwargs) + elif args.gradient_checkpointing: + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + # get peft model with the given config + model = get_peft_model(model, peft_config) + if args.bf16 and getattr(model, "is_loaded_in_4bit", False): + peft_module_casting_to_bf16(model) + # If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager + self._peft_has_been_casted_to_bf16 = True + + # For models that use gradient_checkpointing, we need to attach a hook that enables input + # to explicitly have `requires_grad=True`, otherwise training will either silently + # fail or completely fail. + elif args.gradient_checkpointing: + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + if args.generate_during_eval and not (is_wandb_available() or is_comet_available()): + raise ValueError( + "`generate_during_eval=True` requires Weights and Biases or Comet to be installed." + " Please install `wandb` or `comet-ml` to resolve." + ) + + if model is not None: + self.is_encoder_decoder = model.config.is_encoder_decoder + elif args.is_encoder_decoder is None: + raise ValueError("When no model is provided, you need to pass the parameter is_encoder_decoder.") + else: + self.is_encoder_decoder = args.is_encoder_decoder + + if self.is_encoder_decoder: + self.decoder_start_token_id = model.config.decoder_start_token_id + self.pad_token_id = model.config.pad_token_id + + if processing_class is None: + raise ValueError("processing_class must be specified to tokenize a ORPO dataset.") + if args.max_length is None: + logger.warning( + "`max_length` is not set in the ORPOConfig's init" + " it will default to `512` by default, but you should do it yourself in the future.", + ) + max_length = 512 + else: + max_length = args.max_length + + if args.max_completion_length is None and self.is_encoder_decoder: + logger.warning( + "When using an encoder decoder architecture, you should set `max_completion_length` in the ORPOConfig's init" + " it will default to `128` by default, but you should do it yourself in the future.", + ) + self.max_completion_length = 128 + else: + self.max_completion_length = args.max_completion_length + + if data_collator is None: + data_collator = DPODataCollatorWithPadding( + pad_token_id=processing_class.pad_token_id, + is_encoder_decoder=self.is_encoder_decoder, + ) + + if args.remove_unused_columns: + args.remove_unused_columns = False + # warn users + logger.warning( + "When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your TrainingArguments" + " we have set it for you, but you should do it yourself in the future.", + ) + + self.use_dpo_data_collator = True + else: + self.use_dpo_data_collator = False + + # Disable dropout in the model and reference model + if args.disable_dropout: + disable_dropout_in_model(model) + + self.max_length = max_length + self.generate_during_eval = args.generate_during_eval + self.padding_value = args.padding_value if args.padding_value is not None else processing_class.pad_token_id + self.processing_class = processing_class + + self.beta = args.beta + self.aux_loss_enabled = getattr(model.config, "output_router_logits", False) + self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0) + if self.aux_loss_enabled and self.aux_loss_coef == 0.0: + logger.warning( + "You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to " + "`0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value " + "greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary " + "loss.", + ) + + self._stored_metrics = defaultdict(lambda: defaultdict(list)) + + # Compute that only on the main process for faster data processing. + # see: https://github.com/huggingface/trl/pull/1255 + with PartialState().main_process_first(): + # Extract the prompt if needed, and apply the chat template if needed + train_dataset = train_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc) + train_dataset = train_dataset.map( + maybe_apply_chat_template, + fn_kwargs={"processing_class": processing_class}, + num_proc=args.dataset_num_proc, + ) + train_dataset = train_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc) + if eval_dataset is not None: + eval_dataset = eval_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc) + eval_dataset = eval_dataset.map( + maybe_apply_chat_template, + fn_kwargs={"processing_class": processing_class}, + num_proc=args.dataset_num_proc, + ) + eval_dataset = eval_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc) + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + model_init=model_init, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the + # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set + # self.model_accepts_loss_kwargs to False to enable scaling. + self.model_accepts_loss_kwargs = False + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + if not hasattr(self, "accelerator"): + raise AttributeError( + "Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`." + ) + + def build_tokenized_answer(self, prompt, answer): + """ + Llama tokenizer does satisfy `enc(a + b) = enc(a) + enc(b)`. It does ensure `enc(a + b) = enc(a) + enc(a + + b)[len(enc(a)):]`. Reference: + https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 + """ + + full_tokenized = self.processing_class(prompt + answer, add_special_tokens=False) + prompt_input_ids = self.processing_class(prompt, add_special_tokens=False)["input_ids"] + + answer_input_ids = full_tokenized["input_ids"][len(prompt_input_ids) :] + answer_attention_mask = full_tokenized["attention_mask"][len(prompt_input_ids) :] + + # Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]` + full_concat_input_ids = np.concatenate([prompt_input_ids, answer_input_ids]) + + # Prepare input tokens for token by token comparison + full_input_ids = np.array(full_tokenized["input_ids"]) + + if len(full_input_ids) != len(full_concat_input_ids): + raise ValueError("Prompt input ids and answer input ids should have the same length.") + + # On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens + # can be merged together when tokenizing prompt+answer. This could result + # on the last token from the prompt being different when tokenized on its own + # vs when done as prompt+answer. + response_token_ids_start_idx = len(prompt_input_ids) + + # If tokenized prompt is different than both prompt+answer, then it means the + # last token has changed due to merging. + if prompt_input_ids != full_tokenized["input_ids"][:response_token_ids_start_idx]: + response_token_ids_start_idx -= 1 + + prompt_input_ids = full_tokenized["input_ids"][:response_token_ids_start_idx] + prompt_attention_mask = full_tokenized["attention_mask"][:response_token_ids_start_idx] + + if len(prompt_input_ids) != len(prompt_attention_mask): + raise ValueError("Prompt input ids and attention mask should have the same length.") + + answer_input_ids = full_tokenized["input_ids"][response_token_ids_start_idx:] + answer_attention_mask = full_tokenized["attention_mask"][response_token_ids_start_idx:] + + return dict( + prompt_input_ids=prompt_input_ids, + prompt_attention_mask=prompt_attention_mask, + input_ids=answer_input_ids, + attention_mask=answer_attention_mask, + ) + + def tokenize_row(self, feature, model: PreTrainedModel | nn.Module | None = None) -> dict: + """Tokenize a single row from a ORPO specific dataset. + + At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt + + chosen or prompt + rejected responses is/are too long. First we truncate the prompt; if we're still too long, + we truncate the chosen/rejected. + + We also create the labels for the chosen/rejected responses, which are of length equal to the sum of the length + of the prompt and the chosen/rejected response, with `-100` for the prompt tokens. + """ + batch = {} + prompt = feature["prompt"] + chosen = feature["chosen"] + rejected = feature["rejected"] + + if not self.is_encoder_decoder: + # Check issues below for more details + # 1. https://github.com/huggingface/trl/issues/907 + # 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 + # 3. https://github.com/LianjiaTech/BELLE/issues/337 + + if not isinstance(prompt, str): + raise ValueError(f"prompt should be an str but got {type(prompt)}") + prompt_tokens = self.processing_class(prompt, add_special_tokens=False) + prompt_tokens = {f"prompt_{k}": v for k, v in prompt_tokens.items()} + + if not isinstance(chosen, str): + raise ValueError(f"chosen should be an str but got {type(chosen)}") + chosen_tokens = self.build_tokenized_answer(prompt, chosen) + + if not isinstance(rejected, str): + raise ValueError(f"rejected should be an str but got {type(rejected)}") + rejected_tokens = self.build_tokenized_answer(prompt, rejected) + + # Last prompt token might get merged by tokenizer and + # it should not be included for generation if that happens + prompt_len_input_ids = len(prompt_tokens["prompt_input_ids"]) + + chosen_prompt_len_input_ids = len(chosen_tokens["prompt_input_ids"]) + rejected_prompt_len_input_ids = len(rejected_tokens["prompt_input_ids"]) + prompt_len_input_ids = min(chosen_prompt_len_input_ids, rejected_prompt_len_input_ids) + + for k, v in prompt_tokens.items(): + prompt_tokens[k] = v[:prompt_len_input_ids] + + # Make sure prompts only have one different token at most an + # and length only differs by 1 at most + num_diff_tokens = sum( + a != b + for a, b in zip(chosen_tokens["prompt_input_ids"], rejected_tokens["prompt_input_ids"], strict=False) + ) + num_diff_len = abs(chosen_prompt_len_input_ids - rejected_prompt_len_input_ids) + if num_diff_tokens > 1 or num_diff_len > 1: + raise ValueError( + "Chosen and rejected prompt_input_ids might only differ on the " + "last token due to tokenizer merge ops." + ) + + # add BOS token to head of prompt. Avoid adding if it's already there + prompt_tokens, chosen_tokens, rejected_tokens = add_bos_token_if_needed( + self.processing_class.bos_token_id, + prompt_len_input_ids, + prompt_tokens, + chosen_prompt_len_input_ids, + chosen_tokens, + rejected_prompt_len_input_ids, + rejected_tokens, + ) + + # add EOS token to end of answer. Avoid adding if it's already there + chosen_tokens, rejected_tokens = add_eos_token_if_needed( + self.processing_class.eos_token_id, chosen_tokens, rejected_tokens + ) + + longer_response_length = max(len(chosen_tokens["input_ids"]), len(rejected_tokens["input_ids"])) + + # if combined sequence is too long, truncate the response + for answer_tokens in [chosen_tokens, rejected_tokens]: + if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length: + for k in ["input_ids", "attention_mask"]: + answer_tokens[k] = answer_tokens[k][: self.max_length - longer_response_length] + + # Create labels + chosen_sequence_tokens = { + k: chosen_tokens[f"prompt_{k}"] + chosen_tokens[k] for k in ["input_ids", "attention_mask"] + } + rejected_sequence_tokens = { + k: rejected_tokens[f"prompt_{k}"] + rejected_tokens[k] for k in ["input_ids", "attention_mask"] + } + chosen_sequence_tokens["labels"] = chosen_sequence_tokens["input_ids"][:] + chosen_sequence_tokens["labels"][: len(chosen_tokens["prompt_input_ids"])] = [-100] * len( + chosen_tokens["prompt_input_ids"] + ) + rejected_sequence_tokens["labels"] = rejected_sequence_tokens["input_ids"][:] + rejected_sequence_tokens["labels"][: len(rejected_tokens["prompt_input_ids"])] = [-100] * len( + rejected_tokens["prompt_input_ids"] + ) + + for k, toks in { + "chosen_": chosen_sequence_tokens, + "rejected_": rejected_sequence_tokens, + "": prompt_tokens, + }.items(): + for type_key, tokens in toks.items(): + if type_key == "token_type_ids": + continue + batch[f"{k}{type_key}"] = tokens + + else: + chosen_tokens = self.processing_class( + chosen, truncation=True, max_length=self.max_completion_length, add_special_tokens=True + ) + rejected_tokens = self.processing_class( + rejected, truncation=True, max_length=self.max_completion_length, add_special_tokens=True + ) + prompt_tokens = self.processing_class(prompt, add_special_tokens=True) + + batch["chosen_labels"] = chosen_tokens["input_ids"] + batch["rejected_labels"] = rejected_tokens["input_ids"] + batch["prompt_input_ids"] = prompt_tokens["input_ids"] + batch["prompt_attention_mask"] = prompt_tokens["attention_mask"] + + if model is not None and hasattr(model, "prepare_decoder_input_ids_from_labels"): + batch["rejected_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels( + labels=torch.tensor(batch["rejected_labels"]) + ) + batch["chosen_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels( + labels=torch.tensor(batch["chosen_labels"]) + ) + + if is_torch_xla_available(): + # Pad the sequences to global max_length to avoid TorchXLA recompilation + for k in batch: + if "labels" in k or self.is_encoder_decoder: + pad_value = -100 + elif k.endswith("_input_ids"): + pad_value = self.padding_value + elif k.endswith("_attention_mask"): + pad_value = 0 + batch[k] = batch[k] + [pad_value] * (self.max_length - len(batch[k])) + return batch + + @staticmethod + def concatenated_inputs( + batch: dict[str, list | torch.LongTensor], + is_encoder_decoder: bool = False, + padding_value: int = 0, + device: torch.device | None = None, + ) -> dict[str, torch.LongTensor]: + """Concatenate the chosen and rejected inputs into a single tensor. + + Args: + batch: + A batch of data. Must contain the keys 'chosen_input_ids' and 'rejected_input_ids', which are tensors + of shape (batch_size, sequence_length). + is_encoder_decoder: + Whether the model is an encoder-decoder model. + padding_value: + The padding value to use for the concatenated inputs_ids. + device: + The device for the concatenated inputs. + + Returns: + A dictionary containing the concatenated inputs under the key 'concatenated_input_ids'. + """ + concatenated_batch = {} + + if is_encoder_decoder: + max_length = max(batch["chosen_labels"].shape[1], batch["rejected_labels"].shape[1]) + else: + max_length = max(batch["chosen_input_ids"].shape[1], batch["rejected_input_ids"].shape[1]) + + for k in batch: + if k.startswith("chosen") and isinstance(batch[k], torch.Tensor): + if "labels" in k or is_encoder_decoder: + pad_value = -100 + elif k.endswith("_input_ids"): + pad_value = padding_value + elif k.endswith("_attention_mask"): + pad_value = 0 + concatenated_key = k.replace("chosen", "concatenated") + concatenated_batch[concatenated_key] = pad_to_length(batch[k], max_length, pad_value=pad_value) + for k in batch: + if k.startswith("rejected") and isinstance(batch[k], torch.Tensor): + if "labels" in k or is_encoder_decoder: + pad_value = -100 + elif k.endswith("_input_ids"): + pad_value = padding_value + elif k.endswith("_attention_mask"): + pad_value = 0 + concatenated_key = k.replace("rejected", "concatenated") + concatenated_batch[concatenated_key] = torch.cat( + ( + concatenated_batch[concatenated_key], + pad_to_length(batch[k], max_length, pad_value=pad_value), + ), + dim=0, + ).to(device=device) + + if is_encoder_decoder: + concatenated_batch["concatenated_input_ids"] = batch["prompt_input_ids"].repeat(2, 1).to(device=device) + concatenated_batch["concatenated_attention_mask"] = ( + batch["prompt_attention_mask"].repeat(2, 1).to(device=device) + ) + + return concatenated_batch + + def odds_ratio_loss( + self, + policy_chosen_logps: torch.FloatTensor, + policy_rejected_logps: torch.FloatTensor, + ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + """Compute ORPO's odds ratio (OR) loss for a batch of policy and reference model log probabilities. + + Args: + policy_chosen_logps: + Log probabilities of the policy model for the chosen responses. Shape: (batch_size,) + policy_rejected_logps: + Log probabilities of the policy model for the rejected responses. Shape: (batch_size,) + + Returns: + A tuple of three tensors: (losses, chosen_rewards, rejected_rewards). The losses tensor contains the ORPO + loss for each example in the batch. The chosen_rewards and rejected_rewards tensors contain the rewards for + the chosen and rejected responses, respectively. The log odds ratio of the chosen responses over the + rejected responses ratio for logging purposes. The `log(sigmoid(log_odds_chosen))` for logging purposes. + """ + + # Derived from Eqs. (4) and (7) from https://huggingface.co/papers/2403.07691 by using log identities and exp(log(P(y|x)) = P(y|x) + policy_chosen_logps = policy_chosen_logps.float() + policy_rejected_logps = policy_rejected_logps.float() + log_odds = (policy_chosen_logps - policy_rejected_logps) - ( + log1mexp(policy_chosen_logps) - log1mexp(policy_rejected_logps) + ) + ratio = F.logsigmoid(log_odds) + losses = self.beta * ratio + + chosen_rewards = self.beta * (policy_chosen_logps.to(self.accelerator.device)).detach() + rejected_rewards = self.beta * (policy_rejected_logps.to(self.accelerator.device)).detach() + + return losses, chosen_rewards, rejected_rewards, torch.mean(ratio), torch.mean(log_odds) + + @staticmethod + def get_batch_logps( + logits: torch.FloatTensor, + labels: torch.LongTensor, + average_log_prob: bool = False, + is_encoder_decoder: bool = False, + ) -> torch.FloatTensor: + """Compute the log probabilities of the given labels under the given logits. + + Args: + logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size) + labels: + Labels for which to compute the log probabilities. Label tokens with a value of `-100` are ignored. + Shape: (batch_size, sequence_length) + average_log_prob: + If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the + log probabilities of the (non-masked) tokens. + is_encoder_decoder: Whether the model is an encoder-decoder model. + + Returns: + A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the + given logits. + """ + if logits.shape[:-1] != labels.shape: + raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.") + + if not is_encoder_decoder: + labels = labels[:, 1:].clone() + logits = logits[:, :-1, :] + loss_mask = labels != -100 + + # dummy token; we'll ignore the losses on these tokens later + labels = torch.where(labels == -100, 0, labels) + + per_token_logps = selective_log_softmax(logits, labels) + + if average_log_prob: + return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1) + else: + return (per_token_logps * loss_mask).sum(-1) + + def concatenated_forward( + self, model: nn.Module, batch: dict[str, list | torch.LongTensor] + ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + """Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together. + + We do this to avoid doing two forward passes, because it's faster for FSDP. + """ + concatenated_batch = self.concatenated_inputs( + batch, + is_encoder_decoder=self.is_encoder_decoder, + padding_value=self.padding_value, + device=self.accelerator.device, + ) + len_chosen = batch["chosen_labels"].shape[0] + + model_kwargs = ( + { + "decoder_input_ids": self._shift_right(concatenated_batch["concatenated_labels"]), + } + if self.is_encoder_decoder + else {} + ) + + if self.aux_loss_enabled: + model_kwargs["output_router_logits"] = True + + outputs = model( + concatenated_batch["concatenated_input_ids"], + attention_mask=concatenated_batch["concatenated_attention_mask"], + use_cache=False, + **model_kwargs, + ) + all_logits = outputs.logits + + def cross_entropy_loss(logits, labels): + if not self.is_encoder_decoder: + # Shift so that tokens < n predict n + logits = logits[..., :-1, :].contiguous() + labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = nn.CrossEntropyLoss() + logits = logits.view(-1, logits.shape[-1]) + labels = labels.view(-1) + # Enable model parallelism + labels = labels.to(logits.device) + loss = loss_fct(logits, labels) + return loss + + if self.is_encoder_decoder: + labels = concatenated_batch["concatenated_labels"].clone() + else: + labels = concatenated_batch["concatenated_input_ids"].clone() + attention_mask = concatenated_batch["concatenated_attention_mask"] + labels = torch.where(attention_mask == 1, labels, -100) + # orpo chosen nll loss is computed over the full prompt and response + chosen_nll_loss = cross_entropy_loss(all_logits[:len_chosen], labels[:len_chosen]) + + all_logps = self.get_batch_logps( + all_logits, + concatenated_batch["concatenated_labels"], + average_log_prob=True, + is_encoder_decoder=self.is_encoder_decoder, + ) + + chosen_logps = all_logps[:len_chosen] + rejected_logps = all_logps[len_chosen:] + + if not self.is_encoder_decoder: + chosen_logits = all_logits[:len_chosen, :-1, :] + rejected_logits = all_logits[len_chosen:, :-1, :] + else: + chosen_logits = all_logits[:len_chosen] + rejected_logits = all_logits[len_chosen:] + + if self.aux_loss_enabled: + return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, chosen_nll_loss, outputs.aux_loss) + + return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, chosen_nll_loss) + + def get_batch_loss_metrics( + self, + model, + batch: dict[str, list | torch.LongTensor], + train_eval: Literal["train", "eval"] = "train", + ): + """Compute the ORPO loss and other metrics for the given batch of inputs for train or test.""" + metrics = {} + + forward_output = self.concatenated_forward(model, batch) + ( + policy_chosen_logps, + policy_rejected_logps, + policy_chosen_logits, + policy_rejected_logits, + policy_nll_loss, + ) = forward_output[:5] + if self.aux_loss_enabled: + aux_loss = forward_output[5] + + losses, chosen_rewards, rejected_rewards, log_odds_ratio, log_odds_chosen = self.odds_ratio_loss( + policy_chosen_logps, policy_rejected_logps + ) + # full ORPO loss + loss = policy_nll_loss - losses.mean() + + reward_accuracies = (chosen_rewards > rejected_rewards).float() + + prefix = "eval_" if train_eval == "eval" else "" + metrics[f"{prefix}rewards/chosen"] = self.accelerator.gather_for_metrics(chosen_rewards).mean() + metrics[f"{prefix}rewards/rejected"] = self.accelerator.gather_for_metrics(rejected_rewards).mean() + metrics[f"{prefix}rewards/accuracies"] = self.accelerator.gather_for_metrics(reward_accuracies).mean() + metrics[f"{prefix}rewards/margins"] = self.accelerator.gather_for_metrics( + chosen_rewards - rejected_rewards + ).mean() + metrics[f"{prefix}logps/rejected"] = self.accelerator.gather_for_metrics(policy_rejected_logps).detach().mean() + metrics[f"{prefix}logps/chosen"] = self.accelerator.gather_for_metrics(policy_chosen_logps).detach().mean() + metrics[f"{prefix}logits/rejected"] = self.accelerator.gather_for_metrics( + policy_rejected_logits.detach().mean() + ).mean() + metrics[f"{prefix}logits/chosen"] = self.accelerator.gather_for_metrics( + policy_chosen_logits.detach().mean() + ).mean() + metrics[f"{prefix}nll_loss"] = self.accelerator.gather_for_metrics(policy_nll_loss).detach().mean() + metrics[f"{prefix}log_odds_ratio"] = self.accelerator.gather_for_metrics(log_odds_ratio).detach().mean() + metrics[f"{prefix}log_odds_chosen"] = self.accelerator.gather_for_metrics(log_odds_chosen).detach().mean() + if is_torch_xla_available(): + xm.mark_step() # needed because .item() calls + for k, v in metrics.items(): + metrics[k] = v.item() + if self.aux_loss_enabled: + loss += self.aux_loss_coef * aux_loss + + return loss, metrics + + def compute_loss( + self, + model: PreTrainedModel | nn.Module, + inputs: dict[str, torch.Tensor | Any], + return_outputs=False, + num_items_in_batch=None, + ) -> torch.Tensor | tuple[torch.Tensor, dict[str, torch.Tensor]]: + compute_loss_context_manager = ( + autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() + ) + + with compute_loss_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="train") + + # Make sure to move the loss to the device the original accumulating loss is at back in the `Trainer` class: + loss = loss.to(self.args.device) + + # force log the metrics + self.store_metrics(metrics, train_eval="train") + + if return_outputs: + return (loss, metrics) + return loss + + def generate_from_model(self, model, batch: dict[str, torch.LongTensor]) -> str: + """Generate samples from the model and reference model for the given batch of inputs.""" + + # If one uses `generate_during_eval` with peft + bf16, we need to explicitly call generate with + # the torch amp context manager as some hidden states are silently casted to full precision. + generate_context_manager = ( + autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() + ) + + with generate_context_manager: + policy_output = model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + + policy_output = pad_to_length(policy_output, self.max_length, self.processing_class.pad_token_id) + policy_output_decoded = self.processing_class.batch_decode(policy_output, skip_special_tokens=True) + + return policy_output_decoded + + def prediction_step( + self, + model: PreTrainedModel | nn.Module, + inputs: dict[str, torch.Tensor | Any], + prediction_loss_only: bool, + ignore_keys: list[str] | None = None, + ): + if not self.use_dpo_data_collator: + logger.warning( + "prediction_step is only implemented for DPODataCollatorWithPadding, and you passed a datacollator that is different than " + "DPODataCollatorWithPadding - you might see unexpected behavior. Alternatively, you can implement your own prediction_step method if you are using a custom data collator" + ) + if ignore_keys is None: + if hasattr(model, "config"): + ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", []) + else: + ignore_keys = [] + + prediction_context_manager = ( + autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() + ) + + with torch.no_grad(), prediction_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="eval") + + # force log the metrics + self.store_metrics(metrics, train_eval="eval") + + if prediction_loss_only: + return (loss.detach(), None, None) + + # logits for the chosen and rejected samples from model + logits_dict = { + "eval_logits/chosen": metrics["eval_logits/chosen"], + "eval_logits/rejected": metrics["eval_logits/rejected"], + } + logits = [v for k, v in logits_dict.items() if k not in ignore_keys] + logits = torch.tensor(logits, device=self.accelerator.device) + labels = torch.zeros(logits.shape[0], device=self.accelerator.device) + + return (loss.detach(), logits, labels) + + def store_metrics(self, metrics: dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None: + for key, value in metrics.items(): + self._stored_metrics[train_eval][key].append(value) + + def evaluation_loop( + self, + dataloader: DataLoader, + description: str, + prediction_loss_only: bool | None = None, + ignore_keys: list[str] | None = None, + metric_key_prefix: str = "eval", + ) -> EvalLoopOutput: + """ + Overriding built-in evaluation loop to store metrics for each batch. Prediction/evaluation loop, shared by + `Trainer.evaluate()` and `Trainer.predict()`. + + Works both with or without labels. + """ + + # Sample and save to game log if requested (for one batch to save time) + if self.generate_during_eval: + # Generate random indices within the range of the total number of samples + num_samples = len(dataloader.dataset) + random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size) + + # Use dataloader.dataset.select to get the random batch without iterating over the DataLoader + random_batch_dataset = dataloader.dataset.select(random_indices) + random_batch = self.data_collator(random_batch_dataset) + random_batch = self._prepare_inputs(random_batch) + + policy_output_decoded = self.generate_from_model(self.model, random_batch) + + table = pd.DataFrame( + columns=["Prompt", "Policy"], + data=[ + [prompt, pol[len(prompt) :]] + for prompt, pol in zip(random_batch["prompt"], policy_output_decoded, strict=True) + ], + ) + if "wandb" in self.args.report_to: + wandb.log({"game_log": wandb.Table(data=table)}) + + if "comet_ml" in self.args.report_to: + log_table_to_comet_experiment( + name="game_log.csv", + table=table, + ) + + # Base evaluation + initial_output = super().evaluation_loop( + dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix + ) + + return initial_output + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + """ + Log `logs` on the various objects watching training, including stored metrics. + + Args: + logs (`dict[str, float]`): + The values to log. + start_time (`float`, *optional*): + Start time of the training. + """ + # logs either has 'loss' or 'eval_loss' + train_eval = "train" if "loss" in logs else "eval" + # Add averaged stored metrics to logs + for key, metrics in self._stored_metrics[train_eval].items(): + logs[key] = torch.tensor(metrics).mean().item() + del self._stored_metrics[train_eval] + return super().log(logs, start_time) + + def _shift_right(self, input_ids): + if self.decoder_start_token_id is None: + raise ValueError( + "model.config.decoder_start_token_id has to be defined. It is usually set to the pad_token_id." + ) + + # shift inputs to the right + if is_torch_fx_proxy(input_ids): + # Item assignment is not supported natively for proxies. + shifted_input_ids = torch.full(input_ids.shape[:-1] + (1,), self.decoder_start_token_id) + shifted_input_ids = torch.cat([shifted_input_ids, input_ids[..., :-1]], dim=-1) + else: + shifted_input_ids = input_ids.new_zeros(input_ids.shape) + shifted_input_ids[..., 1:] = input_ids[..., :-1].clone() + shifted_input_ids[..., 0] = self.decoder_start_token_id + + if self.pad_token_id is None: + raise ValueError("model.config.pad_token_id has to be defined.") + # replace possible -100 values in labels by `pad_token_id` + shifted_input_ids.masked_fill_(shifted_input_ids == -100, self.pad_token_id) + + return shifted_input_ids + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/papo/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/papo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..62fb8105cb446c197570023e388299e1bd96bbc4 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/papo/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from .papo_config import PAPOConfig +from .papo_trainer import PAPOTrainer diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/papo/papo_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/papo/papo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..e142a94a9cdc3128456b6127436c3befd6bc2a93 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/papo/papo_config.py @@ -0,0 +1,73 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass +from typing import Literal + +from ...trainer.grpo_config import GRPOConfig + + +@dataclass +class PAPOConfig(GRPOConfig): + """ + Configuration class for PAPOTrainer. + + PAPO (Perception-Aware Policy Optimization) extends GRPO/DAPO for multimodal reasoning by adding an implicit + perception loss and double entropy regularization. + + Args: + perception_loss_weight (`float`, *optional*, defaults to `0.1`): + gamma Weight coefficient for the perception loss term. This encourages the model to be sensitive to visual + changes. + + mask_ratio (`float`, *optional*, defaults to `0.3`): + Ratio of the image to mask when computing perception loss. + + mask_type (`Literal["random", "patch", "grid"]`, *optional*, defaults to `"random"`): + Type of masking strategy to use. + + der_loss_weight1 (`float`, *optional*, defaults to `0.03`): + eta1 Weight coefficient for the Double Entropy Regularization (DER) term. This term encourages confident + predictions with original images (low entropy) and uncertain predictions with masked images (high entropy). + + der_loss_weight2 (`float`, *optional*, defaults to `0.03`): + eta2 Weight coefficient for the Double Entropy Regularization (DER) term. This term encourages confident + predictions with original images (low entropy) and uncertain predictions with masked images (high entropy). + + loss_type (`Literal["grpo", "dapo"]`, inherited from GRPOConfig): + Base loss type to use. Set to "grpo" for PAPO-G or "dapo" for PAPO-D. + """ + + perception_loss_weight: float = 0.1 + mask_ratio: float = 0.3 + mask_type: Literal["random", "patch", "grid"] = "random" + + # Added for Double Entropy Regularization + der_loss_weight1: float = 0.03 + der_loss_weight2: float = 0.03 + + def __post_init__(self): + super().__post_init__() + + # Validation + if not 0.0 <= self.mask_ratio <= 1.0: + raise ValueError(f"mask_ratio must be between 0 and 1, got {self.mask_ratio}") + + if self.der_loss_weight1 < 0 or self.der_loss_weight2 < 0: + raise ValueError( + f"der_loss_weight1 and der_loss_weight2 must be non-negative, got {self.der_loss_weight1} and {self.der_loss_weight2}" + ) + + if self.mask_type not in ["random", "patch", "grid"]: + raise ValueError(f"mask_type must be one of ['random', 'patch', 'grid'], got {self.mask_type}") diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/papo/papo_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/papo/papo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..c38b3e53b12df1b5fa9a108324dcec3c9977713c --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/papo/papo_trainer.py @@ -0,0 +1,353 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import random +import textwrap + +import torch +from datasets import Dataset, IterableDataset +from transformers import PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin + +from ...trainer.grpo_trainer import GRPOTrainer, RewardFunc +from ...trainer.utils import nanmax, nanmin +from .papo_config import PAPOConfig + + +class PAPOTrainer(GRPOTrainer): + """ + Trainer for Perception-Aware Policy Optimization (PAPO). + + PAPO extends GRPO/DAPO for multimodal reasoning by adding an implicit perception loss that encourages the model to + better utilize visual information. The key innovation is computing KL divergence between model outputs on original + vs. corrupted (masked) images. + + Two variants are supported: + - PAPO-G: PAPO + GRPO (use loss_type="grpo") + - PAPO-D: PAPO + DAPO (use loss_type="dapo") + + Example: + + ```python + >>> from datasets import load_dataset + >>> from trl.experimental.papo import PAPOTrainer, PAPOConfig + + >>> dataset = load_dataset("your-vlm-dataset", split="train") + + + >>> def reward_func(completions, **kwargs): + ... # Your reward function for multimodal reasoning + ... return [compute_reward(c) for c in completions] + # PAPO-G + + >>> config = PAPOConfig( + ... loss_type="grpo", # Use GRPO as base + ... perception_loss_weight=0.1, + ... mask_ratio=0.3, + ... ) + # PAPO-G + + >>> config = PAPOConfig( + ... loss_type="dapo", # Use DAPO as base + ... perception_loss_weight=0.1, + ... mask_ratio=0.3, + ... ) + + >>> trainer = PAPOTrainer( + ... model="Qwen/Qwen2-VL-2B-Instruct", + ... reward_funcs=reward_func, + ... args=config, + ... train_dataset=dataset, + ... ) + + >>> trainer.train() + ``` + + Args: + model (`Union[str, PreTrainedModel]`): + Model to be trained (must be a vision-language model). + reward_funcs (`Union[RewardFunc, list[RewardFunc]]`): + Reward functions for computing rewards (same as GRPO). + args ([`PAPOConfig`], *optional*, defaults to `None`): + Configuration for this trainer. If `None`, a default configuration is used. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + Dataset to use for training. Must include "prompt" and "image" columns. + eval_dataset: Same requirements as train_dataset. + processing_class: Processing class (tokenizer/processor) for the model. + reward_processing_classes: Processing classes for reward models. + callbacks: Training callbacks. + optimizers: Optimizer and scheduler tuple. + peft_config: PEFT configuration if using parameter-efficient fine-tuning. + """ + + _tag_names = ["trl", "papo"] + _name = "PAPO" + _paper = { + "title": "Perception-Aware Policy Optimization for Multimodal Reasoning", + "id": "2507.06448", + # docstyle-ignore + "citation": textwrap.dedent( + """\ + @misc{wang2025perceptionawarepolicyoptimizationmultimodal, + title = {{Perception-Aware Policy Optimization for Multimodal Reasoning}}, + author = {Zhenhailong Wang and Xuehang Guo and Sofia Stoica and Haiyang Xu and Hongru Wang and Hyeonjeong Ha and Xiusi Chen and Yangyi Chen and Ming Yan and Fei Huang and Heng Ji}, + year = 2025, + url = {https://arxiv.org/abs/2507.06448}, + archivePrefix= {arXiv}, + eprint = {2507.06448}, + primaryClass = {cs.CL} + }""" + ), + } + + def __init__( + self, + model: str | PreTrainedModel, + reward_funcs: RewardFunc | list[RewardFunc], + args: PAPOConfig | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None, + callbacks=None, + optimizers=(None, None), + peft_config=None, + ): + # Initialize with default PAPO config if not provided + if args is None: + model_name = model if isinstance(model, str) else model.config._name_or_path + model_name = model_name.split("/")[-1] + args = PAPOConfig(f"{model_name}-PAPO") + + # Store PAPO-specific parameters + self.perception_loss_weight = args.perception_loss_weight + self.mask_ratio = args.mask_ratio + self.mask_type = args.mask_type + self.der_loss_weight1 = args.der_loss_weight1 + self.der_loss_weight2 = args.der_loss_weight2 + + # Initialize parent GRPO trainer + super().__init__( + model=model, + reward_funcs=reward_funcs, + args=args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + reward_processing_classes=reward_processing_classes, + callbacks=callbacks, + optimizers=optimizers, + peft_config=peft_config, + ) + + def _mask_image(self, pixel_values: torch.Tensor, mask_ratio: float = None) -> torch.Tensor: + """ + Apply masking to image pixel values. + + Args: + pixel_values: Image tensor of shape (B, C, H, W) or (B, N, C, H, W) for multi-image + mask_ratio: Ratio of image to mask (defaults to self.mask_ratio) + + Returns: + Masked pixel values tensor + """ + if mask_ratio is None: + mask_ratio = self.mask_ratio + + masked_pixel_values = pixel_values.clone() + + if self.mask_type == "random": + # Random pixel masking + mask = torch.rand_like(pixel_values) > mask_ratio + masked_pixel_values = masked_pixel_values * mask + + elif self.mask_type == "patch": + # Patch-based masking (mask contiguous regions) + B = pixel_values.shape[0] + if pixel_values.ndim == 4: # (B, C, H, W) + C, H, W = pixel_values.shape[1:] + for i in range(B): + # Calculate patch size to mask + patch_h = int(H * mask_ratio**0.5) + patch_w = int(W * mask_ratio**0.5) + # Random starting position + start_h = random.randint(0, max(0, H - patch_h)) + start_w = random.randint(0, max(0, W - patch_w)) + # Apply mask + masked_pixel_values[i, :, start_h : start_h + patch_h, start_w : start_w + patch_w] = 0 + + elif pixel_values.ndim == 5: # (B, N, C, H, W) for multi-image + N, C, H, W = pixel_values.shape[1:] + for i in range(B): + for n in range(N): + patch_h = int(H * mask_ratio**0.5) + patch_w = int(W * mask_ratio**0.5) + start_h = random.randint(0, max(0, H - patch_h)) + start_w = random.randint(0, max(0, W - patch_w)) + masked_pixel_values[i, n, :, start_h : start_h + patch_h, start_w : start_w + patch_w] = 0 + + elif self.mask_type == "grid": + # Grid-based masking (mask regular grid cells) + if pixel_values.ndim == 4: + C, H, W = pixel_values.shape[1:] + grid_size = int((1 / mask_ratio) ** 0.5) + cell_h, cell_w = H // grid_size, W // grid_size + + for i in range(grid_size): + for j in range(grid_size): + if random.random() < mask_ratio: + masked_pixel_values[:, :, i * cell_h : (i + 1) * cell_h, j * cell_w : (j + 1) * cell_w] = 0 + + return masked_pixel_values + + def _compute_loss(self, model, inputs): + # >>> 1. GRPO loss + # Compute the per-token log probabilities for the model + prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"] + completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"] + input_ids = torch.cat([prompt_ids, completion_ids], dim=1) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + + # Compute the per_token_logps and the entropy at each position in the completion + per_token_logps, entropies, _ = self._get_per_token_logps_and_entropies( + model, + input_ids, + attention_mask, + logits_to_keep, + compute_entropy=True, + pixel_values=inputs.get("pixel_values"), + image_grid_thw=inputs.get("image_grid_thw"), + num_images=inputs.get("num_images"), + pixel_attention_mask=inputs.get("pixel_attention_mask"), + image_sizes=inputs.get("image_sizes"), + ) + + if self.top_entropy_quantile < 1.0: + entropy_mask = self.get_high_entropy_mask(entropies, completion_mask, 1 - self.top_entropy_quantile) + else: + entropy_mask = None + + # Compute the KL divergence between the model and the reference model + if self.beta != 0.0: + ref_per_token_logps = inputs["ref_per_token_logps"] + per_token_kl = ( + torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1 + ) + + # Compute the loss + advantages = inputs["advantages"] + # When using num_iterations == 1 and steps_per_generation <= gradient_accumulation_steps + # old_per_token_logps == per_token_logps, so we can skip it's computation + # (see _generate_and_score_completions) and use per_token_logps.detach() instead. + old_per_token_logps = inputs.get("old_per_token_logps") + old_per_token_logps = per_token_logps.detach() if old_per_token_logps is None else old_per_token_logps + + log_ratio = per_token_logps - old_per_token_logps + if self.importance_sampling_level == "token": + log_importance_weights = log_ratio + elif self.importance_sampling_level == "sequence": + log_importance_weights = (log_ratio * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0) + log_importance_weights = log_importance_weights.unsqueeze(-1) + else: + raise ValueError( + f"Unknown importance sampling level: {self.importance_sampling_level}. Possible values are 'token' " + "and 'sequence'." + ) + # From here, log_importance_weights (and all subsequent tensors, coef_1, coef_2, etc.) shape depends on + # importance_sampling_level: "token" level: (B, T); "sequence" level: (B, 1) + + coef_1 = torch.exp(log_importance_weights) + coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high) + + # Two-sided clipping + if self.args.delta is not None: + coef_1 = torch.clamp(coef_1, max=self.args.delta) + + per_token_loss1 = coef_1 * advantages.unsqueeze(1) + per_token_loss2 = coef_2 * advantages.unsqueeze(1) + per_token_loss = -torch.min(per_token_loss1, per_token_loss2) + if entropy_mask is not None: + per_token_loss = per_token_loss * entropy_mask + if self.beta != 0.0: + per_token_loss = per_token_loss + self.beta * per_token_kl + + if self.loss_type == "grpo": + loss = ((per_token_loss * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0)).mean() + loss = loss / self.current_gradient_accumulation_steps + elif self.loss_type == "dapo": + normalizer = inputs["num_items_in_batch"] / self.accelerator.num_processes + loss = (per_token_loss * completion_mask).sum() / normalizer + else: + raise ValueError(f"Unknown loss type: {self.loss_type}") + # >>> 2. Implicit Perception Loss + inputs["pixel_values"] = self._mask_image(inputs["pixel_values"], self.mask_ratio) + mask_img_per_token_logps, mask_img_entropies, _ = self._get_per_token_logps_and_entropies( + model, + input_ids, + attention_mask, + logits_to_keep, + compute_entropy=True, + pixel_values=inputs.get("pixel_values"), + image_grid_thw=inputs.get("image_grid_thw"), + num_images=inputs.get("num_images"), + pixel_attention_mask=inputs.get("pixel_attention_mask"), + image_sizes=inputs.get("image_sizes"), + ) + perception_kl = ( + torch.exp(mask_img_per_token_logps - per_token_logps) - (mask_img_per_token_logps - per_token_logps) - 1 + ) + perception_kl = torch.clamp(perception_kl, min=0.0, max=0.2) + perception_loss = self.perception_loss_weight * perception_kl + + # >>> 3. Double Entropy Loss + der_loss = self.der_loss_weight1 * entropies + self.der_loss_weight2 * mask_img_entropies + + # PAPO Loss + loss = (loss - perception_loss + der_loss).mean() + # Log the metrics + mode = "train" if self.model.training else "eval" + + completion_token_count = completion_mask.sum().clamp(min=1.0) + + def masked_batch_mean(x): + if x.shape[1] == 1: # when importance_sampling_level == "sequence" + return x.mean() + else: + return (x * completion_mask).sum() / completion_token_count + + if self.beta != 0.0: + mean_kl = masked_batch_mean(per_token_kl) + self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item()) + + mean_entropy = masked_batch_mean(entropies) + self._metrics[mode]["entropy"].append(self.accelerator.gather(mean_entropy).nanmean().item()) + + # Compute the clipped probability ratios + is_low_clipped = (coef_1 < 1 - self.epsilon_low) & (advantages.unsqueeze(1) < 0) + is_high_clipped = (coef_1 > 1 + self.epsilon_high) & (advantages.unsqueeze(1) > 0) + is_region_clipped = is_low_clipped | is_high_clipped + + low_clip = masked_batch_mean(is_low_clipped.float()) + high_clip = masked_batch_mean(is_high_clipped.float()) + clip_ratio = masked_batch_mean(is_region_clipped.float()) + + gathered_low_clip = self.accelerator.gather(low_clip) + self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item()) + self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item()) + gathered_high_clip = self.accelerator.gather(high_clip) + self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item()) + self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item()) + gathered_clip_ratio = self.accelerator.gather(clip_ratio) + self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item()) + return loss diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ppo/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ppo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..09451e973bea4ae1432fe16276907644cd67466c --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ppo/__init__.py @@ -0,0 +1,30 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .modeling_value_head import ( + AutoModelForCausalLMWithValueHead, + AutoModelForSeq2SeqLMWithValueHead, + PreTrainedModelWrapper, +) +from .ppo_config import PPOConfig +from .ppo_trainer import PPOTrainer + + +__all__ = [ + "AutoModelForCausalLMWithValueHead", + "AutoModelForSeq2SeqLMWithValueHead", + "PreTrainedModelWrapper", + "PPOConfig", + "PPOTrainer", +] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ppo/modeling_value_head.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ppo/modeling_value_head.py new file mode 100644 index 0000000000000000000000000000000000000000..eacd2045b1910b98107929842098725b7f73aab4 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ppo/modeling_value_head.py @@ -0,0 +1,1020 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import logging +import os + +import torch +import torch.nn as nn +from accelerate import PartialState +from huggingface_hub import hf_hub_download +from huggingface_hub.utils import ( + EntryNotFoundError, + HFValidationError, + LocalEntryNotFoundError, + RepositoryNotFoundError, +) +from safetensors.torch import load_file as safe_load_file +from transformers import ( + AutoModelForCausalLM, + AutoModelForSeq2SeqLM, + PreTrainedModel, + is_torch_npu_available, + is_torch_xpu_available, +) +from transformers.utils import is_peft_available + + +if is_peft_available(): + from peft import ( + PeftConfig, + PeftModel, + PeftModelForCausalLM, + PeftModelForSeq2SeqLM, + PromptLearningConfig, + get_peft_model, + prepare_model_for_kbit_training, + ) + + +class PreTrainedModelWrapper(nn.Module): + """ + Wrapper for a [`~transformers.PreTrainedModel`] implemented as a standard PyTorch [`torch.nn.Module`]. + + This class provides a compatibility layer that preserves the key attributes and methods of the original + [`~transformers.PreTrainedModel`], while exposing a uniform interface consistent with PyTorch modules. It enables + seamless integration of pretrained Transformer models into custom training, evaluation, or inference workflows. + + Attributes: + pretrained_model ([`~transformers.PreTrainedModel`]): + The model to be wrapped. + parent_class ([`~transformers.PreTrainedModel`]): + The parent class of the model to be wrapped. + supported_args (`list`): + The list of arguments that are supported by the wrapper class. + """ + + transformers_parent_class = None + supported_args = None + supported_modules = ("v_head",) + supported_rm_modules = ("score",) + supported_pretrained_model_architectures = ( + (PreTrainedModel) + if not is_peft_available() + else (PreTrainedModel, PeftModelForCausalLM, PeftModelForSeq2SeqLM) + ) + + def __init__( + self, pretrained_model=None, score_module=None, supports_rm_adapter=False, rm_adapter_name=None, **kwargs + ): + super().__init__() + self.pretrained_model = pretrained_model + + self.config = pretrained_model.config + self.prepare_inputs_for_generation = pretrained_model.prepare_inputs_for_generation + self.is_loaded_in_8bit = getattr(pretrained_model, "is_loaded_in_8bit", False) + self.is_loaded_in_4bit = getattr(pretrained_model, "is_loaded_in_4bit", False) + self.is_sequential_parallel = False + + if hasattr(pretrained_model, "gradient_checkpointing_disable"): + self.gradient_checkpointing_disable = pretrained_model.gradient_checkpointing_disable + + if hasattr(pretrained_model, "gradient_checkpointing_enable"): + self.gradient_checkpointing_enable = pretrained_model.gradient_checkpointing_enable + + if hasattr(pretrained_model, "enable_input_require_grads"): + self.enable_input_require_grads = pretrained_model.enable_input_require_grads + + self.supports_rm_adapter = supports_rm_adapter + self.rm_adapter_name = rm_adapter_name + self.policy_adapter_name = "default" + if score_module is not None: + self.score = score_module + + @classmethod + def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): + r""" + Instantiates a new model from a pretrained model from `transformers`. The pretrained model is loaded using the + `from_pretrained` method of the [`~transformers.PreTrainedModel`] class. The arguments that are specific to the + [`~transformers.PreTrainedModel`] class are passed along this method and filtered out from the `kwargs` + argument. + + Args: + pretrained_model_name_or_path (`str` or [`~transformers.PreTrainedModel`]): + The path to the pretrained model or its name. + *model_args (`list`, *optional*): + Additional positional arguments passed along to the underlying model's `from_pretrained` method. + **kwargs (`dict`, *optional*): + Additional keyword arguments passed along to the underlying model's `from_pretrained` method. We also + pre-process the kwargs to extract the arguments that are specific to the + [`~transformers.PreTrainedModel`] class and the arguments that are specific to trl models. The kwargs + also support `prepare_model_for_kbit_training` arguments from `peft` library. + """ + if kwargs is not None: + peft_config = kwargs.pop("peft_config", None) + reward_adapter = kwargs.pop("reward_adapter", None) + reward_adapter_name = kwargs.pop("reward_adapter_name", "reward_adapter") + is_trainable = kwargs.pop("is_trainable", False) + trl_model_args, pretrained_kwargs, peft_quantization_kwargs = cls._split_kwargs(kwargs) + token = pretrained_kwargs.get("token", None) + else: + peft_config = None + is_trainable = False + trl_model_args = {} + pretrained_kwargs = {} + peft_quantization_kwargs = {} + token = None + + if reward_adapter is not None and not isinstance(reward_adapter, str): + raise ValueError( + "The `reward_adapter` argument should be a string representing the name of local path or the Hub id to the Reward Modeling adapter." + ) + + is_peft_model = False + + current_device = cls._get_current_device() + if isinstance(pretrained_model_name_or_path, str): + quantization_config = pretrained_kwargs.get("quantization_config", None) + if quantization_config is not None: + is_loaded_in_8bit = getattr(quantization_config, "load_in_8bit", False) + is_loaded_in_4bit = getattr(quantization_config, "load_in_4bit", False) + else: + is_loaded_in_8bit = pretrained_kwargs["load_in_8bit"] if "load_in_8bit" in pretrained_kwargs else False + is_loaded_in_4bit = pretrained_kwargs["load_in_4bit"] if "load_in_4bit" in pretrained_kwargs else False + else: + is_loaded_in_8bit = getattr(pretrained_model_name_or_path, "is_loaded_in_8bit", False) + is_loaded_in_4bit = getattr(pretrained_model_name_or_path, "is_loaded_in_4bit", False) + + if (is_loaded_in_8bit or is_loaded_in_4bit) and "device_map" not in pretrained_kwargs: + # warn users + logging.warning( + "The `device_map` argument is not provided. We will override the device_map argument." + " to set the entire" + " model on the current device. If you want to set the model on multiple devices, please provide" + " a custom `device_map` argument." + ) + pretrained_kwargs["device_map"] = {"": current_device} + + if is_peft_available() and peft_config is not None and not isinstance(peft_config, PeftConfig): + raise ValueError("The `peft_config` argument should be an instance of `peft.PeftConfig` class.") + + # First, load the pre-trained model using the parent-class + # either `AutoModelForCausalLM` or `AutoModelForSeq2SeqLM` + if isinstance(pretrained_model_name_or_path, str): + if is_peft_available(): + try: + # If there is a trained peft adapter in the hub, load its config. + remote_adapter_config = hf_hub_download( + pretrained_model_name_or_path, + "adapter_config.json", + token=token, + ) + except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError): + remote_adapter_config = None + else: + remote_adapter_config = None + + local_adapter_present = os.path.exists(os.path.join(pretrained_model_name_or_path, "adapter_config.json")) + + if (local_adapter_present or remote_adapter_config is not None) and is_peft_available(): + if peft_config is not None: + logging.warning( + "`peft_config` argument ignored since a peft config file was found in " + f"{pretrained_model_name_or_path}" + ) + + # Load the trained peft adapter config + if local_adapter_present: + trained_adapter_config = PeftConfig.from_pretrained(pretrained_model_name_or_path) + else: + remote_adapter_dir = os.path.dirname(remote_adapter_config) + trained_adapter_config = PeftConfig.from_pretrained(remote_adapter_dir) + + # Load the pretrained base model + pretrained_model = cls.transformers_parent_class.from_pretrained( + trained_adapter_config.base_model_name_or_path, *model_args, **pretrained_kwargs + ) + + # Wrap the pretrained model with the trained peft adapter + pretrained_model = PeftModel.from_pretrained( + pretrained_model, pretrained_model_name_or_path, is_trainable=is_trainable, token=token + ) + logging.info("Trained peft adapter loaded") + else: + pretrained_model = cls.transformers_parent_class.from_pretrained( + pretrained_model_name_or_path, *model_args, **pretrained_kwargs + ) + + if peft_config is not None: + # Initialize a new peft adapter with the given config + if is_loaded_in_8bit or is_loaded_in_4bit: + pretrained_model = prepare_model_for_kbit_training( + pretrained_model, + **peft_quantization_kwargs, + ) + pretrained_model = get_peft_model(pretrained_model, peft_config) + logging.info("peft adapter initialised") + + elif isinstance(pretrained_model_name_or_path, cls.supported_pretrained_model_architectures): + pretrained_model = pretrained_model_name_or_path + + if peft_config is not None and isinstance(pretrained_model, PreTrainedModel): + # Initialize a new peft adapter with the given config + if is_loaded_in_8bit or is_loaded_in_4bit: + pretrained_model = prepare_model_for_kbit_training( + pretrained_model, + **peft_quantization_kwargs, + ) + pretrained_model = get_peft_model(pretrained_model, peft_config) + logging.info("peft adapter initialised") + else: + raise ValueError( + "pretrained_model_name_or_path should be a string or a PreTrainedModel, " + f"but is {type(pretrained_model_name_or_path)}" + ) + + if is_peft_available(): + if isinstance(pretrained_model, PeftModel): + is_peft_model = True + # for backward compatibility + if hasattr(pretrained_model, "active_peft_config") and isinstance( + pretrained_model.active_peft_config, PromptLearningConfig + ): + raise ValueError("PromptLearningConfig is not supported for PPO training.") + + # Add reward modeling adapter if specified + if not is_peft_model and reward_adapter is not None: + raise ValueError("reward_adapter can only be used with a PeftModel. ") + elif is_peft_model and reward_adapter is not None: + score_module = cls.add_and_load_reward_modeling_adapter( + pretrained_model, reward_adapter, reward_adapter_name, token=token + ) + multi_adapter_args = { + "score_module": score_module, + "supports_rm_adapter": True, + "rm_adapter_name": reward_adapter_name, + } + else: + multi_adapter_args = {"supports_rm_adapter": False} + + # Then, create the full model by instantiating the wrapper class + model = cls(pretrained_model, **multi_adapter_args, **trl_model_args) + + # if resume_training, load the state_dict again - this is ok since the + # state_dict is removed from the model after loading it. + is_resuming_training = True + if isinstance(pretrained_model_name_or_path, str): + safe_filename = os.path.join(pretrained_model_name_or_path, "model.safetensors") + filename = os.path.join(pretrained_model_name_or_path, "pytorch_model.bin") + + sharded_index_filename = os.path.join(pretrained_model_name_or_path, "pytorch_model.bin.index.json") + safe_sharded_index_filename = os.path.join(pretrained_model_name_or_path, "model.safetensors.index.json") + is_sharded = False + use_safe = os.path.exists(safe_filename) + + if not (os.path.exists(filename) or os.path.exists(safe_filename)): + # Try with `pytorch_model.bin` + filename, files_to_download, is_sharded, is_resuming_training = cls._get_checkpoint_from_hub( + pretrained_model, + pretrained_model_name_or_path, + sharded_index_filename, + token=token, + ) + # Try with safetensors + if filename is None and files_to_download is None: + safe_filename, files_to_download, is_sharded, is_resuming_training = cls._get_checkpoint_from_hub( + pretrained_model, + pretrained_model_name_or_path, + safe_sharded_index_filename, + token=token, + model_name="model.safetensors", + model_index_name="model.safetensors.index.json", + ) + use_safe = True + else: + use_safe = False + + loading_func = safe_load_file if use_safe else torch.load + load_kwargs = {} if use_safe else {"map_location": "cpu", "weights_only": True} + + if is_resuming_training: + if is_sharded: + # download each file and add it to the state_dict + state_dict = {} + + for shard_file in files_to_download: + filename = hf_hub_download( + pretrained_model_name_or_path, + shard_file, + token=token, + ) + state_dict.update(loading_func(filename, **load_kwargs)) + else: + state_dict = loading_func(filename if not use_safe else safe_filename, **load_kwargs) + + else: + state_dict = pretrained_model_name_or_path.state_dict() + + model.is_peft_model = is_peft_model + model.current_device = current_device + + if is_resuming_training: + model.post_init(state_dict=state_dict) + + return model + + @classmethod + def _get_checkpoint_from_hub( + cls, + pretrained_model, + pretrained_model_name_or_path, + index_filename, + token=None, + model_name="pytorch_model.bin", + model_index_name="pytorch_model.bin.index.json", + ): + files_to_download = None + filename = None + is_resuming_training = True + is_sharded = False + + try: + filename = hf_hub_download( + pretrained_model_name_or_path, + model_name, + token=token, + ) + # sharded + except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError): + if os.path.exists(index_filename): + index_file_name = index_filename + else: + try: + index_file_name = hf_hub_download( + pretrained_model_name_or_path, + model_index_name, + token=token, + ) + except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError): + # not continue training, do not have v_head weight + is_resuming_training = False + logging.warning( + f"A {type(pretrained_model)} model is loaded from '{pretrained_model_name_or_path}', " + f"and no v_head weight is found. This IS expected if you are not resuming PPO training." + ) + # load json + if is_resuming_training: + with open(index_file_name) as f: + index = json.load(f) + # check filename with `v_head` or any known extra module: + files_to_download = set() + for k, v in index["weight_map"].items(): + if any(module in k for module in cls.supported_modules): + files_to_download.add(v) + is_sharded = True + + return filename, files_to_download, is_sharded, is_resuming_training + + @classmethod + def _get_current_device(cls): + r""" + Get the current device. For GPU & XPU, we return the local process index using the `accelerate.PartialState` + object to handle corner cases when running scripts in distributed environments. + + Returns: + current_device (`int | str`): + The current device. + """ + state = PartialState() + if torch.cuda.is_available() or is_torch_xpu_available(): + return state.local_process_index + elif is_torch_npu_available(): + return f"npu:{state.local_process_index}" + else: + return "cpu" + + @classmethod + def _split_kwargs(cls, kwargs): + """ + Separate the kwargs from the arguments that we support inside `supported_args` and the ones that we don't. + """ + check_peft_kwargs = False + + if is_peft_available(): + from peft import prepare_model_for_kbit_training + + check_peft_kwargs = True + + supported_kwargs = {} + unsupported_kwargs = {} + peft_kwargs = {} + + for key, value in kwargs.items(): + if key in cls.supported_args: + supported_kwargs[key] = value + else: + unsupported_kwargs[key] = value + + if check_peft_kwargs: + if key in prepare_model_for_kbit_training.__code__.co_varnames: + peft_kwargs[key] = value + if key in unsupported_kwargs: + unsupported_kwargs.pop(key) + + return supported_kwargs, unsupported_kwargs, peft_kwargs + + @classmethod + def add_and_load_reward_modeling_adapter( + cls, pretrained_model, adapter_model_id, adapter_name="reward_model_adapter", token=None + ): + r""" + Add and load a reward modeling adapter. This method can only be used if the model is a `PeftModel` and if you + have initialized the model with the `reward_modeling_adapter_id` argument, pointing to the id of the reward + modeling adapter. The latest needs also to contain the score head in order to produce the reward. + """ + pretrained_model.load_adapter(adapter_model_id, adapter_name, is_trainable=False) + pretrained_model.train() + + filename = os.path.join(adapter_model_id, "adapter_model.bin") + safe_loading = False + if not os.path.exists(filename): + try: + local_filename = hf_hub_download( + adapter_model_id, + "adapter_model.bin", + token=token, + ) + except Exception: + filename = os.path.join(adapter_model_id, "adapter_model.safetensors") + safe_loading = True + if not os.path.exists(filename): + try: + local_filename = hf_hub_download( + adapter_model_id, + "adapter_model.safetensors", + token=token, + ) + except Exception as exc: + raise ValueError( + "Could not find adapter model in the Hub, make sure you have the correct adapter model id." + ) from exc + else: + local_filename = filename + else: + local_filename = filename + + loading_func = safe_load_file if safe_loading else torch.load + load_kwargs = {} if safe_loading else {"map_location": "cpu", "weights_only": True} + + adapter_state_dict = loading_func(local_filename, **load_kwargs) + + for score_name_candidate in cls.supported_rm_modules: + if any(score_name_candidate in name for name in adapter_state_dict.keys()): + score_name = score_name_candidate + # we have found the correct head name and can break + break + + score_dict = {} + + for name, param in adapter_state_dict.items(): + if score_name in name: + key_name = ".".join(name.split(".")[-1:]) + score_dict[key_name] = param.to(cls._get_current_device()) + + num_labels, hidden_dim = score_dict["weight"].shape + has_bias = any("bias" in name for name in adapter_state_dict.keys()) + + score = nn.Linear(hidden_dim, num_labels, bias=has_bias).to( + device=cls._get_current_device(), + dtype=pretrained_model.dtype, + ) + score.load_state_dict(score_dict) + for param in score.parameters(): + param.requires_grad = False + + return score + + def push_to_hub(self, *args, **kwargs): + r""" + Push the pretrained model to the hub. This method is a wrapper around + [`~transformers.PreTrainedModel.push_to_hub`]. Please refer to the documentation of + [`~transformers.PreTrainedModel.push_to_hub`] for more information. + + Args: + *args (`list`, *optional*): + Positional arguments passed along to the underlying model's `push_to_hub` method. + **kwargs (`dict`, *optional*): + Keyword arguments passed along to the underlying model's `push_to_hub` method. + """ + raise NotImplementedError + + def save_pretrained(self, *args, **kwargs): + r""" + Save the pretrained model to a directory. This method is a wrapper around + [`~transformers.PreTrainedModel.save_pretrained`]. Please refer to the documentation of + [`~transformers.PreTrainedModel.save_pretrained`] for more information. + + Args: + *args (`list`, *optional*): + Positional arguments passed along to the underlying model's `save_pretrained` method. + **kwargs (`dict`, *optional*): + Keyword arguments passed along to the underlying model's `save_pretrained` method. + """ + state_dict = kwargs.get("state_dict") + if state_dict is None: + state_dict = self.state_dict() + kwargs["state_dict"] = state_dict + + # if it is a peft model only save the `v_head` state_dict and + # pop the `state_dict` from the kwargs to avoid silent bugs with `peft` + if self.is_peft_model: + save_path = args[0] + save_path = os.path.join(save_path, "pytorch_model.bin") + torch.save(state_dict, save_path) + _ = kwargs.pop("state_dict", None) + + return self.pretrained_model.save_pretrained(*args, **kwargs) + + def state_dict(self, *args, **kwargs): + r""" + Return the state_dict of the pretrained model. + """ + raise NotImplementedError + + def post_init(self, *args, **kwargs): + r""" + Post initialization method. This method is called after the model is instantiated and loaded from a checkpoint. + It can be used to perform additional operations such as loading the state_dict. + """ + raise NotImplementedError + + def compute_reward_score(self, input_ids, attention_mask=None, **kwargs): + r""" + Computes the reward score for a given input. The method has first to enable the adapter and then compute the + reward score. After that the model disables the reward modeling adapter and enables the default ppo adapter + again. + """ + if not self.supports_rm_adapter: + raise ValueError("This model does not support reward modeling adapter.") + + # enable rm adapter + self.pretrained_model.set_adapter(self.rm_adapter_name) + self.pretrained_model.eval() + + with torch.no_grad(): + base_model_output = self.pretrained_model( + input_ids=input_ids, + attention_mask=attention_mask, + output_hidden_states=True, + return_dict=True, + **kwargs, + ) + + last_hidden_states = base_model_output.hidden_states[-1] + scores = self.score(last_hidden_states) + + self.pretrained_model.set_adapter(self.policy_adapter_name) + self.pretrained_model.eval() + + return scores + + +class ValueHead(nn.Module): + r""" + The ValueHead class implements a head for GPT2 that returns a scalar for each output token. + """ + + def __init__(self, config, **kwargs): + super().__init__() + if not hasattr(config, "summary_dropout_prob"): + summary_dropout_prob = kwargs.pop("summary_dropout_prob", 0.1) + else: + summary_dropout_prob = config.summary_dropout_prob + + self.dropout = nn.Dropout(summary_dropout_prob) if summary_dropout_prob else nn.Identity() + + # Determine hidden_size in priority order: + # 1. word_embed_proj_dim (OPT-350m): output projection dim, != internal hidden_size + # 2. hidden_size: standard attribute for most decoder-only and seq2seq models + # 3. text_config.hidden_size: multimodal configs (Gemma3, LLaVA,...) with no top-level hidden_size + # 4. decoder.hidden_size: EncoderDecoder compositions (e.g. BERT encoder + BERT decoder) + if hasattr(config, "word_embed_proj_dim"): + hidden_size = config.word_embed_proj_dim + elif hasattr(config, "hidden_size"): + hidden_size = config.hidden_size + elif hasattr(config, "text_config") and hasattr(config.text_config, "hidden_size"): + hidden_size = config.text_config.hidden_size + elif ( + getattr(config, "is_encoder_decoder", False) + and hasattr(config, "decoder") + and hasattr(config.decoder, "hidden_size") + ): + hidden_size = config.decoder.hidden_size + else: + raise ValueError( + "Cannot determine `hidden_size` from model config. " + "Please open an issue or pass a model whose config exposes one of: " + "`hidden_size`, `word_embed_proj_dim`, `text_config.hidden_size`, or `decoder.hidden_size`." + ) + self.summary = nn.Linear(hidden_size, 1) + + self.flatten = nn.Flatten() + + def forward(self, hidden_states): + output = self.dropout(hidden_states) + + # For now force upcast in fp32 if needed. Let's keep the + # output in fp32 for numerical stability. + if output.dtype != self.summary.weight.dtype: + output = output.to(self.summary.weight.dtype) + + output = self.summary(output) + return output + + +class AutoModelForCausalLMWithValueHead(PreTrainedModelWrapper): + """ + An autoregressive model with a value head in addition to the language model head. This class inherits from + [`experimental.ppo.PreTrainedModelWrapper`] and wraps a [`~transformers.PreTrainedModel`] class. The wrapper class + supports classic functions such as `from_pretrained`, `push_to_hub` and `generate`. To call a method of the wrapped + model, simply manipulate the `pretrained_model` attribute of this class. + + Class attributes: + - **transformers_parent_class** ([`~transformers.PreTrainedModel`]) -- The parent class of the wrapped model. + This + should be set to `transformers.AutoModelForCausalLM` for this class. + - **supported_args** (`tuple`) -- A tuple of strings that are used to identify the arguments that are supported + by the [`ValueHead`] class. Currently, the supported args are: + - **summary_dropout_prob** (`float`, `optional`, defaults to `None`) -- The dropout probability for the + [`ValueHead`] class. + - **v_head_initializer_range** (`float`, `optional`, defaults to `0.2`) -- The initializer range for the + [`ValueHead`] if a specific initialization strategy is selected. + - **v_head_init_strategy** (`str`, `optional`, defaults to `None`) -- The initialization strategy for the + [`ValueHead`]. Currently, the supported strategies are: + - **`None`** -- Initializes the weights of the [`ValueHead`] with a random distribution. This is the + default strategy. + - **"normal"** -- Initializes the weights of the [`ValueHead`] with a normal distribution. + """ + + transformers_parent_class = AutoModelForCausalLM + supported_args = ( + "summary_dropout_prob", + "v_head_initializer_range", + "v_head_init_strategy", + ) + + def __init__(self, pretrained_model, **kwargs): + """ + Initializes the model. + + Args: + pretrained_model ([`~transformers.PreTrainedModel`]): + The model to wrap. It should be a causal language model such as GPT2. or any model mapped inside the + `AutoModelForCausalLM` class. + kwargs (`dict`, `optional`): + Additional keyword arguments, that are passed to the [`ValueHead`] class. + """ + super().__init__(pretrained_model, **kwargs) + v_head_kwargs, _, _ = self._split_kwargs(kwargs) + self.v_head = ValueHead(self.pretrained_model.config, **v_head_kwargs) + self._init_weights(**v_head_kwargs) + + def _init_weights(self, **kwargs): + r""" + Initializes the weights of the value head. The default initialization strategy is random. Users can pass a + different initialization strategy by passing the `v_head_init_strategy` argument when calling + `.from_pretrained`. Supported strategies are: + - `normal`: initializes the weights with a normal distribution. + + Args: + **kwargs (`dict`, `optional`): + Additional keyword arguments, that are passed to the [`ValueHead`] class. These arguments can contain + the `v_head_init_strategy` argument as well as the `v_head_initializer_range` argument. + """ + initializer_range = kwargs.pop("v_head_initializer_range", 0.2) + # random init by default + init_strategy = kwargs.pop("v_head_init_strategy", None) + if init_strategy is None: + # do nothing + pass + elif init_strategy == "normal": + self.v_head.summary.weight.data.normal_(mean=0.0, std=initializer_range) + self.v_head.summary.bias.data.zero_() + + def forward( + self, + input_ids=None, + past_key_values=None, + attention_mask=None, + return_past_key_values=False, + **kwargs, + ): + r""" + Applies a forward pass to the wrapped model and returns the logits of the value head. + + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. + past_key_values (`tuple(tuple(torch.FloatTensor))`, `optional`): + Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model + (see `past_key_values` input) to speed up sequential decoding. + attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, `optional`): + Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``: + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + return_past_key_values (bool): A flag indicating if the computed hidden-states should be returned. + kwargs (`dict`, `optional`): + Additional keyword arguments, that are passed to the wrapped model. + """ + kwargs["output_hidden_states"] = True # this had already been set in the LORA / PEFT examples + kwargs["past_key_values"] = past_key_values + + if self.is_peft_model and self.pretrained_model.active_peft_config.peft_type == "PREFIX_TUNING": + kwargs.pop("past_key_values") + + base_model_output = self.pretrained_model( + input_ids=input_ids, + attention_mask=attention_mask, + **kwargs, + ) + + last_hidden_state = base_model_output.hidden_states[-1] + lm_logits = base_model_output.logits + loss = base_model_output.loss + + if last_hidden_state.device != self.v_head.summary.weight.device: + last_hidden_state = last_hidden_state.to(self.v_head.summary.weight.device) + + value = self.v_head(last_hidden_state).squeeze(-1) + + # force upcast in fp32 if logits are in half-precision + if lm_logits.dtype != torch.float32: + lm_logits = lm_logits.float() + + if return_past_key_values: + return (lm_logits, loss, value, base_model_output.past_key_values) + else: + return (lm_logits, loss, value) + + def generate(self, *args, **kwargs): + r""" + A simple wrapper around the `generate` method of the wrapped model. Please refer to the + [`generate`](https://huggingface.co/docs/transformers/internal/generation_utils) method of the wrapped model + for more information about the supported arguments. + + Args: + *args (`list`, *optional*): + Positional arguments passed to the `generate` method of the wrapped model. + **kwargs (`dict`, *optional*): + Keyword arguments passed to the `generate` method of the wrapped model. + """ + return self.pretrained_model.generate(*args, **kwargs) + + def state_dict(self, *args, **kwargs): + r""" + Returns the state dictionary of the model. We add the state dictionary of the value head to the state + dictionary of the wrapped model by prepending the key with `v_head.`. + """ + if not self.is_peft_model: + pretrained_model_state_dict = self.pretrained_model.state_dict(*args, **kwargs) + else: + # if it is a peft model, only save the v_head + pretrained_model_state_dict = {} + + v_head_state_dict = self.v_head.state_dict(*args, **kwargs) + for k, v in v_head_state_dict.items(): + pretrained_model_state_dict[f"v_head.{k}"] = v + return pretrained_model_state_dict + + def push_to_hub(self, *args, **kwargs): + self.pretrained_model.v_head = self.v_head + + return self.pretrained_model.push_to_hub(*args, **kwargs) + + def post_init(self, state_dict): + r""" + We add the state dictionary of the value head to the state dictionary of the wrapped model by prepending the + key with `v_head.`. This function removes the `v_head.` prefix from the keys of the value head state + dictionary. + """ + for k in list(state_dict.keys()): + if "v_head." in k: + state_dict[k.replace("v_head.", "")] = state_dict.pop(k) + self.v_head.load_state_dict(state_dict, strict=False) + del state_dict + + if hasattr(self.pretrained_model, "hf_device_map"): + if ( + "cpu" in self.pretrained_model.hf_device_map.values() + or "disk" in self.pretrained_model.hf_device_map.values() + ): + raise ValueError( + "The model is offloaded on CPU or disk - CPU & disk offloading is not supported for ValueHead models." + ) + + first_device = list(set(self.pretrained_model.hf_device_map.values()))[0] + if isinstance(first_device, int): + if is_torch_npu_available(): + first_device = f"npu:{first_device}" + elif is_torch_xpu_available(): + first_device = f"xpu:{first_device}" + else: + first_device = f"cuda:{first_device}" + self.v_head = self.v_head.to(first_device) + + def set_device_hook(module, input, outputs): + new_output = () + for output in outputs: + if isinstance(output, torch.Tensor): + new_output += (output.to(first_device),) + else: + new_output += (output,) + return new_output + + self.register_forward_hook(set_device_hook) + + self.is_sequential_parallel = True + + +class AutoModelForSeq2SeqLMWithValueHead(PreTrainedModelWrapper): + """ + A seq2seq model with a value head in addition to the language model head. This class inherits from + [`experimental.ppo.PreTrainedModelWrapper`] and wraps a [`~transformers.PreTrainedModel`] class. The wrapper class + supports classic functions such as `from_pretrained` and `push_to_hub` and also provides some additional + functionalities such as `generate`. + + Args: + pretrained_model ([`~transformers.PreTrainedModel`]): + The model to wrap. It should be a causal language model such as GPT2. or any model mapped inside the + [`~transformers.AutoModelForSeq2SeqLM`] class. + kwargs: + Additional keyword arguments passed along to the [`ValueHead`] class. + """ + + transformers_parent_class = AutoModelForSeq2SeqLM + lm_head_namings = ["lm_head", "embed_out", "output_projection"] + supported_args = ( + "summary_dropout_prob", + "v_head_initializer_range", + "v_head_init_strategy", + ) + + def __init__(self, pretrained_model, **kwargs): + super().__init__(pretrained_model, **kwargs) + v_head_kwargs, _, _ = self._split_kwargs(kwargs) + self.is_encoder_decoder = True + + if not self._has_lm_head(): + raise ValueError("The model does not have a language model head, please use a model that has one.") + + self.v_head = ValueHead(self.pretrained_model.config, **v_head_kwargs) + + self._init_weights(**v_head_kwargs) + + def _has_lm_head(self): + # check module names of all modules inside `pretrained_model` to find the language model head + for name, _module in self.pretrained_model.named_modules(): + if any(attribute in name for attribute in self.lm_head_namings): + return True + return False + + def post_init(self, state_dict): + r""" + We add the state dictionary of the value head to the state dictionary of the wrapped model by prepending the + key with `v_head.`. This function removes the `v_head.` prefix from the keys of the value head state + dictionary. + """ + for k in list(state_dict.keys()): + if "v_head." in k: + state_dict[k.replace("v_head.", "")] = state_dict.pop(k) + self.v_head.load_state_dict(state_dict, strict=False) + del state_dict + + if hasattr(self.pretrained_model, "hf_device_map"): + if ( + "cpu" in self.pretrained_model.hf_device_map.values() + or "disk" in self.pretrained_model.hf_device_map.values() + ): + raise ValueError( + "The model is offloaded on CPU or disk - CPU & disk offloading is not supported for ValueHead models." + ) + + # get the lm_head device + for name, module in self.pretrained_model.named_modules(): + if any(attribute in name for attribute in self.lm_head_namings): + lm_head_device = module.weight.device + break + + # put v_head on the same device as the lm_head to avoid issues + self.v_head = self.v_head.to(lm_head_device) + + def set_device_hook(module, input, outputs): + r""" + A hook that sets the device of the output of the model to the device of the first parameter of the + model. + + Args: + module (`nn.Module`): + The module to which the hook is attached. + input (`tuple`): + The input to the module. + outputs (`tuple`): + The output of the module. + """ + new_output = () + for output in outputs: + if isinstance(output, torch.Tensor): + new_output += (output.to(lm_head_device),) + else: + new_output += (output,) + return new_output + + self.register_forward_hook(set_device_hook) + self.is_sequential_parallel = True + + def state_dict(self, *args, **kwargs): + r""" + Returns the state dictionary of the model. We add the state dictionary of the value head to the state + dictionary of the wrapped model by prepending the key with `v_head.`. + """ + if not self.is_peft_model: + pretrained_model_state_dict = self.pretrained_model.state_dict(*args, **kwargs) + else: + # if it is a peft model, only save the v_head + pretrained_model_state_dict = {} + + v_head_state_dict = self.v_head.state_dict(*args, **kwargs) + for k, v in v_head_state_dict.items(): + pretrained_model_state_dict[f"v_head.{k}"] = v + return pretrained_model_state_dict + + def push_to_hub(self, *args, **kwargs): + self.pretrained_model.v_head = self.v_head + + return self.pretrained_model.push_to_hub(*args, **kwargs) + + def _init_weights(self, **kwargs): + r""" + We initialize the weights of the value head. + """ + initializer_range = kwargs.pop("v_head_initializer_range", 0.2) + # random init by default + init_strategy = kwargs.pop("v_head_init_strategy", None) + if init_strategy is None: + # do nothing + pass + elif init_strategy == "normal": + self.v_head.summary.weight.data.normal_(mean=0.0, std=initializer_range) + self.v_head.summary.bias.data.zero_() + + def forward( + self, + input_ids=None, + past_key_values=None, + attention_mask=None, + return_past_key_values=False, + **kwargs, + ): + kwargs["past_key_values"] = past_key_values + if self.is_peft_model and self.pretrained_model.active_peft_config.peft_type == "PREFIX_TUNING": + kwargs.pop("past_key_values") + + base_model_output = self.pretrained_model( + input_ids=input_ids, + attention_mask=attention_mask, + output_hidden_states=True, # We force the model to output hidden states + **kwargs, + ) + + last_hidden_state = base_model_output.decoder_hidden_states[-1] + lm_logits = base_model_output.logits + loss = base_model_output.loss + + value = self.v_head(last_hidden_state).squeeze(-1) + + # force upcast in fp32 if logits are in half-precision + if lm_logits.dtype != torch.float32: + lm_logits = lm_logits.float() + + if return_past_key_values: + return (lm_logits, loss, value, base_model_output.past_key_values) + else: + return (lm_logits, loss, value) + + def generate(self, *args, **kwargs): + r""" + We call `generate` on the wrapped model. + """ + return self.pretrained_model.generate(*args, **kwargs) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ppo/ppo_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ppo/ppo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..b96ee394734982fd82cf6ba2ae87bc6ca7be206f --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ppo/ppo_config.py @@ -0,0 +1,280 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Literal + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class PPOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`experimental.ppo.PPOTrainer`]. + + This class includes only the parameters that are specific to PPO training. For a full list of training arguments, + please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may + differ from those in [`~transformers.TrainingArguments`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + dataset_num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + num_mini_batches (`int`, *optional*, defaults to `1`): + Number of minibatches to split a batch into. + total_episodes (`int`, *optional*): + Total number of episodes in the dataset. + local_rollout_forward_batch_size (`int`, *optional*, defaults to `64`): + Per rank no grad forward pass in the rollout phase. + num_sample_generations (`int`, *optional*, defaults to `10`): + Number of debugging samples generations (i.e., `generate_completions` calls) throughout training. + response_length (`int`, *optional*, defaults to `53`): + Length of the response. + stop_token (`str`, *optional*): + Specifies the stop token to use for text generation. This parameter is mutually exclusive with + `stop_token_id`. + + - `None`: No stop token is applied, unless `stop_token_id` is specified. + - `'eos'`: Uses the tokenizer's `eos_token`. + + stop_token_id (`int`, *optional*): + Specifies the ID of the stop token to use for text generation. If `None`, no stop token ID is applied, + unless `stop_token` is specified. This parameter is mutually exclusive with `stop_token`. + temperature (`float`, *optional*, defaults to `0.7`): + Sampling temperature. + missing_eos_penalty (`float`, *optional*): + Penalty applied to the score when the model fails to generate an EOS token. This is useful to encourage to + generate completions shorter than the maximum length (`max_new_tokens`). The penalty must be a positive + value. + sft_model_path (`str`, *optional*, defaults to `"EleutherAI/pythia-160m"`): + Path to the SFT model. + world_size (`int`, *optional*): + Number of processes (GPUs) to use for the training. + num_total_batches (`int`, *optional*): + Number of total batches to train. + micro_batch_size (`int`, *optional*): + Micro batch size across devices (HF's `per_device_train_batch_size` * `world_size`). + local_batch_size (`int`, *optional*): + Batch size per GPU (HF's `per_device_train_batch_size` * `gradient_accumulation_steps`). + batch_size (`int`, *optional*): + Batch size across devices (HF's `per_device_train_batch_size` * `world_size` * + `gradient_accumulation_steps`). + local_mini_batch_size (`int`, *optional*): + Mini batch size per GPU. + mini_batch_size (`int`, *optional*): + Mini batch size across GPUs. + push_to_hub (`bool`, *optional*, defaults to `False`): + Whether to push the model to the Hub after training. + reward_model_path (`str`, *optional*, defaults to `"EleutherAI/pythia-160m"`): + Path to the reward model. + model_adapter_name (`str`, *optional*): + Name of the train target PEFT adapter, when using LoRA with multiple adapters. + ref_adapter_name (`str`, *optional*): + Name of the reference PEFT adapter, when using LoRA with multiple adapters. + num_ppo_epochs (`int`, *optional*, defaults to `4`): + Number of epochs to train. + whiten_rewards (`bool`, *optional*, defaults to `False`): + Whether to whiten the rewards. + kl_coef (`float`, *optional*, defaults to `0.05`): + KL coefficient. + kl_estimator (`Literal["k1", "k3"]`, *optional*, defaults to `"k1"`): + Which estimator for KL-Divergence to use from [Approximating KL + Divergence](http://joschu.net/blog/kl-approx.html). Defaults to "k1", a straightforward, unbiased + estimator. Can be set to "k3", an unbiased estimator with lower variance which "appears to be a strictly + better estimator". Cannot be set to "k2", as it is used for logging purposes. + cliprange (`float`, *optional*, defaults to `0.2`): + Clip range. + vf_coef (`float`, *optional*, defaults to `0.1`): + Value function coefficient. + cliprange_value (`float`, *optional*, defaults to `0.2`): + Clip range for the value function. + gamma (`float`, *optional*, defaults to `1.0`): + Discount factor. + lam (`float`, *optional*, defaults to `0.95`): + Lambda value for GAE. + ds3_gather_for_generation (`bool`, *optional*, defaults to `True`): + This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation, + improving generation speed. However, disabling this option allows training models that exceed the VRAM + capacity of a single GPU, albeit at the cost of slower generation. + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `3e-6` instead of `5e-5`. + """ + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=3e-6, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + dataset_num_proc: int | None = field( + default=None, + metadata={"help": "Number of processes to use for processing the dataset."}, + ) + num_mini_batches: int = field( + default=1, + metadata={"help": "Number of minibatches to split a batch into."}, + ) + total_episodes: int | None = field( + default=None, + metadata={"help": "Total number of episodes in the dataset."}, + ) + local_rollout_forward_batch_size: int = field( + default=64, + metadata={"help": "Per rank no grad forward pass in the rollout phase."}, + ) + num_sample_generations: int = field( + default=10, + metadata={ + "help": "Number of debugging samples generations (i.e., `generate_completions` calls) throughout training." + }, + ) + response_length: int = field( + default=53, + metadata={"help": "Length of the response."}, + ) + stop_token: Literal["eos"] | None = field( + default=None, + metadata={ + "help": "Specifies the stop token to use for text generation. This parameter is mutually exclusive with " + "`stop_token_id`." + }, + ) + stop_token_id: int | None = field( + default=None, + metadata={ + "help": "Specifies the ID of the stop token to use for text generation. If `None`, no stop token ID is " + "applied, unless `stop_token` is specified. This parameter is mutually exclusive with `stop_token`." + }, + ) + temperature: float = field( + default=0.7, + metadata={"help": "Sampling temperature."}, + ) + missing_eos_penalty: float | None = field( + default=None, + metadata={ + "help": "Penalty applied to the score when the model fails to generate an EOS token. This is useful to " + "encourage to generate completions shorter than the maximum length (`max_new_tokens`). The penalty must be " + "a positive value." + }, + ) + sft_model_path: str = field( + default="EleutherAI/pythia-160m", + metadata={"help": "Path to the SFT model."}, + ) + world_size: int | None = field( + default=None, + metadata={"help": "Number of processes (GPUs) to use for the training."}, + ) + num_total_batches: int | None = field( + default=None, + metadata={"help": "Number of total batches to train."}, + ) + micro_batch_size: int | None = field( + default=None, + metadata={"help": "Micro batch size across devices (HF's `per_device_train_batch_size` * `world_size`)."}, + ) + local_batch_size: int | None = field( + default=None, + metadata={"help": "Batch size per GPU (HF's `per_device_train_batch_size` * `gradient_accumulation_steps`)."}, + ) + batch_size: int | None = field( + default=None, + metadata={ + "help": "Batch size across devices (HF's `per_device_train_batch_size` * `world_size` * " + "`gradient_accumulation_steps`)." + }, + ) + local_mini_batch_size: int | None = field( + default=None, + metadata={"help": "Mini batch size per GPU."}, + ) + mini_batch_size: int | None = field( + default=None, + metadata={"help": "Mini batch size across GPUs."}, + ) + push_to_hub: bool = field( + default=False, + metadata={"help": "Whether to push the model to the Hub after training."}, + ) + reward_model_path: str = field( + default="EleutherAI/pythia-160m", + metadata={"help": "Path to the reward model."}, + ) + model_adapter_name: str | None = field( + default=None, + metadata={"help": "Name of the train target PEFT adapter, when using LoRA with multiple adapters."}, + ) + ref_adapter_name: str | None = field( + default=None, + metadata={"help": "Name of the reference PEFT adapter, when using LoRA with multiple adapters."}, + ) + num_ppo_epochs: int = field( + default=4, + metadata={"help": "Number of epochs to train."}, + ) + whiten_rewards: bool = field( + default=False, + metadata={"help": "Whether to whiten the rewards."}, + ) + kl_coef: float = field( + default=0.05, + metadata={"help": "KL coefficient."}, + ) + kl_estimator: Literal["k1", "k3"] = field( + default="k1", + metadata={ + "help": "Which estimator for KL-Divergence to use from Approximating KL Divergence " + "(http://joschu.net/blog/kl-approx.html). Defaults to 'k1', a straightforward, unbiased estimator. Can be " + "set to 'k3', an unbiased estimator with lower variance which 'appears to be a strictly better " + "estimator'. Cannot be set to 'k2', as it is used for logging purposes." + }, + ) + cliprange: float = field( + default=0.2, + metadata={"help": "Clip range."}, + ) + vf_coef: float = field( + default=0.1, + metadata={"help": "Value function coefficient."}, + ) + cliprange_value: float = field( + default=0.2, + metadata={"help": "Clip range for the value function."}, + ) + gamma: float = field( + default=1.0, + metadata={"help": "Discount factor."}, + ) + lam: float = field( + default=0.95, + metadata={"help": "Lambda value for GAE."}, + ) + ds3_gather_for_generation: bool = field( + default=True, + metadata={ + "help": "This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for " + "generation, improving generation speed. However, disabling this option allows training models that " + "exceed the VRAM capacity of a single GPU, albeit at the cost of slower generation." + }, + ) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ppo/ppo_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ppo/ppo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..f982932a2990fe2ffa994d2816d3b9532e86d970 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ppo/ppo_trainer.py @@ -0,0 +1,1038 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import gc +import math +import os +import textwrap +import time +from collections import defaultdict +from contextlib import contextmanager, nullcontext +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +import pandas as pd +import torch +import torch.nn as nn +import transformers +from accelerate import Accelerator +from accelerate.logging import get_logger +from accelerate.utils import gather_object +from datasets import Dataset +from packaging.version import Version +from torch.utils.data import DataLoader +from transformers import ( + BaseImageProcessor, + DataCollatorWithPadding, + FeatureExtractionMixin, + GenerationConfig, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, + TrainerControl, + TrainerState, +) +from transformers.integrations import get_reporting_integration_callbacks +from transformers.trainer import DEFAULT_CALLBACKS, DEFAULT_PROGRESS_CALLBACK +from transformers.trainer_callback import CallbackHandler, ExportableState, PrinterCallback +from transformers.utils import ModelOutput, is_peft_available, is_rich_available + +from ...models.utils import prepare_deepspeed, unwrap_model_for_generation +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import ( + disable_dropout_in_model, + log_table_to_comet_experiment, + pad, + selective_log_softmax, +) +from ..utils import ( + create_reference_model, + empty_cache, + first_true_indices, + get_reward, + peft_module_casting_to_bf16, +) +from .ppo_config import PPOConfig + + +if is_rich_available(): + from rich.console import Console + from rich.table import Table + + +logger = get_logger(__name__) + +if is_peft_available(): + from peft import PeftConfig, PeftModel, get_peft_model + + +INVALID_LOGPROB = 1.0 + + +def generate( + lm_backbone: torch.nn.Module, queries: torch.Tensor, pad_token_id: int, generation_config: GenerationConfig +) -> tuple[torch.Tensor, torch.Tensor]: + """ + Generates sequences from the language model backbone in a way that does not affect padding tokens. + + Args: + lm_backbone (`torch.nn.Module`): + The language model backbone used for generation. + queries (`torch.Tensor`): + The tensor containing the input queries. + pad_token_id (`int`): + The token ID representing the pad token. + generation_config ([`~transformers.GenerationConfig`]): + The configuration for the generation process. + + Returns: + tuple: + - `generated_sequences` (`torch.Tensor`): + The concatenated tensor of input queries and generated sequences. + - `logits` (`torch.Tensor`): + The logits output from the generation process. + """ + context_length = queries.shape[1] + attention_mask = queries != pad_token_id + input_ids = torch.masked_fill(queries, ~attention_mask, 0) + output = lm_backbone.generate( + input_ids=input_ids, + attention_mask=attention_mask, + # position_ids=attention_mask.cumsum(1) - attention_mask.long(), # not needed: already adjusted in generations + # https://github.com/huggingface/transformers/blob/ac33aeeeee2a7a89b89c93c2962e6feb90daef0a/src/transformers/models/gpt2/modeling_gpt2.py#L1227-L1250 + generation_config=generation_config, + return_dict_in_generate=True, + output_scores=True, + ) + logits = torch.stack(output.scores, 1) + return torch.cat((queries, output.sequences[:, context_length:]), dim=1), logits + + +@torch.no_grad() +def batch_generation( + model: torch.nn.Module, + queries: torch.Tensor, + local_rollout_forward_batch_size: int, + pad_token_id: int, + generation_config: GenerationConfig, +): + query_responses = [] + logitss = [] + batch_size = queries.shape[0] + for i in range(0, batch_size, local_rollout_forward_batch_size): + query = queries[i : i + local_rollout_forward_batch_size] + query_response, logits = generate( + model, + query, + pad_token_id, + generation_config, + ) + query_responses.append(query_response) + logitss.append(logits) + + # padding tensors + padded_query_responses = pad(query_responses, padding_value=pad_token_id, padding_side="right") + padded_logitss = pad(logitss, padding_value=0, padding_side="right") + + # reshaping + padded_query_responses = padded_query_responses.view(-1, padded_query_responses.shape[-1])[:batch_size] + padded_logitss = padded_logitss.view(-1, *padded_logitss.shape[2:])[:batch_size] + + return padded_query_responses, padded_logitss + + +def exact_div(a, b, custom_error_message=""): + q = a // b + if a != q * b: + raise ValueError(f"{custom_error_message}, inexact division: {a} / {b} = {a / b}") + return q + + +def print_rich_table(df: pd.DataFrame) -> None: + if not is_rich_available(): + raise ImportError( + "The function `print_rich_table` requires the `rich` library. Please install it with `pip install rich`." + ) + console = Console() + table = Table(show_lines=True) + for column in df.columns: + table.add_column(column) + for _, row in df.iterrows(): + table.add_row(*row.astype(str).tolist()) + console.print(table) + + +def truncate_response(stop_token_id: int, pad_token_id: int, responses: torch.Tensor) -> torch.Tensor: + """ + Truncates the responses at the first occurrence of the stop token, filling the rest with pad tokens. + + Args: + stop_token_id (`int`): + The token ID representing the stop token where truncation occurs. + pad_token_id (`int`): + The token ID representing the pad token used to fill the truncated responses. + responses (`torch.Tensor`): + The tensor containing the responses to be truncated. + + Returns: + `torch.Tensor`: + The truncated responses tensor with pad tokens filled after the stop token. + """ + trunc_idxs = first_true_indices(responses == stop_token_id).unsqueeze(-1) + new_size = [1] * (len(responses.size()) - 1) + [responses.shape[1]] + idxs = torch.arange(responses.shape[1], device=responses.device).view(*new_size) + postprocessed_responses = torch.masked_fill(responses, idxs > trunc_idxs, pad_token_id) + return postprocessed_responses + + +def forward( + model: torch.nn.Module, + query_responses: torch.Tensor, + pad_token_id: int, +) -> ModelOutput: + """ + Performs a forward pass through the model with the given query responses and pad token ID. + + Args: + model (`torch.nn.Module`): + The model to perform the forward pass. + query_responses (`torch.Tensor`): + The tensor containing the query responses. + pad_token_id (`int`): + The token ID representing the pad token. + + Returns: + `ModelOutput`: + The output of the model, including hidden states. + """ + attention_mask = query_responses != pad_token_id + position_ids = attention_mask.cumsum(1) - attention_mask.long() + input_ids = torch.masked_fill(query_responses, ~attention_mask, 0) + return model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + return_dict=True, + output_hidden_states=True, + ) + + +@dataclass +class OnlineTrainerState(TrainerState): + """ + Training state for online/on-policy trainers. + + Extends [`~transformers.TrainerState`] with an `episode` counter to track the current rollout/episode. + + Args: + episode (`int`, defaults to 0): Zero-based episode index. + """ + + episode: int = 0 + + +def masked_mean(values: torch.Tensor, mask: torch.Tensor, axis: bool | None = None) -> torch.Tensor: + """Compute mean of tensor with a masked values.""" + if axis is not None: + return (values * mask).sum(axis=axis) / mask.sum(axis=axis) + else: + return (values * mask).sum() / mask.sum() + + +def masked_var(values: torch.Tensor, mask: torch.Tensor, unbiased: bool = True) -> torch.Tensor: + """Compute variance of tensor with masked values.""" + mean = masked_mean(values, mask) + centered_values = values - mean + variance = masked_mean(centered_values**2, mask) + if unbiased: + mask_sum = mask.sum() + if mask_sum == 0: + raise ValueError( + "The sum of the mask is zero, which can happen when `mini_batch_size=1`;" + "try increase the `mini_batch_size` or `gradient_accumulation_steps`" + ) + # note that if mask_sum == 1, then there is a division by zero issue + # to avoid it you just need to use a larger minibatch_size + bessel_correction = mask_sum / (mask_sum - 1) + variance = variance * bessel_correction + return variance + + +def masked_whiten(values: torch.Tensor, mask: torch.Tensor, shift_mean: bool = True) -> torch.Tensor: + """Whiten values with masked values.""" + mean, var = masked_mean(values, mask), masked_var(values, mask) + whitened = (values - mean) * torch.rsqrt(var + 1e-8) + if not shift_mean: + whitened += mean + return whitened + + +# taken from https://github.com/OpenLMLab/MOSS-RLHF/blob/40b91eb2f2b71b16919addede0341d2bef70825d/ppo/ppo_trainer.py#L29 +# we did this we can do a single `model = accelerator.prepare(model)` +class PolicyAndValueWrapper(nn.Module): + def __init__(self, policy, value_model) -> None: + super().__init__() + self.policy = policy + self.value_model = value_model + self.critic_backbone = getattr(value_model, value_model.base_model_prefix) + self.is_gradient_checkpointing = policy.is_gradient_checkpointing + + def gradient_checkpointing_enable(self, **kwargs): + self.policy.gradient_checkpointing_enable(**kwargs) + self.is_gradient_checkpointing = True + + def gradient_checkpointing_disable(self): + self.policy.gradient_checkpointing_disable() + self.is_gradient_checkpointing = False + + def forward(self, **kwargs): + output = self.critic_backbone(**kwargs) + logits = self.value_model.score(output.hidden_states[-1]) + return self.policy(**kwargs), logits + + +class PPOTrainer(_BaseTrainer): + """Trainer for Proximal Policy Optimization (PPO). + + For details on PPO, see the paper: [Proximal Policy Optimization + Algorithms](https://huggingface.co/papers/1707.06347). + + Args: + args ([`experimental.ppo.PPOConfig`]): + Training arguments. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`]): + Class to process the data. + model (`torch.nn.Module`): + Model to be trained. This is the policy model. + ref_model (`torch.nn.Module`, *optional*): + Reference model used to compute the KL divergence. If `None`, a copy of the policy model is created. + reward_model (`torch.nn.Module`): + Reward model used to compute the rewards. + train_dataset ([`~datasets.Dataset`]): + Dataset for training. + value_model (`torch.nn.Module`): + Value model used to predict the value of a state. + data_collator ([`~transformers.DataCollatorWithPadding`], *optional*): + Data collator to batch and pad samples from the dataset. If `None`, a default data collator is created + using the `processing_class`. + eval_dataset ([`~datasets.Dataset`] or `dict` of [`~datasets.Dataset`], *optional*): + Dataset for evaluation. + optimizers (`tuple` of `torch.optim.Optimizer` and `torch.optim.lr_scheduler.LambdaLR`, *optional*, defaults to `(None, None)`): + Tuple containing the optimizer and the learning rate scheduler to use for training. If `None`, the + optimizer and the learning rate scheduler are created using the + [`~transformers.Trainer.create_optimizer_and_scheduler`] method. + callbacks (`list` of [`~transformers.TrainerCallback`], *optional*): + Callbacks to use during training. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration to use PEFT for training. If `None`, PEFT is not used. If provided, the policy `model` + will be wrapped with the specified PEFT adapter. + """ + + _tag_names = ["trl", "ppo"] + _name = "PPO" + _paper = { + "title": "Fine-Tuning Language Models from Human Preferences", + "id": "1909.08593", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{mziegler2019fine-tuning, + title = {{Fine-Tuning Language Models from Human Preferences}}, + author = {Daniel M. Ziegler and Nisan Stiennon and Jeffrey Wu and Tom B. Brown and Alec Radford and Dario Amodei and Paul F. Christiano and Geoffrey Irving}, + year = 2019, + eprint = {arXiv:1909.08593} + }"""), + } + + def __init__( + self, + args: PPOConfig, + processing_class: PreTrainedTokenizerBase | BaseImageProcessor | FeatureExtractionMixin | ProcessorMixin, + model: nn.Module, + ref_model: nn.Module | None, + reward_model: nn.Module, + train_dataset: Dataset, + value_model: nn.Module, + data_collator: DataCollatorWithPadding | None = None, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + # less commonly used + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + callbacks: list[TrainerCallback] | None = None, + peft_config: "PeftConfig | None" = None, + ) -> None: + if train_dataset is None: + raise ValueError("`train_dataset` is required") + + if ref_model is model: + raise ValueError( + "`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the " + "same as `model`, you must make a copy of it, or `None` if you use peft." + ) + + self.args = args + self.processing_class = processing_class + self.policy_model = model + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + # Define the collator if not provided + if data_collator is None: + data_collator = DataCollatorWithPadding(self.processing_class) + + # Handle stop token settings: update policy model's generation_config to use provided stop token + if args.stop_token and args.stop_token_id: + raise ValueError("You cannot set both `stop_token` and `stop_token_id`.") + elif args.stop_token: + if args.stop_token == "eos": + self.policy_model.generation_config.eos_token_id = self.stop_token_id = processing_class.eos_token_id + else: + raise ValueError( + f"Unknown `stop_token` {args.stop_token}. Allowed values are: `'eos'` and `None` (no stop token)." + ) + else: + self.policy_model.generation_config.eos_token_id = self.stop_token_id = args.stop_token_id # None or int + + # Check that the kl estimator is valid + if self.args.kl_estimator not in {"k1", "k3"}: + raise ValueError( + "kl_estimator must be either 'k1' (straightforward, unbiased) or 'k3' (lower variance, unbiased, " + "appears to be a strictly better estimator). See " + "[Approximating KL Divergence](http://joschu.net/blog/kl-approx.html) for details." + ) + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if isinstance(self.policy_model, PeftModel): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first " + "merge and unload the existing adapter, save the resulting base model, and then pass that base " + "model along with the new `peft_config` to the trainer." + ) + + # get peft model with the given config + self.policy_model = get_peft_model(self.policy_model, peft_config) + if args.bf16 and getattr(self.policy_model, "is_loaded_in_4bit", False): + peft_module_casting_to_bf16(self.policy_model) + + self.is_peft_model = is_peft_available() and isinstance(self.policy_model, PeftModel) + self.model_adapter_name = args.model_adapter_name + self.ref_adapter_name = args.ref_adapter_name + + if ref_model: + self.ref_model = ref_model + elif self.is_peft_model: + self.ref_model = None + else: + self.ref_model = create_reference_model(self.policy_model) + + self.reward_model = reward_model + self.train_dataset = train_dataset + self.train_dataset_len = len(train_dataset) + self.value_model = value_model + self.data_collator = data_collator + self.eval_dataset = eval_dataset + self.optimizer, self.lr_scheduler = optimizers + self.optimizer_cls_and_kwargs = None # needed for transformers >= 4.47 + + ######### + # calculate various batch sizes + ######### + if args.total_episodes is None: # allow the users to define episodes in terms of epochs. + args.total_episodes = int(args.num_train_epochs * self.train_dataset_len) + accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps) + self.accelerator = accelerator + args.world_size = accelerator.num_processes + args.local_batch_size = args.per_device_train_batch_size * args.gradient_accumulation_steps + args.micro_batch_size = int(args.per_device_train_batch_size * args.world_size) + args.batch_size = int(args.local_batch_size * args.world_size) + args.mini_batch_size = exact_div( + args.batch_size, args.num_mini_batches, "`batch_size` must be a multiple of `num_mini_batches`" + ) + args.local_mini_batch_size = exact_div( + args.local_batch_size, args.num_mini_batches, "`local_batch_size` must be a multiple of `num_mini_batches`" + ) + if args.whiten_rewards: + assert args.local_mini_batch_size >= 8, ( + f"Per-rank minibatch size {args.local_mini_batch_size} is insufficient for whitening" + ) + # `per_rank_rollout_batch_size` is our `args.local_batch_size` + # `per_rank_minibatch_size` is our `args.local_mini_batch_size` + args.num_total_batches = math.ceil( + args.total_episodes / args.batch_size + ) # we may train for more than `total_episodes` + self.local_seed = args.seed + accelerator.process_index * 100003 # Prime + if args.num_sample_generations > 0: + self.sample_generations_freq = max(1, args.num_total_batches // args.num_sample_generations) + self.local_dataloader_batch_size = args.local_batch_size + + ######### + # setup model, optimizer, and others + ######### + for module in [self.policy_model, self.ref_model, self.value_model, self.reward_model]: + if module is not None: + disable_dropout_in_model(module) + self.model = PolicyAndValueWrapper(self.policy_model, self.value_model) + self.model.config = self.policy_model.config # needed for pushing to hub + self.create_optimizer_and_scheduler( + num_training_steps=args.num_total_batches + ) # note that we are calling `self.lr_scheduler.step()` manually only at the batch level + + ######### + # trainer specifics + ######### + default_callbacks = DEFAULT_CALLBACKS + get_reporting_integration_callbacks(self.args.report_to) + self.callbacks = default_callbacks if callbacks is None else default_callbacks + callbacks + self.callback_handler = CallbackHandler( + self.callbacks, self.model, self.processing_class, self.optimizer, self.lr_scheduler + ) + self.add_callback(PrinterCallback if self.args.disable_tqdm else DEFAULT_PROGRESS_CALLBACK) + self.control = TrainerControl() + self.state = OnlineTrainerState( + is_local_process_zero=self.is_local_process_zero(), + is_world_process_zero=self.is_world_process_zero(), + stateful_callbacks=[ + cb for cb in self.callback_handler.callbacks + [self.control] if isinstance(cb, ExportableState) + ], + ) + self.current_flos = 0 + self.hp_search_backend = None + self.is_deepspeed_enabled = getattr(self.accelerator.state, "deepspeed_plugin", None) is not None + self.is_fsdp_enabled = getattr(self.accelerator.state, "fsdp_plugin", None) is not None + # Create distant repo and output directory if needed + self.hub_model_id = None + if self.args.push_to_hub: + self.init_hf_repo() + if self.args.should_save: + os.makedirs(self.args.output_dir, exist_ok=True) + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + ######### + # setup dataloader + ######### + self.dataloader = DataLoader( + self.train_dataset, + batch_size=self.local_dataloader_batch_size, + shuffle=True, + collate_fn=self.data_collator, + drop_last=True, # needed; otherwise the last batch will be of ragged shape + ) + # sync random states for DataLoader(shuffle=True) before `accelerator.prepare` + # see https://gist.github.com/vwxyzjn/2581bff1e48e185e0b85b6dfe1def79c + torch.manual_seed(args.seed) + self.model, self.optimizer, self.dataloader = accelerator.prepare(self.model, self.optimizer, self.dataloader) + torch.manual_seed(self.local_seed) # reset the local seed again + + self.eval_dataloader = DataLoader( + self.eval_dataset, + batch_size=args.per_device_eval_batch_size, + collate_fn=self.data_collator, + drop_last=True, + ) # no need to shuffle eval dataset + self.eval_dataloader = accelerator.prepare(self.eval_dataloader) + + if self.is_deepspeed_enabled: + self.reward_model = prepare_deepspeed(self.reward_model, accelerator) + + if self.ref_model is None: + if not self.is_peft_model: + raise ValueError("No reference model and model is not a Peft model.") + else: + self.ref_model = prepare_deepspeed(self.ref_model, accelerator) + else: + if self.ref_model is None: + if not self.is_peft_model: + raise ValueError("No reference model and model is not a Peft model.") + else: + self.ref_model = self.ref_model.to(self.accelerator.device) + self.reward_model = self.reward_model.to(self.accelerator.device) + + def get_train_dataloader(self) -> DataLoader: + return self.dataloader + + def get_eval_dataloader(self) -> DataLoader: + return self.eval_dataloader + + @contextmanager + def null_ref_context(self): + """Context manager for handling null reference model (that is, peft adapter manipulation).""" + with ( + self.accelerator.unwrap_model(self.model.policy).disable_adapter() + if self.is_peft_model and not self.ref_adapter_name + else nullcontext() + ): + if self.ref_adapter_name: + self.model.policy.set_adapter(self.ref_adapter_name) + yield + if self.ref_adapter_name: + self.model.policy.set_adapter(self.model_adapter_name or "default") + + def save_model(self, output_dir: str | None = None, _internal_call: bool = False): + backup_model = self.model + if hasattr(self.model, "policy"): + self.model = self.model.policy # save only the policy for inference + if self.is_deepspeed_enabled: + backup_deepspeed = self.deepspeed + self.deepspeed = self.model + + super().save_model(output_dir, _internal_call) + + self.model = backup_model + if self.is_deepspeed_enabled: + self.deepspeed = backup_deepspeed + + def train(self): + args = self.args + accelerator = self.accelerator + optimizer = self.optimizer + model = self.model + ref_policy = self.ref_model + reward_model = self.reward_model + processing_class = self.processing_class + dataloader = self.dataloader + device = accelerator.device + + def repeat_generator(): + while True: + yield from dataloader + + iter_dataloader = iter(repeat_generator()) + generation_kwargs = { + "max_new_tokens": args.response_length, + "temperature": (args.temperature + 1e-7), + "top_k": 0.0, + "top_p": 1.0, + "do_sample": True, + } + generation_config = GenerationConfig(**generation_kwargs) + + accelerator.print("===training policy===") + start_time = time.time() + stats_shape = (args.num_ppo_epochs, args.num_mini_batches, args.gradient_accumulation_steps) + approxkl_stats = torch.zeros(stats_shape, device=device) + pg_clipfrac_stats = torch.zeros(stats_shape, device=device) + pg_loss_stats = torch.zeros(stats_shape, device=device) + vf_loss_stats = torch.zeros(stats_shape, device=device) + vf_clipfrac_stats = torch.zeros(stats_shape, device=device) + entropy_stats = torch.zeros(stats_shape, device=device) + ratio_stats = torch.zeros(stats_shape, device=device) + model.train() + + # trainer state initialization + self.state.global_step = 0 + self.state.episode = 0 + self.state.max_steps = args.num_total_batches + self.state.num_train_epochs = args.total_episodes / self.train_dataset_len + # Compute absolute values for logging, eval, and save if given as ratio + if args.logging_steps is not None: + if args.logging_steps < 1: + self.state.logging_steps = math.ceil(self.state.max_steps * args.logging_steps) + else: + self.state.logging_steps = args.logging_steps + if args.eval_steps is not None: + if args.eval_steps < 1: + self.state.eval_steps = math.ceil(self.state.max_steps * args.eval_steps) + else: + self.state.eval_steps = args.eval_steps + if args.save_steps is not None: + if args.save_steps < 1: + self.state.save_steps = math.ceil(self.state.max_steps * args.save_steps) + else: + self.state.save_steps = args.save_steps + self.control = self.callback_handler.on_train_begin(args, self.state, self.control) + + # backward compatibility + if self.is_deepspeed_enabled: + self.deepspeed = self.model + self.model_wrapped = self.model + + for update in range(1, args.num_total_batches + 1): + self.state.episode += 1 * args.batch_size + data = next(iter_dataloader) + with torch.no_grad(): + queries = data["input_ids"].to(device) + context_length = queries.shape[1] + responses = [] + postprocessed_responses = [] + logprobs = [] + ref_logprobs = [] + scores = [] + sequence_lengths = [] + values = [] + with ( + unwrap_model_for_generation( + self.model, + self.accelerator, + gather_deepspeed3_params=self.args.ds3_gather_for_generation, + generation_kwargs=generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762 + ) as unwrapped_model + ): + query_responses, logitss = batch_generation( + unwrapped_model.policy, + queries, + args.local_rollout_forward_batch_size, + processing_class.pad_token_id, + generation_config, + ) + + for i in range(0, queries.shape[0], args.local_rollout_forward_batch_size): + query = queries[i : i + args.local_rollout_forward_batch_size] + query_response = query_responses[i : i + args.local_rollout_forward_batch_size] + response = query_response[:, context_length:] + logits = logitss[i : i + args.local_rollout_forward_batch_size] + logprob = selective_log_softmax(logits, response) + del logits + empty_cache() + + if ref_policy is None: + with self.null_ref_context(): + ref_output = forward(model.policy, query_response, processing_class.pad_token_id) + else: + ref_output = forward(ref_policy, query_response, processing_class.pad_token_id) + ref_logits = ref_output.logits[:, context_length - 1 : -1] + ref_logits /= args.temperature + 1e-7 + ref_logprob = selective_log_softmax(ref_logits, response) + del ref_output, ref_logits + empty_cache() + + # Response Processing 1. truncate response after the first occurrence of `stop_token_id` + postprocessed_response = response + if self.stop_token_id is not None: # handle the edge case when stop_token_id exists but is 0 + postprocessed_response = truncate_response( + self.stop_token_id, processing_class.pad_token_id, response + ) + + # Response Processing 2. run reward model on the truncated responses + postprocessed_query_response = torch.cat((query, postprocessed_response), 1) + sequence_length = first_true_indices(postprocessed_response == processing_class.pad_token_id) - 1 + unwrapped_value_model = accelerator.unwrap_model(model).value_model + full_value, _, _ = get_reward( + unwrapped_value_model, query_response, processing_class.pad_token_id, context_length + ) + value = full_value[:, context_length - 1 : -1].squeeze(-1) + _, score, _ = get_reward( + reward_model, postprocessed_query_response, processing_class.pad_token_id, context_length + ) + + responses.append(response) + postprocessed_responses.append(postprocessed_response) + logprobs.append(logprob) + ref_logprobs.append(ref_logprob) + sequence_lengths.append(sequence_length) + scores.append(score) + values.append(value) + responses = torch.cat(responses, 0) + postprocessed_responses = torch.cat(postprocessed_responses, 0) + logprobs = torch.cat(logprobs, 0) + ref_logprobs = torch.cat(ref_logprobs, 0) + sequence_lengths = torch.cat(sequence_lengths, 0) + scores = torch.cat(scores, 0) + values = torch.cat(values, 0) + del (logprob, ref_logprob, full_value, value, score, unwrapped_model) + empty_cache() + gc.collect() + + # Response Processing 3. Filter completion. Ensure that the sample contains stop_token_id + # Completions not passing that filter will receive a lower score. + contain_eos_token = torch.any(postprocessed_responses == self.processing_class.eos_token_id, dim=-1) + if self.args.missing_eos_penalty is not None: + scores[~contain_eos_token] -= self.args.missing_eos_penalty + # accelerator.print(f"{scores=}, {(contain_eos_token.sum() / len(contain_eos_token))=}") + + # be very careful with `padding_mask_p1`; see https://excalidraw.com/#json=LWnzG4w2k5DjF_EOL_xPt,e2w3a-hFJ_gX5vOfeyXGTw + response_idxs = torch.arange(responses.shape[1], device=responses.device).repeat(responses.shape[0], 1) + padding_mask = response_idxs > sequence_lengths.unsqueeze(1) + logprobs = torch.masked_fill(logprobs, padding_mask, INVALID_LOGPROB) + ref_logprobs = torch.masked_fill(ref_logprobs, padding_mask, INVALID_LOGPROB) + sequence_lengths_p1 = sequence_lengths + 1 + padding_mask_p1 = response_idxs > (sequence_lengths_p1.unsqueeze(1)) + values = torch.masked_fill(values, padding_mask_p1, 0) + + # 4. compute rewards + # Formula used by http://joschu.net/blog/kl-approx.html for the k1 and k3 estimators + logr = ref_logprobs - logprobs + kl = -logr if args.kl_estimator == "k1" else (logr.exp() - 1) - logr # Else statement is k3 + non_score_reward = -args.kl_coef * kl + rewards = non_score_reward.clone() + actual_start = torch.arange(rewards.size(0), device=rewards.device) + actual_end = torch.where(sequence_lengths_p1 < rewards.size(1), sequence_lengths_p1, sequence_lengths) + rewards[actual_start, actual_end] += scores + + # 5. whiten rewards + if args.whiten_rewards: + rewards = masked_whiten(rewards, mask=~padding_mask_p1, shift_mean=False) + rewards = torch.masked_fill(rewards, padding_mask_p1, 0) + + # 6. compute advantages and returns + lastgaelam = 0 + advantages_reversed = [] + gen_length = responses.shape[1] + for t in reversed(range(gen_length)): + nextvalues = values[:, t + 1] if t < gen_length - 1 else 0.0 + delta = rewards[:, t] + args.gamma * nextvalues - values[:, t] + lastgaelam = delta + args.gamma * args.lam * lastgaelam + advantages_reversed.append(lastgaelam) + advantages = torch.stack(advantages_reversed[::-1], axis=1) + returns = advantages + values + advantages = masked_whiten(advantages, ~padding_mask) + advantages = torch.masked_fill(advantages, padding_mask, 0) + empty_cache() + + # Do multiple epochs of PPO training, with a fresh random shuffle in each epoch + for ppo_epoch_idx in range(args.num_ppo_epochs): + b_inds = np.random.permutation(args.local_batch_size) + minibatch_idx = 0 + for mini_batch_start in range(0, args.local_batch_size, args.local_mini_batch_size): + mini_batch_end = mini_batch_start + args.local_mini_batch_size + mini_batch_inds = b_inds[mini_batch_start:mini_batch_end] + gradient_accumulation_idx = 0 + for micro_batch_start in range(0, args.local_mini_batch_size, args.per_device_train_batch_size): + with accelerator.accumulate(model): + micro_batch_end = micro_batch_start + args.per_device_train_batch_size + micro_batch_inds = mini_batch_inds[micro_batch_start:micro_batch_end] + mb_advantage = advantages[micro_batch_inds] + mb_responses = responses[micro_batch_inds] + mb_query_responses = query_responses[micro_batch_inds] + mb_logprobs = logprobs[micro_batch_inds] + mb_return = returns[micro_batch_inds] + mb_values = values[micro_batch_inds] + + output, vpred_temp = forward(model, mb_query_responses, processing_class.pad_token_id) + logits = output.logits[:, context_length - 1 : -1] + logits /= args.temperature + 1e-7 + new_logprobs = selective_log_softmax(logits, mb_responses) + new_logprobs = torch.masked_fill( + new_logprobs, padding_mask[micro_batch_inds], INVALID_LOGPROB + ) + vpred = vpred_temp[:, context_length - 1 : -1].squeeze(-1) + vpred = torch.masked_fill(vpred, padding_mask_p1[micro_batch_inds], 0) + vpredclipped = torch.clamp( + vpred, + mb_values - args.cliprange_value, + mb_values + args.cliprange_value, + ) + vf_losses1 = torch.square(vpred - mb_return) + vf_losses2 = torch.square(vpredclipped - mb_return) + vf_loss_max = torch.max(vf_losses1, vf_losses2) + vf_loss = 0.5 * masked_mean(vf_loss_max, ~padding_mask_p1[micro_batch_inds]) + vf_clipfrac = masked_mean( + (vf_losses2 > vf_losses1).float(), ~padding_mask_p1[micro_batch_inds] + ) + logprobs_diff = new_logprobs - mb_logprobs + ratio = torch.exp(logprobs_diff) + pg_losses = -mb_advantage * ratio + pg_losses2 = -mb_advantage * torch.clamp(ratio, 1.0 - args.cliprange, 1.0 + args.cliprange) + pg_loss_max = torch.max(pg_losses, pg_losses2) + pg_loss = masked_mean(pg_loss_max, ~padding_mask[micro_batch_inds]) + loss = pg_loss + args.vf_coef * vf_loss + accelerator.backward(loss) + optimizer.step() + optimizer.zero_grad() + with torch.no_grad(): + pg_clipfrac = masked_mean( + (pg_losses2 > pg_losses).float(), ~padding_mask[micro_batch_inds] + ) + prob_dist = torch.nn.functional.softmax(logits, dim=-1) + entropy = torch.logsumexp(logits, dim=-1) - torch.sum(prob_dist * logits, dim=-1) + approxkl = 0.5 * (logprobs_diff**2).mean() + approxkl_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = approxkl + pg_clipfrac_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = ( + pg_clipfrac + ) + pg_loss_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = pg_loss + vf_loss_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = vf_loss + vf_clipfrac_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = ( + vf_clipfrac + ) + entropy_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = entropy.mean() + ratio_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = ratio.mean() + gradient_accumulation_idx += 1 + minibatch_idx += 1 + # del everything and empty cache + # fmt: off + del ( + output, vpred_temp, logits, new_logprobs, vpred, vpredclipped, + vf_losses1, vf_losses2, vf_loss, vf_clipfrac, logprobs_diff, ratio, pg_losses, pg_losses2, pg_loss_max, + pg_loss, loss, pg_clipfrac, prob_dist, entropy, approxkl, mb_return, + mb_advantage, mb_values, mb_responses, mb_query_responses, mb_logprobs, + ) + # fmt: on + empty_cache() + with torch.no_grad(): + mean_kl = kl.sum(1).mean() + mean_entropy = (-logprobs).sum(1).mean() + mean_non_score_reward = non_score_reward.sum(1).mean() + rlhf_reward = mean_non_score_reward + scores.mean() + eps = int(self.state.episode / (time.time() - start_time)) + metrics = {} + metrics["eps"] = eps + metrics["objective/kl"] = self.accelerator.gather_for_metrics(mean_kl).mean().item() + metrics["objective/entropy"] = self.accelerator.gather_for_metrics(mean_entropy).mean().item() + metrics["objective/non_score_reward"] = ( + self.accelerator.gather_for_metrics(mean_non_score_reward).mean().item() + ) + metrics["objective/rlhf_reward"] = self.accelerator.gather_for_metrics(rlhf_reward).mean().item() + metrics["objective/scores"] = self.accelerator.gather_for_metrics(scores.mean()).mean().item() + metrics["policy/approxkl_avg"] = self.accelerator.gather_for_metrics(approxkl_stats).mean().item() + metrics["policy/clipfrac_avg"] = self.accelerator.gather_for_metrics(pg_clipfrac_stats).mean().item() + metrics["loss/policy_avg"] = self.accelerator.gather_for_metrics(pg_loss_stats).mean().item() + metrics["loss/value_avg"] = self.accelerator.gather_for_metrics(vf_loss_stats).mean().item() + metrics["val/clipfrac_avg"] = self.accelerator.gather_for_metrics(vf_clipfrac_stats).mean().item() + metrics["policy/entropy_avg"] = self.accelerator.gather_for_metrics(entropy_stats).mean().item() + metrics["val/ratio"] = self.accelerator.gather_for_metrics(ratio_stats).mean().item() + metrics["val/ratio_var"] = self.accelerator.gather_for_metrics(ratio_stats).var().item() + metrics["val/num_eos_tokens"] = (responses == processing_class.eos_token_id).sum().item() + metrics["lr"] = self.lr_scheduler.get_last_lr()[0] + metrics["episode"] = self.state.episode + self.state.epoch = self.state.episode / self.train_dataset_len # used by self.log + self.state.global_step += 1 + self.log(metrics) + + self.lr_scheduler.step() + self.control = self.callback_handler.on_step_end(args, self.state, self.control) + if self.control.should_save: + self._save_checkpoint(model, trial=None) + self.control = self.callback_handler.on_save(self.args, self.state, self.control) + del kl, mean_kl, mean_entropy, mean_non_score_reward, scores, metrics, non_score_reward + empty_cache() + gc.collect() + + if args.num_sample_generations > 0 and (update - 1) % self.sample_generations_freq == 0: + self.generate_completions(sampling=True) + empty_cache() + del ( + query_responses, + responses, + postprocessed_responses, + logprobs, + ref_logprobs, + values, + sequence_lengths, + contain_eos_token, + sequence_lengths_p1, + response_idxs, + padding_mask, + padding_mask_p1, + rewards, + actual_start, + actual_end, + advantages, + returns, + ) + empty_cache() + + # HF trainer specifics + self.control = self.callback_handler.on_train_end(args, self.state, self.control) + if self.control.should_save: + self._save_checkpoint(model, trial=None) + self.control = self.callback_handler.on_save(self.args, self.state, self.control) + + def generate_completions(self, sampling: bool = False): + if self.eval_dataset is None: + return # no eval set to sample from (pass eval_dataset and eval_strategy != "no" for sample generations) + args = self.args + processing_class = self.processing_class + generation_kwargs = { + "max_new_tokens": args.response_length, + "temperature": (0.01 + 1e-7), + "top_k": 0.0, + "top_p": 1.0, + "do_sample": True, + } + generation_config = GenerationConfig(**generation_kwargs) + + table = defaultdict(list) + with ( + unwrap_model_for_generation( + self.model, + self.accelerator, + gather_deepspeed3_params=self.args.ds3_gather_for_generation, + generation_kwargs=generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762 + ) as unwrapped_model + ): + for batch in self.eval_dataloader: + query = batch["input_ids"] + with torch.no_grad(): + context_length = query.shape[1] + query_response, _ = batch_generation( + unwrapped_model.policy, + query, + query.shape[0], + processing_class.pad_token_id, + generation_config, + ) + response = query_response[:, context_length:] + postprocessed_response = response + if self.stop_token_id is not None: # handle the edge case when stop_token_id exists but is 0 + postprocessed_response = truncate_response( + self.stop_token_id, processing_class.pad_token_id, response + ) + table["query"].extend( + gather_object(processing_class.batch_decode(query, skip_special_tokens=True)) + ) + table["model response"].extend( + gather_object(processing_class.batch_decode(postprocessed_response)) + ) + + postprocessed_query_response = torch.cat((query, postprocessed_response), 1) + _, score, _ = get_reward( + self.reward_model, postprocessed_query_response, processing_class.pad_token_id, context_length + ) + table["score"].extend(self.accelerator.gather_for_metrics(score).float().cpu().numpy()) + + if sampling: + break + df = pd.DataFrame(table) + + if self.accelerator.is_main_process: + if is_rich_available(): + print_rich_table(df.iloc[0 : 0 + 5]) + if "wandb" in args.report_to: + import wandb + + if wandb.run is not None: + wandb.log({"completions": wandb.Table(dataframe=df)}) + + if "comet_ml" in args.report_to: + log_table_to_comet_experiment( + name="completions.csv", + table=df, + ) + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/prm/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/prm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..210c474aa459261c71906d4e1b11994a08dddd4c --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/prm/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .prm_config import PRMConfig +from .prm_trainer import PRMTrainer + + +__all__ = ["PRMConfig", "PRMTrainer"] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/prm/prm_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/prm/prm_config.py new file mode 100644 index 0000000000000000000000000000000000000000..b6150c01b2e4739e027ee3072080c5f057478841 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/prm/prm_config.py @@ -0,0 +1,88 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class PRMConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`experimental.prm.PRMTrainer`]. + + This class includes only the parameters that are specific to PRM training. For a full list of training arguments, + please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may + differ from those in [`~transformers.TrainingArguments`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + max_length (`int` or `None`, *optional*, defaults to `1024`): + Maximum length of the sequences (prompt + completion) used for truncation. + max_completion_length (`int`, *optional*): + Maximum length of the completion used for truncation. The completion is the concatenation of the steps. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. + step_separator (`str`, *optional*, defaults to `"\n"`): + Separator used to separate each step of the reasoning process. + train_on_last_step_only (`bool`, *optional*, defaults to `False`): + Whether to train only on the last step. + dataset_num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `1e-5` instead of `5e-5`. + """ + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=1e-5, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + max_length: int | None = field( + default=1024, + metadata={"help": "Maximum length of the sequences (prompt + completion) used for truncation."}, + ) + max_completion_length: int | None = field( + default=None, + metadata={ + "help": "Maximum length of the completion used for truncation. The completion is the concatenation of the " + "steps." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the model and reference model."}, + ) + step_separator: str = field( + default="\n", + metadata={"help": "Separator used to separate each step of the reasoning process."}, + ) + train_on_last_step_only: bool = field( + default=False, + metadata={"help": "Whether to train only on the last step."}, + ) + dataset_num_proc: int | None = field( + default=None, + metadata={"help": "Number of processes to use for processing the dataset."}, + ) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/prm/prm_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/prm/prm_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..43ad64b849956c1fb48bec9e7d372fcbe560fa1b --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/prm/prm_trainer.py @@ -0,0 +1,371 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import textwrap +from collections.abc import Callable +from itertools import chain +from pathlib import Path + +import numpy as np +import torch +import torch.nn as nn +import transformers +from accelerate import PartialState +from accelerate.logging import get_logger +from accelerate.utils import is_peft_model +from datasets import Dataset, features +from packaging.version import Version +from transformers import ( + BaseImageProcessor, + DataCollator, + DataCollatorForTokenClassification, + FeatureExtractionMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, +) +from transformers.trainer_utils import EvalPrediction +from transformers.utils import is_peft_available + +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import disable_dropout_in_model +from ..utils import prepare_peft_model +from .prm_config import PRMConfig + + +if is_peft_available(): + from peft import PeftConfig + +logger = get_logger(__name__) + + +def compute_accuracy(eval_pred: EvalPrediction) -> dict[str, float]: + predictions, labels = eval_pred + if predictions.ndim == 3: + # Token classification task. Shapes are (batch_size, seq_len, num_labels) and (batch_size, seq_len) + # Used to compute the accuracy in the prm_trainer. + predictions = np.argmax(predictions, axis=2) + + # Flatten the predictions and labels to remove the ignored tokens. + predictions = np.array( + [ + p + for prediction, label in zip(predictions, labels, strict=True) + for (p, lbl) in zip(prediction, label, strict=True) + if lbl != -100 + ] + ) + labels = np.array([lbl for label in labels for lbl in label if lbl != -100]) + + else: + # Here, predictions is rewards_chosen and rewards_rejected. Shapes are (batch_size, 2) and (batch_size,) + # We want to see how much of the time rewards_chosen > rewards_rejected. + equal_mask = predictions[:, 0] == predictions[:, 1] + equal_predictions_count = int(equal_mask.sum()) + + if equal_predictions_count > 0: + # Before using the logger, the accelerate state must be initialized. It'susually the case when using this + # function inside a Trainer, but it may not be the case otherwise, in particular when unit testing. + PartialState() + + logger.warning( + f"There are {equal_predictions_count} out of {len(predictions[:, 0])} instances where the predictions " + "for both options are equal. These instances are ignored in the accuracy computation.", + ) + + # Filter out equal predictions + predictions = predictions[~equal_mask] + labels = labels[~equal_mask] + + # Use the remaining predictions for accuracy calculation + predictions = np.argmax(predictions, axis=1) + + accuracy = np.array(predictions == labels, dtype=float).mean().item() + return {"accuracy": accuracy} + + +class PRMTrainer(_BaseTrainer): + """ + Initialize PRMTrainer. + + Args: + model ([`~transformers.PreTrainedModel`]): + The model to train, preferably an `AutoModelForTokenClassification`. + args ([`experimental.prm.PRMConfig`]): + The arguments to use for training. + data_collator ([`~transformers.DataCollator`]): + The data collator to use for training. If None is specified, the default data collator + ([`~transformers.DataCollatorForTokenClassification`]) will be used which will pad the sequences to the + maximum length of the sequences in the batch, given a dataset of paired sequences. + train_dataset ([`~datasets.Dataset`]): + The dataset to use for training. + eval_dataset ([`~datasets.Dataset`]): + The dataset to use for evaluation. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + model_init (`Callable[[], transformers.PreTrainedModel]`): + The model initializer to use for training. If None is specified, the default model initializer will be + used. + compute_metrics (`Callable[[transformers.EvalPrediction], dict]`, *optional* defaults to `compute_accuracy`): + The metrics to use for evaluation. If no metrics are specified, the default metric (`compute_accuracy`) + will be used. + callbacks (`list[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + peft_config ([`~peft.PeftConfig`], *optional*): + The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in + a PEFT model. + """ + + _tag_names = ["trl", "prm"] + _name = "PRM" + _paper = { + "title": "Solving math word problems with process-and outcome-based feedback", + "id": "2211.14275", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{uesato2022solving, + title = {{Solving Math Word Problems With Process- and Outcome-Based Feedback}}, + author = {Uesato, Jonathan and Kushman, Nate and Kumar, Ramana and Song, Francis and Siegel, Noah and Wang, Lisa and Creswell, Antonia and Irving, Geoffrey and Higgins, Irina}, + year = 2022, + journal = {arXiv preprint arXiv:2211.14275} + }"""), + } + + def __init__( + self, + model: PreTrainedModel | nn.Module | None = None, + args: PRMConfig | None = None, + data_collator: DataCollator | None = None, + train_dataset: Dataset | None = None, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + processing_class: PreTrainedTokenizerBase + | BaseImageProcessor + | FeatureExtractionMixin + | ProcessorMixin + | None = None, + model_init: Callable[[], PreTrainedModel] | None = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = ( + None, + None, + ), + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + peft_config: "PeftConfig | None" = None, + ): + if train_dataset is None: + raise ValueError("`train_dataset` is required") + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if peft_config is not None or is_peft_model(model): + model = prepare_peft_model(model, peft_config, args) + + # Disable dropout in the model + if args.disable_dropout: + disable_dropout_in_model(model) + + if compute_metrics is None: + compute_metrics = compute_accuracy + + if data_collator is None: + if processing_class is None: + raise ValueError( + "A processing_class must be specified when using the default DataCollatorForTokenClassification" + ) + data_collator = DataCollatorForTokenClassification(processing_class) + + if "input_ids" not in train_dataset.column_names: + with PartialState().main_process_first(): + fn_kwargs = { + "tokenizer": processing_class, + "step_separator": args.step_separator, + "max_length": args.max_length, + "max_completion_length": args.max_completion_length, + "train_on_last_step_only": args.train_on_last_step_only, + } + train_fn_kwargs = {**fn_kwargs, "is_eval": False} + train_dataset = train_dataset.map( + self.tokenize_row, + fn_kwargs=train_fn_kwargs, + num_proc=args.dataset_num_proc, + remove_columns=train_dataset.features, + desc="Tokenizing train dataset", + features=features.Features( # needed to avoid map to cast labels to bool + { + "labels": features.Sequence(features.Value("int64")), + "input_ids": features.Sequence(features.Value("int64")), + } + ), + ) + + eval_fn_kwargs = {**fn_kwargs, "is_eval": True} + if eval_dataset is not None: + eval_dataset = eval_dataset.map( + self.tokenize_row, + fn_kwargs=eval_fn_kwargs, + num_proc=args.dataset_num_proc, + remove_columns=eval_dataset.features, + desc="Tokenizing eval dataset", + features=features.Features( # needed to avoid map to cast labels to bool + { + "labels": features.Sequence(features.Value("int64")), + "input_ids": features.Sequence(features.Value("int64")), + } + ), + ) + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + model_init=model_init, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + @staticmethod + def tokenize_row( + features, + tokenizer, + step_separator, + max_length, + max_completion_length, + train_on_last_step_only, + is_eval, + ): + r""" + Tokenize a row of the dataset. + + Args: + features (`dict[str, str]`): + Row of the dataset, should contain the keys `"prompt"`, `"completions"`, and `"labels"`. + tokenizer ([`~transformers.PreTrainedTokenizerBase`]): + Tokenizer used to process the data. + step_separator (`str`): + Separator between steps in the completion. + max_length (`int` or `None`): + Maximum length of the sequences (prompt + completion). If `None`, the sequences are not truncated. + max_completion_length (`int` or `None`): + Maximum length of the completion sequences. If `None`, the completion sequences are not truncated. + train_on_last_step_only (`bool`): + Whether to train only on the last step. If `True`, the labels are `-100` for all tokens except the last + token of the completion. + is_eval (`bool`): + Whether the function is used to tokenize samples from a training or an evaluation dataset. Used only if + `train_on_last_step_only` is set to `True`. + + Returns: + `dict[str, list[int]]`: + Tokenized sequences with the keys `"input_ids"`, and `"labels". + + Example: + ```python + >>> from transformers import AutoTokenizer + + >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B") + >>> features = { + ... "prompt": "Which number is larger, 9.8 or 9.11?", + ... "completions": ["11 is greater than 8.", "Hence, 9.11 > 9.8."], + ... "labels": [True, False], + ... } + >>> PRMTrainer.tokenize_row( + ... features, tokenizer, "\n", max_completion_length=None, train_on_last_step_only=False, is_eval=False + ... ) + {'input_ids': [23085, 1372, 374, 8131, 11, 220, 24, 13, 23, 476, 220, 24, 13, 16, 16, 30, 16, 16, 374, 7046, 1091, 220, 23, 13, 198, 39, 763, 11, 220, 24, 13, 16, 16, 861, 220, 24, 13, 23, 13, 198], + 'labels': [-100, -100, -100, -100, -100, -100, -100, -100, 1, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, 0]} + ``` + """ + # Tokenize the prompt and completions + prompt_ids = tokenizer(features["prompt"], add_special_tokens=False)["input_ids"] + completions_ids = [ + tokenizer(completion, add_special_tokens=False)["input_ids"] for completion in features["completions"] + ] + if train_on_last_step_only and not is_eval: + labels = [-100] * (len(features["labels"]) - 1) + [int(features["labels"][-1])] + else: + labels = [int(label) for label in features["labels"]] + + # Get the ID of the separator token and add it to the completions + separator_ids = tokenizer.encode(step_separator, add_special_tokens=False) + completions_ids = [completion + separator_ids for completion in completions_ids] + + # Create the label + labels = [ + [-100] * (len(completion) - 1) + [label] for completion, label in zip(completions_ids, labels, strict=True) + ] + + # Join the completions and labels steps + completion_ids = list(chain(*completions_ids)) + labels = list(chain(*labels)) + + if tokenizer.bos_token_id is not None: + prompt_ids = [tokenizer.bos_token_id] + prompt_ids + + # Truncate completion sequences + if max_completion_length is not None: + completion_ids = completion_ids[:max_completion_length] + labels = labels[:max_completion_length] + + input_ids = prompt_ids + completion_ids + labels = [-100] * len(prompt_ids) + labels + + if max_length is not None: + input_ids = input_ids[:max_length] + labels = labels[:max_length] + + return {"input_ids": input_ids, "labels": labels} + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdft/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..85a7818ae5c8b83264ffec56a58c52f344fa5c26 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdft/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .sdft_config import SDFTConfig +from .sdft_trainer import SDFTTrainer + + +__all__ = ["SDFTConfig", "SDFTTrainer"] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdft/loss_utils.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdft/loss_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5caa8c88713d2088c9c4c728dcea3e62236cf4e4 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdft/loss_utils.py @@ -0,0 +1,135 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Pure helper functions for self-distillation loss computation.""" + +import torch +import torch.nn.functional as F + +from ...trainer.utils import selective_log_softmax + + +def compute_divergence( + student_log_probs: torch.Tensor, + teacher_log_probs: torch.Tensor, + alpha: float, +) -> torch.Tensor: + if alpha == 0.0: + kl = F.kl_div(student_log_probs, teacher_log_probs, reduction="none", log_target=True) + elif alpha == 1.0: + kl = F.kl_div(teacher_log_probs, student_log_probs, reduction="none", log_target=True) + else: + alpha_t = torch.tensor(alpha, dtype=student_log_probs.dtype, device=student_log_probs.device) + mixture = torch.logsumexp( + torch.stack([student_log_probs + torch.log(1 - alpha_t), teacher_log_probs + torch.log(alpha_t)]), + dim=0, + ) + kl_teacher = F.kl_div(mixture, teacher_log_probs, reduction="none", log_target=True) + kl_student = F.kl_div(mixture, student_log_probs, reduction="none", log_target=True) + kl = torch.lerp(kl_student, kl_teacher, alpha) + return kl.sum(-1) + + +def add_tail_bucket(log_probs: torch.Tensor) -> torch.Tensor: + """Append a bucket holding the leftover probability mass to a top-k log-prob support. + + `log_probs` are true log-probabilities over a top-k subset, so they sum to the captured mass `P_topk <= 1`. This + appends one extra category equal to the tail mass `1 - P_topk`, yielding a distribution that sums to exactly 1. + """ + log_s = torch.logsumexp(log_probs, dim=-1, keepdim=True) + log_s = torch.clamp(log_s, max=-1e-7) + tail_log = torch.log(-torch.expm1(log_s)) + return torch.cat([log_probs, tail_log], dim=-1) + + +def apply_importance_sampling_clipping( + per_token_loss: torch.Tensor, + student_log_probs: torch.Tensor, + old_log_probs: torch.Tensor, + clip_coeff: float, +) -> torch.Tensor: + negative_approx_kl = (student_log_probs - old_log_probs).detach() + negative_approx_kl = torch.clamp(negative_approx_kl, min=-20.0, max=20.0) + ratio = torch.exp(negative_approx_kl).clamp(max=clip_coeff) + return per_token_loss * ratio + + +def compute_topk_self_distillation_loss( + student_logits: torch.Tensor, + teacher_logits: torch.Tensor, + *, + distillation_topk: int, + distillation_alpha: float, + distillation_add_tail: bool, +) -> torch.Tensor: + """Compute distillation loss on the student's top-k token support. + + The student's top-k logits define the support. The teacher distribution is projected onto the same token indices. + The selected support is then either renormalized or augmented with a tail bucket before the divergence is computed. + """ + student_logsumexp = torch.logsumexp(student_logits, dim=-1, keepdim=True) + topk_student_logits, topk_indices = torch.topk(student_logits, k=distillation_topk, dim=-1) + topk_student_log_probs = topk_student_logits - student_logsumexp + + teacher_logsumexp = torch.logsumexp(teacher_logits, dim=-1, keepdim=True) + topk_teacher_logits = torch.gather(teacher_logits, dim=-1, index=topk_indices) + topk_teacher_log_probs = topk_teacher_logits - teacher_logsumexp + + # Top-k log-probs sum to the captured mass P_topk <= 1; the rest (1 - P_topk) is the "tail". + if distillation_add_tail: + # Lump the tail into one bucket so the divergence approximates the full-vocab divergence. + topk_student_log_probs = add_tail_bucket(topk_student_log_probs) + topk_teacher_log_probs = add_tail_bucket(topk_teacher_log_probs) + else: + # Drop the tail and renormalize the top-k to sum to 1: divergence over the top-k conditional only. + topk_student_log_probs = topk_student_log_probs - torch.logsumexp(topk_student_log_probs, dim=-1, keepdim=True) + topk_teacher_log_probs = topk_teacher_log_probs - torch.logsumexp(topk_teacher_log_probs, dim=-1, keepdim=True) + + return compute_divergence(topk_student_log_probs, topk_teacher_log_probs, distillation_alpha) + + +def compute_full_logit_self_distillation_loss( + student_logits: torch.Tensor, + teacher_logits: torch.Tensor, + *, + distillation_alpha: float, +) -> torch.Tensor: + """Compute full-vocabulary self-distillation loss between student and teacher logits.""" + student_log_probs = torch.log_softmax(student_logits, dim=-1) + teacher_log_probs = torch.log_softmax(teacher_logits, dim=-1) + return compute_divergence(student_log_probs, teacher_log_probs, distillation_alpha) + + +def compute_sampled_token_self_distillation_loss( + student_logits: torch.Tensor, + teacher_logits: torch.Tensor, + completion_ids: torch.Tensor, + *, + distillation_alpha: float, +) -> torch.Tensor: + """Compute token-level self-distillation loss only on the sampled completion tokens. + + This path compares student and teacher log-probabilities on the realized completion tokens rather than over a + larger token support. + """ + if distillation_alpha != 1.0: + raise ValueError( + "Only reverse KL (alpha=1.0) is supported for token-level distillation when " + f"`distillation_mode='sampled_token'`, got alpha={distillation_alpha}" + ) + + student_per_token_logps = selective_log_softmax(student_logits, completion_ids) + teacher_per_token_logps = selective_log_softmax(teacher_logits, completion_ids) + log_ratio = student_per_token_logps - teacher_per_token_logps + return log_ratio.detach() * student_per_token_logps diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdft/sdft_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdft/sdft_config.py new file mode 100644 index 0000000000000000000000000000000000000000..b21e3dbc60c782e385bdac882913691285ee19d8 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdft/sdft_config.py @@ -0,0 +1,472 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any, Literal + +from transformers import TrainingArguments + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class SDFTConfig(_BaseConfig): + r""" + Configuration class for the [`SDFTTrainer`]. + + Parameters: + > Parameters that control the SDFT loss + + distillation_alpha (`float`, *optional*, defaults to `0.5`): + Divergence interpolation coefficient for SDFT top-k logit distillation. + distillation_mode (`Literal["sampled_token", "full_logits", "topk_logits"]`, *optional*, defaults to `"topk_logits"`): + Distillation objective mode. SDFT defaults to top-k logit distillation. + distillation_topk (`int`, *optional*, defaults to `100`): + Number of top tokens used by the default SDFT top-k logit objective. + distillation_is_clip (`float`, *optional*, defaults to `2.0`): + Clipping coefficient for importance sampling in self-distillation. `None` disables clipping. + distillation_add_tail (`bool`, *optional*, defaults to `False`): + Whether to add a tail bucket for non-top-k probability mass. + num_loss_tokens_to_skip (`int`, *optional*, defaults to `0`): + Number of initial completion tokens to exclude from the distillation loss. + + > Parameters that control the teacher + + teacher_model_kind (`str`, *optional*, defaults to `"base"`): + Semantic teacher choice for SDFT. `base` uses the initial student, `live` uses the current student, and + `ema` uses an exponentially averaged teacher. + teacher_update_rate (`float`, *optional*, defaults to `0.05`): + EMA update rate used when `teacher_model_kind="ema"`. A value of `1.0` reduces the update to a hard + overwrite, periodically resyncing the teacher to the current student weights. + teacher_sync_steps (`int`, *optional*, defaults to `1`): + Number of optimizer steps between teacher updates. + + > Parameters that control teacher-conditioned generation + + generate_from_teacher (`bool`, *optional*, defaults to `False`): + Whether on-policy generation should use the teacher-conditioned prompt instead of the student prompt. + teacher_prompt_template (`str`, *optional*, defaults to `"{prompt}\n\n{privileged_context}"`): + Template used to combine the student prompt and privileged context into the teacher prompt. + + > Parameters that control the model + + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments for `transformers.AutoModelForCausalLM.from_pretrained`, used when the `model` argument + of the `SDFTTrainer` is provided as a string. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to + [`~transformers.AutoModelForCausalLM.from_pretrained`] and [`~transformers.AutoProcessor.from_pretrained`], + for both the student and teacher. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the student and teacher models. + + > Parameters that control data preprocessing + + remove_unused_columns (`bool`, *optional*, defaults to `False`): + Whether to only keep the columns required by the trainer in the dataset. Keep this to `False` if you + provide extra columns (such as `privileged_context`) that the trainer needs. + max_prompt_length (`int`, *optional*, defaults to `512`): + Maximum prompt length. Longer prompts are truncated from the left. + shuffle_dataset (`bool`, *optional*, defaults to `True`): + Whether to shuffle the training dataset. + + > Parameters that control generation + + num_generations (`int`, *optional*, defaults to `8`): + Number of generations to sample. The effective batch size (num_processes * per_device_batch_size * + gradient_accumulation_steps) must be evenly divisible by this value. + num_generations_eval (`int`, *optional*): + Number of generations to sample during evaluation. This allows using fewer generations during evaluation to + save computation. If `None`, uses the value of `num_generations`. + max_completion_length (`int`, *optional*, defaults to `256`): + Maximum length of the generated completion. + temperature (`float`, *optional*, defaults to `1.0`): + Temperature for sampling. The higher the temperature, the more random the completions. + top_p (`float`, *optional*, defaults to `1.0`): + Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to 1.0 + to consider all tokens. + top_k (`int`, *optional*, defaults to `0`): + Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is + disabled and all tokens are considered. + min_p (`float`, *optional*): + Minimum token probability, which will be scaled by the probability of the most likely token. It must be a + value between 0.0 and 1.0. Typical values are in the 0.01-0.2 range. + repetition_penalty (`float`, *optional*, defaults to `1.0`): + Float that penalizes new tokens based on whether they appear in the prompt and the generated text so far. + Values > 1.0 encourage the model to use new tokens, while values < 1.0 encourage the model to repeat + tokens. + cache_implementation (`str`, *optional*): + Implementation of the cache method for faster generation when use_vllm is set to False. + generation_kwargs (`dict[str, Any]`, *optional*): + Additional keyword arguments to pass to `GenerationConfig` (if using transformers) or `SamplingParams` (if + using vLLM) when sampling completions. This can be used to further customize the generation behavior, such + as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that conflict with the other generation + parameters (like `min_p`, `top_p`, etc.), they will override them. + chat_template_kwargs (`dict[str, Any]`, *optional*): + Additional keyword arguments to pass to the `apply_chat_template` function when generating completions. + ds3_gather_for_generation (`bool`, *optional*, defaults to `True`): + This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation, + improving generation speed. However, disabling this option allows training models that exceed the VRAM + capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible + with vLLM generation. + + > Parameters that control generation acceleration powered by vLLM + + use_vllm (`bool`, *optional*, defaults to `False`): + Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for generation + instead of the default model.generate(). Requires `vllm` to be installed. + use_teacher_server (`bool`, *optional*, defaults to `False`): + Compute teacher logprobs from the running vLLM generation server instead of a local teacher forward. Only + supported for `teacher_model_kind='live'` with `use_vllm=True` and `vllm_mode='server'`, and + `distillation_mode` in {'sampled_token', 'topk_logits'} (the server returns the teacher's top-k logprobs, + not the full vocabulary; `topk_logits` distills over the teacher's own top-k support). + vllm_mode (`str`, *optional*, defaults to `"colocate"`): + Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `'server'` or + `'colocate'`. `'server'`: The trainer will send generation requests to a separate vLLM server. Make sure a + TRL vLLM server is running (start with `trl vllm-serve`). `'colocate'`: vLLM will run in the same process + and share the training GPUs. This avoids the need for a separate server but may cause resource contention + with training. + vllm_model_impl (`str`, *optional*, defaults to `"vllm"`): + Model implementation to use for vLLM. Must be one of `transformers` or `vllm`. `transformers`: Use the + `transformers` backend for model implementation. `vllm`: Use the `vllm` library for model implementation. + vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`): + Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but + waking the engine adds host–device transfer latency. + vllm_server_base_url (`str`, *optional*): + Base URL for the vLLM server (e.g., 'http://localhost:8000'). If provided, `vllm_server_host` and + `vllm_server_port` are ignored. + vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`): + Host of the vLLM server to connect to. Ignored if vllm_server_base_url is provided. + vllm_server_port (`int`, *optional*, defaults to `8000`): + Port of the vLLM server to connect to. Ignored if vllm_server_base_url is provided. + vllm_group_port (`int`, *optional*, defaults to `51216`): + Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port + is occupied, there is no need to change it. + vllm_server_timeout (`float`, *optional*, defaults to `240.0`): + Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up after the + timeout, a `ConnectionError` is raised. + vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`): + Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set to + `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when + launching the vLLM server via the `--vllm_tensor_parallel_size` flag. + vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.3`): + Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set to + `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when + launching the vLLM server via the `--vllm_gpu_memory_utilization` flag. + vllm_max_model_length (`int`, *optional*): + Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus + `max_completion_length`; if omitted, it is inferred from the model config. + + > Parameters that control the training + + num_iterations (`int`, *optional*, defaults to `1`): + Number of iterations per batch (denoted as μ in the algorithm). + generation_batch_size (`int`, *optional*): + Batch size to use for generation. If `None`, it defaults to the effective training batch size: + `per_device_train_batch_size * num_processes * steps_per_generation`. + steps_per_generation (`int`, *optional*): + Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`. + """ + + _VALID_DICT_FIELDS = TrainingArguments._VALID_DICT_FIELDS + ["model_init_kwargs"] + + model_init_kwargs: dict[str, Any] | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `transformers.AutoModelForCausalLM.from_pretrained`, used when the `model` argument of the `SDFTTrainer` is provided as a string." + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. " + "Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoProcessor.from_pretrained`, for both the " + "student and teacher." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the student and teacher models."}, + ) + remove_unused_columns: bool = field( + default=False, + metadata={ + "help": "Whether to only keep the columns required by the trainer in the dataset. Keep this to `False` if you provide extra columns (such as `privileged_context`) that the trainer needs." + }, + ) + max_prompt_length: int | None = field( + default=512, + metadata={"help": "Maximum prompt length. Longer prompts are truncated from the left."}, + ) + num_generations: int = field( + default=8, + metadata={ + "help": "Number of generations to sample. The effective batch size (num_processes * per_device_batch_size * gradient_accumulation_steps) must be evenly divisible by this value." + }, + ) + num_generations_eval: int | None = field( + default=None, + metadata={ + "help": "Number of generations to sample during evaluation. This allows using fewer generations during evaluation to save computation. If `None`, uses the value of `num_generations`." + }, + ) + max_completion_length: int | None = field( + default=256, + metadata={"help": "Maximum length of the generated completion."}, + ) + ds3_gather_for_generation: bool = field( + default=True, + metadata={ + "help": "This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation, improving generation speed. However, disabling this option allows training models that exceed the VRAM capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible with vLLM generation." + }, + ) + shuffle_dataset: bool = field( + default=True, + metadata={"help": "Whether to shuffle the training dataset."}, + ) + generation_batch_size: int | None = field( + default=None, + metadata={ + "help": "Batch size to use for generation. If `None`, it defaults to the effective training batch size: `per_device_train_batch_size * num_processes * steps_per_generation`." + }, + ) + steps_per_generation: int | None = field( + default=None, + metadata={"help": "Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`."}, + ) + temperature: float = field( + default=1.0, + metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."}, + ) + top_p: float = field( + default=1.0, + metadata={ + "help": "Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to 1.0 to consider all tokens." + }, + ) + top_k: int = field( + default=0, + metadata={ + "help": "Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is disabled and all tokens are considered." + }, + ) + min_p: float | None = field( + default=None, + metadata={ + "help": "Minimum token probability, which will be scaled by the probability of the most likely token. It must be a value between 0.0 and 1.0. Typical values are in the 0.01-0.2 range." + }, + ) + generation_kwargs: dict[str, Any] | None = field( + default=None, + metadata={ + "help": "Additional keyword arguments to pass to `GenerationConfig` (if using transformers) or `SamplingParams` (if using vLLM) when sampling completions. This can be used to further customize the generation behavior, such as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that conflict with the other generation parameters (like `min_p`, `top_p`, etc.), they will override them." + }, + ) + chat_template_kwargs: dict[str, Any] | None = field( + default=None, + metadata={ + "help": "Additional keyword arguments to pass to the `apply_chat_template` function when generating completions." + }, + ) + repetition_penalty: float = field( + default=1.0, + metadata={ + "help": "Float that penalizes new tokens based on whether they appear in the prompt and the generated text so far. Values > 1.0 encourage the model to use new tokens, while values < 1.0 encourage the model to repeat tokens." + }, + ) + cache_implementation: str | None = field( + default=None, + metadata={"help": "Implementation of the cache method for faster generation when use_vllm is set to False."}, + ) + use_vllm: bool = field( + default=False, + metadata={ + "help": "Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for generation instead of the default model.generate(). Requires `vllm` to be installed." + }, + ) + use_teacher_server: bool = field( + default=False, + metadata={ + "help": "Compute teacher logprobs from the running vLLM generation server instead of a local teacher " + "forward. Only supported for `teacher_model_kind='live'` with `use_vllm=True` and `vllm_mode='server'`, " + "and `distillation_mode` in {'sampled_token', 'topk_logits'} (the server returns the teacher's top-k " + "logprobs, not the full vocabulary; `topk_logits` distills over the teacher's own top-k support)." + }, + ) + vllm_mode: str = field( + default="colocate", + metadata={ + "help": "Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `'server'` or `'colocate'`. `'server'`: The trainer will send generation requests to a separate vLLM server. Make sure a TRL vLLM server is running (start with `trl vllm-serve`). `'colocate'`: vLLM will run in the same process and share the training GPUs. This avoids the need for a separate server but may cause resource contention with training." + }, + ) + vllm_model_impl: str = field( + default="vllm", + metadata={ + "help": "Model implementation to use for vLLM. Must be one of `transformers` or `vllm`. `transformers`: Use the `transformers` backend for model implementation. `vllm`: Use the `vllm` library for model implementation." + }, + ) + vllm_enable_sleep_mode: bool = field( + default=False, + metadata={ + "help": "Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but waking the engine adds host–device transfer latency." + }, + ) + vllm_server_base_url: str | None = field( + default=None, + metadata={ + "help": "Base URL for the vLLM server (e.g., 'http://localhost:8000'). If provided, `vllm_server_host` and `vllm_server_port` are ignored." + }, + ) + vllm_server_host: str = field( + default="0.0.0.0", + metadata={"help": "Host of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."}, + ) + vllm_server_port: int = field( + default=8000, + metadata={"help": "Port of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."}, + ) + vllm_group_port: int = field( + default=51216, + metadata={ + "help": "Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port is occupied, there is no need to change it." + }, + ) + vllm_server_timeout: float = field( + default=240.0, + metadata={ + "help": "Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up after the timeout, a `ConnectionError` is raised." + }, + ) + vllm_tensor_parallel_size: int = field( + default=1, + metadata={ + "help": "Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when launching the vLLM server via the `--vllm_tensor_parallel_size` flag." + }, + ) + vllm_gpu_memory_utilization: float = field( + default=0.3, + metadata={ + "help": "Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when launching the vLLM server via the `--vllm_gpu_memory_utilization` flag." + }, + ) + vllm_max_model_length: int | None = field( + default=None, + metadata={ + "help": "Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus `max_completion_length`; if omitted, it is inferred from the model config." + }, + ) + num_iterations: int = field( + default=1, + metadata={"help": "Number of iterations per batch (denoted as μ in the algorithm)."}, + ) + teacher_model_kind: str = field( + default="base", + metadata={ + "help": "Semantic teacher choice for SDFT. `base` uses the initial student, `live` uses the current " + "student, and `ema` uses an exponentially averaged teacher." + }, + ) + teacher_update_rate: float = field( + default=0.05, + metadata={ + "help": 'EMA update rate used when `teacher_model_kind="ema"`. A value of `1.0` reduces the update ' + "to a hard overwrite, periodically resyncing the teacher to the current student weights." + }, + ) + teacher_sync_steps: int = field( + default=1, + metadata={"help": "Number of optimizer steps between teacher updates."}, + ) + distillation_alpha: float = field( + default=0.5, + metadata={"help": "Divergence interpolation coefficient for SDFT top-k logit distillation."}, + ) + distillation_mode: Literal["sampled_token", "full_logits", "topk_logits"] = field( + default="topk_logits", + metadata={"help": "Distillation objective mode. SDFT defaults to top-k logit distillation."}, + ) + distillation_topk: int | None = field( + default=100, + metadata={"help": "Number of top tokens used by the default SDFT top-k logit objective."}, + ) + distillation_is_clip: float | None = field( + default=2.0, + metadata={ + "help": "Clipping coefficient for importance sampling in self-distillation. `None` disables clipping." + }, + ) + distillation_add_tail: bool = field( + default=False, + metadata={"help": "Whether to add a tail bucket for non-top-k probability mass."}, + ) + generate_from_teacher: bool = field( + default=False, + metadata={ + "help": "Whether on-policy generation should use the teacher-conditioned prompt instead of the student prompt." + }, + ) + teacher_prompt_template: str = field( + default="{prompt}\n\n{privileged_context}", + metadata={ + "help": "Template used to combine the student prompt and privileged context into the teacher prompt." + }, + ) + num_loss_tokens_to_skip: int = field( + default=0, + metadata={"help": "Number of initial completion tokens to exclude from the distillation loss."}, + ) + + def __post_init__(self): + super().__post_init__() + if self.distillation_mode == "sampled_token" and self.distillation_alpha != 1.0: + raise ValueError( + "`distillation_mode='sampled_token'` only supports reverse KL, so it requires " + f"`distillation_alpha=1.0`, got {self.distillation_alpha}." + ) + num_processes = self.world_size + if self.generation_batch_size is None and self.steps_per_generation is None: + self.steps_per_generation = self.gradient_accumulation_steps + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + elif self.generation_batch_size is not None and self.steps_per_generation is None: + global_batch_size = self.per_device_train_batch_size * num_processes + if self.generation_batch_size % global_batch_size != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by the global batch size ({global_batch_size})." + ) + self.steps_per_generation = self.generation_batch_size // global_batch_size + elif self.generation_batch_size is None and self.steps_per_generation is not None: + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + else: + raise ValueError("'generation_batch_size' and 'steps_per_generation' can not both be configured") + + if self.generation_batch_size % self.num_generations != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by num_generations ({self.num_generations})." + ) + + if self.do_eval and self.eval_strategy != "no": + num_generations_eval = self.num_generations_eval or self.num_generations + if (self.per_device_eval_batch_size * num_processes) % num_generations_eval != 0: + raise ValueError( + f"The global eval batch size ({self.per_device_eval_batch_size} * {num_processes}) must be " + f"divisible by the number of generations used for evaluation ({num_generations_eval})." + ) + + if ( + "{prompt}" not in self.teacher_prompt_template + or "{privileged_context}" not in self.teacher_prompt_template + ): + raise ValueError( + "teacher_prompt_template must contain both `{prompt}` and `{privileged_context}` placeholders" + ) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdft/sdft_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdft/sdft_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..1f68ad8467b8345bf67e509b17d8ae1f064c8857 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdft/sdft_trainer.py @@ -0,0 +1,1311 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import textwrap +from collections import defaultdict +from contextlib import nullcontext +from dataclasses import dataclass +from functools import partial +from typing import Any + +import datasets +import torch +from accelerate.logging import get_logger +from accelerate.utils import is_peft_model +from datasets import Dataset, IterableDataset +from torch import nn +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from torch.utils.data import DataLoader, Sampler +from transformers import ( + AutoProcessor, + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, +) +from transformers.trainer_utils import seed_worker +from transformers.utils import is_datasets_available, is_liger_kernel_available, is_peft_available + +from ...data_utils import is_conversational +from ...models import prepare_deepspeed, prepare_fsdp, unwrap_model_for_generation +from ...models.utils import _ForwardRedirection +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import ( + RepeatSampler, + create_model_from_path, + disable_dropout_in_model, + get_config_model_id, + identity, + pad, + selective_log_softmax, + split_tensor_dict, + use_adapter, +) +from ..utils import prepare_peft_model +from .loss_utils import ( + add_tail_bucket, + apply_importance_sampling_clipping, + compute_divergence, + compute_full_logit_self_distillation_loss, + compute_sampled_token_self_distillation_loss, + compute_topk_self_distillation_loss, +) +from .sdft_config import SDFTConfig +from .teacher_sync import PEFTAdapterEMACallback, SyncTeacherModelCallback, is_pure_lora_training + + +if is_peft_available(): + from peft import PeftConfig + +if is_liger_kernel_available(): + from liger_kernel.chunked_loss import LigerFusedLinearJSDLoss + + +logger = get_logger(__name__) + + +TrainingBatch = dict[str, torch.Tensor | Any] + + +def build_teacher_request_inputs( + input_ids: torch.Tensor, + attention_mask: torch.Tensor, + prompt_attention_mask: torch.Tensor, +) -> tuple[list[list[int]], list[int], list[int]]: + """Trim padded batch tensors into per-sample (prompt+completion) sequences for teacher-server requests.""" + if input_ids.shape != attention_mask.shape: + raise ValueError( + f"input_ids and attention_mask must have the same shape, got {input_ids.shape} and {attention_mask.shape}." + ) + + input_ids_cpu = input_ids.detach().cpu() + attention_mask_cpu = attention_mask.detach().cpu().bool() + prompt_lengths = prompt_attention_mask.detach().cpu().sum(dim=1).to(torch.long) + + trimmed_input_ids: list[list[int]] = [] + prompt_lengths_list: list[int] = [] + completion_lengths_list: list[int] = [] + for row, mask, prompt_length in zip(input_ids_cpu, attention_mask_cpu, prompt_lengths, strict=True): + trimmed_row = row[mask] + prompt_len = int(prompt_length.item()) + if prompt_len < 0 or prompt_len > trimmed_row.numel(): + raise ValueError( + f"Invalid prompt length {prompt_len} for trimmed sequence of length {trimmed_row.numel()}." + ) + trimmed_input_ids.append(trimmed_row.tolist()) + prompt_lengths_list.append(prompt_len) + completion_lengths_list.append(int(trimmed_row.numel()) - prompt_len) + return trimmed_input_ids, prompt_lengths_list, completion_lengths_list + + +@dataclass +class DistillationLogits: + """Aligned logits and masks used to compute a self-distillation objective.""" + + completion_ids: torch.Tensor + loss_mask: torch.Tensor + student_logits: torch.Tensor + teacher_logits: torch.Tensor + + +def _extract_last_user_text(messages: list[dict[str, Any]]) -> str: + """Extract the text content from the last user message in a conversational prompt.""" + last_message = messages[-1] + if last_message.get("role") != "user": + raise ValueError( + f"Self-distillation teacher prompt construction expects the conversation to end with a user turn, " + f"but the last message has role '{last_message.get('role')}'. " + f"Prompts ending with assistant prefills or tool turns are not supported." + ) + content = last_message.get("content", "") + if isinstance(content, list): + return " ".join(part.get("text", "") for part in content if part.get("type") == "text") + return content + + +class DemonstrationTeacherContextBuilder: + """Builds student and teacher contexts from prompts plus privileged context""" + + def __init__(self, trainer): + self.trainer = trainer + + def _stringify_privileged_context(self, privileged_context: Any) -> str: + if privileged_context is None: + raise ValueError( + "`privileged_context` must not be None for self-distillation teacher prompt construction." + ) + if isinstance(privileged_context, str): + return privileged_context + if isinstance(privileged_context, list) and privileged_context and isinstance(privileged_context[0], dict): + chunks = [] + for message in privileged_context: + content = message.get("content", "") + if isinstance(content, list): + text = " ".join(part.get("text", "") for part in content if part.get("type") == "text") + else: + text = str(content) + if text: + chunks.append(text) + return "\n".join(chunks) + return str(privileged_context) + + def _compose_teacher_prompt(self, prompt: Any, privileged_context: Any) -> Any: + privileged_text = self._stringify_privileged_context(privileged_context) + if isinstance(prompt, list): + system_messages = prompt[:-1] + prompt_text = _extract_last_user_text(prompt) + teacher_text = self.trainer.args.teacher_prompt_template.format( + prompt=prompt_text, + privileged_context=privileged_text, + ) + return system_messages + [{"role": "user", "content": teacher_text}] + return self.trainer.args.teacher_prompt_template.format(prompt=prompt, privileged_context=privileged_text) + + def select_generation_prompts(self, prompts: list[Any], privileged_contexts: list[Any]) -> list[Any]: + return [ + self._compose_teacher_prompt(prompt, privileged_context) + for prompt, privileged_context in zip(prompts, privileged_contexts, strict=True) + ] + + def build( + self, + prompts: list[Any], + privileged_contexts: list[Any], + completion_ids: torch.Tensor, + completion_mask: torch.Tensor, + ) -> dict[str, torch.Tensor]: + teacher_prompts = [ + self._compose_teacher_prompt(prompt, privileged_context) + for prompt, privileged_context in zip(prompts, privileged_contexts, strict=True) + ] + teacher_prompt_ids_list = self.trainer._tokenize_prompts(teacher_prompts) + device = completion_ids.device + teacher_prompt_ids = [torch.tensor(ids) for ids in teacher_prompt_ids_list] + teacher_prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in teacher_prompt_ids] + teacher_prompt_ids = pad( + teacher_prompt_ids, padding_value=self.trainer._tokenizer.pad_token_id, padding_side="left" + ).to(device=device) + teacher_prompt_mask = pad(teacher_prompt_mask, padding_value=0, padding_side="left").to(device=device) + teacher_input_ids = torch.cat([teacher_prompt_ids, completion_ids], dim=1) + teacher_attention_mask = torch.cat([teacher_prompt_mask, completion_mask], dim=1) + return { + "teacher_input_ids": teacher_input_ids, + "teacher_attention_mask": teacher_attention_mask, + } + + +class SDFTTrainer(_BaseTrainer): + """Trainer for SDFT-style on-policy self-distillation with explicit teacher prompts.""" + + _tag_names = ["trl", "sdft"] + _name = "SDFT" + config_cls = SDFTConfig + # docstyle-ignore + _paper = { + "title": "Self-Distillation Enables Continual Learning", + "id": "2601.19897", + "citation": textwrap.dedent("""\ + @article{shenfeld2026selfdistillation, + title = {{Self-Distillation Enables Continual Learning}}, + author = {Idan Shenfeld and Mehul Damani and Jonas H\\"ubotter and Pulkit Agrawal}, + year = 2026, + eprint = {arXiv:2601.19897} + }"""), + } + + def __init__( + self, + model: str | PreTrainedModel | nn.Module, + args: SDFTConfig | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + peft_config: PeftConfig | None = None, + ): + if isinstance(train_dataset, IterableDataset): + raise NotImplementedError("Iterable datasets are not yet supported in SDFTTrainer.") + if isinstance(eval_dataset, IterableDataset) or ( + isinstance(eval_dataset, dict) and any(isinstance(ds, IterableDataset) for ds in eval_dataset.values()) + ): + raise NotImplementedError("Iterable eval datasets are not yet supported in SDFTTrainer.") + + self.num_loss_tokens_to_skip = args.num_loss_tokens_to_skip + self.teacher_context_builder = DemonstrationTeacherContextBuilder(self) + + if train_dataset is None: + raise ValueError("`train_dataset` is required") + + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + model = create_model_from_path(model, **model_init_kwargs) + elif args.model_init_kwargs is not None: + logger.warning( + "You passed `model_init_kwargs` to the self-distillation config, but `model` is already " + "instantiated. The `model_init_kwargs` will be ignored." + ) + + self.model_kwarg_keys = ( + inspect.signature(model.forward).parameters.keys() + if not hasattr(model, "get_base_model") + else inspect.signature(model.get_base_model().forward).parameters.keys() + ) + + if peft_config is None and getattr(model, "peft_config", None) is not None: + logger.warning( + "The provided self-distillation student model already contains a PEFT adapter. " + "This setup is accepted but not directly supported. In particular, `teacher_model_kind='base'` " + "may refer to the underlying base weights rather than the exact initially loaded student state " + "including its adapter. For unambiguous teacher behavior, start from a merged/non-adapter model " + "or manage separate adapters explicitly." + ) + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config`. Pass either a base " + "model with `peft_config`, or a pre-wrapped PEFT model." + ) + if peft_config is not None or (is_peft_available() and getattr(model, "peft_config", None) is not None): + model = prepare_peft_model(model, peft_config, args) + + if processing_class is None: + processing_class = AutoProcessor.from_pretrained( + get_config_model_id(model.config), + truncation_side="left", + padding_side="left", + trust_remote_code=args.trust_remote_code, + ) + + if isinstance(processing_class, ProcessorMixin): + self._tokenizer = processing_class.tokenizer + elif isinstance(processing_class, PreTrainedTokenizerBase): + self._tokenizer = processing_class + else: + raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`") + + if self._tokenizer.pad_token is None: + self._tokenizer.pad_token = self._tokenizer.eos_token + + self.max_prompt_length = args.max_prompt_length + self.max_completion_length = args.max_completion_length + self.num_generations = args.num_generations + self.num_generations_eval = args.num_generations_eval or args.num_generations + self.num_iterations = args.num_iterations + self.shuffle_dataset = args.shuffle_dataset + self.temperature = args.temperature + self.generate_from_teacher = args.generate_from_teacher + self.use_vllm = args.use_vllm + self.chat_template_kwargs = args.chat_template_kwargs or {} + self._step = 0 + self._buffered_inputs = None + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + + self.generation_kwargs = { + "max_new_tokens": self.max_completion_length, + "do_sample": True, + "pad_token_id": self._tokenizer.pad_token_id, + "bos_token_id": self._tokenizer.bos_token_id, + "eos_token_id": self._tokenizer.eos_token_id, + "temperature": args.temperature, + "top_p": args.top_p, + "top_k": args.top_k, + "min_p": args.min_p, + "repetition_penalty": args.repetition_penalty, + "cache_implementation": args.cache_implementation, + } + if args.generation_kwargs is not None: + self.generation_kwargs.update(args.generation_kwargs) + self.generation_config = GenerationConfig(**self.generation_kwargs, disable_compile=True) + + if hasattr(model, "warnings_issued"): + model.warnings_issued["estimate_tokens"] = True + + # Teacher logprobs from the running vLLM generation server (reuses the synced student weights) instead of a + # local teacher forward. MVP: `live` teacher only — the generation server holds the current student weights. + self.use_teacher_server = args.use_teacher_server + if self.use_teacher_server: + if not (args.use_vllm and args.vllm_mode == "server"): + raise ValueError( + "`use_teacher_server=True` requires `use_vllm=True` and `vllm_mode='server'`: teacher logprobs are " + "served by the same vLLM server used for generation." + ) + if args.teacher_model_kind != "live": + raise ValueError( + "`use_teacher_server=True` only supports `teacher_model_kind='live'` (the generation server holds " + f"the current student weights), got {args.teacher_model_kind!r}." + ) + if args.distillation_mode not in ("sampled_token", "topk_logits"): + raise ValueError( + "`use_teacher_server=True` only supports `distillation_mode` in {'sampled_token', 'topk_logits'}, " + f"got {args.distillation_mode!r}. The server returns the teacher's top-k logprobs, not the full " + "vocabulary, so `full_logits` is unavailable. Note `topk_logits` distills over the teacher's own " + "top-k support (the server cannot score the student's top-k indices)." + ) + if args.use_liger_kernel: + raise ValueError( + "`use_teacher_server=True` is incompatible with `use_liger_kernel`: the server returns top-k " + "logprobs while the Liger fused loss needs full-vocabulary hidden states." + ) + # Liger fused JSD loss for `full_logits`: same generalized JSD as `compute_divergence`, so alpha maps to beta. + self.use_liger_loss = False + if args.use_liger_kernel: + if not is_liger_kernel_available(): + raise ImportError( + "Liger is required to use `use_liger_kernel` as the self-distillation loss. Run " + "`pip install liger-kernel`." + ) + if args.distillation_mode != "full_logits": + raise ValueError( + "`use_liger_kernel` only supports `distillation_mode='full_logits'`, got " + f"{args.distillation_mode!r}. The fused JSD kernel operates on the full vocabulary and cannot " + "express the top-k support or sampled-token objectives." + ) + if args.distillation_is_clip is not None: + raise ValueError( + "`use_liger_kernel` is incompatible with `distillation_is_clip`: the fused kernel does not expose " + "per-token losses for importance-sampling clipping." + ) + self.liger_jsd_loss = LigerFusedLinearJSDLoss( + beta=args.distillation_alpha, + ignore_index=-100, + temperature=args.temperature, + compiled=False, + weight_hard_loss=0.0, + weight_soft_loss=1.0, + ) + self._forward_redirection = _ForwardRedirection() + self.use_liger_loss = True + + super().__init__( + model=model, + args=args, + data_collator=identity, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + callbacks=callbacks, + optimizers=optimizers, + compute_loss_func="non-None value to disable scaling", + ) + + self._last_loaded_step = -1 if self.use_vllm else 0 + if self.use_vllm: + from ...generation.vllm_generation import VLLMGeneration + + self.vllm_generation = VLLMGeneration( + model=self.model, + accelerator=self.accelerator, + processing_class=self.processing_class, + mode=args.vllm_mode, + server_base_url=args.vllm_server_base_url, + server_host=args.vllm_server_host, + server_port=args.vllm_server_port, + group_port=args.vllm_group_port, + server_timeout=args.vllm_server_timeout, + tensor_parallel_size=args.vllm_tensor_parallel_size, + gpu_memory_utilization=args.vllm_gpu_memory_utilization, + max_model_length=args.vllm_max_model_length, + max_num_seqs=args.per_device_train_batch_size + * args.vllm_tensor_parallel_size + * args.steps_per_generation, + enable_sleep_mode=args.vllm_enable_sleep_mode, + model_impl=args.vllm_model_impl, + repetition_penalty=args.repetition_penalty, + temperature=self.temperature, + top_p=args.top_p, + top_k=args.top_k, + min_p=args.min_p, + max_completion_length=self.max_completion_length, + logprobs=None, + generation_kwargs=args.generation_kwargs, + ) + + # Per-rank read-only client to the same generation server for teacher scoring (weights are synced there by + # `VLLMGeneration`; scoring needs no weight-update communicator). Mirrors the distillation trainer's + # `teacher_client`. + self.teacher_client = None + if self.use_teacher_server: + from ...generation.vllm_client import VLLMClient + + base_url = args.vllm_server_base_url or f"http://{args.vllm_server_host}:{args.vllm_server_port}" + self.teacher_client = VLLMClient(base_url=base_url, connection_timeout=args.vllm_server_timeout) + + if args.disable_dropout: + disable_dropout_in_model(self.model) + + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + self._setup_teacher_model() + self.model_accepts_loss_kwargs = False + + def _set_signature_columns_if_needed(self): + if self._signature_columns is None: + self._signature_columns = ["prompt", "privileged_context"] + + def _dispatch_self_distillation_callback(self, event_name: str, **payload) -> None: + for callback in self.callback_handler.callbacks: + callback_fn = getattr(callback, event_name, None) + if callback_fn is not None: + callback_fn( + args=self.args, + state=self.state, + control=self.control, + model=self.model, + processing_class=self.processing_class, + **payload, + ) + + def _setup_teacher_model(self) -> None: + """Prepare teacher state according to the semantic teacher choice. + + Resolve `teacher_model_kind` × PEFT state into the effective teacher: + + - `"live"` (any model): + Teacher is the student. No divergence, no callback. + - `"base"` + PEFT model: + Teacher reuses `self.model`; the base weights are recovered downstream by disabling the adapter via + `use_adapter` during teacher forward. + - `"base"` + non-PEFT model: + Teacher is a frozen deepcopy of the initial student (falls through to the copy branch below). + - `"ema"` + pure-LoRA training: + Teacher reuses `self.model`; a dedicated `"teacher"` LoRA adapter is attached and updated by + `PEFTAdapterEMACallback`. Teacher forward switches to that adapter downstream. + - `"ema"` (otherwise): + Teacher is a frozen deepcopy synchronized each step by `SyncTeacherModelCallback`. + + Must be called after `super().__init__` so that `self.callback_handler` is available. + """ + + teacher_model_kind = self.args.teacher_model_kind + + if teacher_model_kind == "live": + self.teacher_model = self.model + return + + if teacher_model_kind == "base" and is_peft_model(self.model): + self.teacher_model = self.model + return + + if self._use_peft_ema_teacher_adapter(): + # Must run after super().__init__ so self.callback_handler exists. + self.add_callback( + PEFTAdapterEMACallback( + model=self.model, + teacher_adapter_name="teacher", + update_rate=self.args.teacher_update_rate, + sync_steps=self.args.teacher_sync_steps, + accelerator=self.accelerator, + ) + ) + self.teacher_model = self.model + return + + if is_peft_model(self.model): + raise ValueError( + "`teacher_model_kind='ema'` with a non-pure-LoRA PEFT model is not supported: the separate EMA " + "teacher cannot be parameter-matched to the PEFT student. Use pure-LoRA training, a non-PEFT model, " + "or `teacher_model_kind` in {'live', 'base'}." + ) + + # Build the teacher from the model path (like the GRPO/DPO reference model) rather than deep-copying the + # student: under ZeRO-3 the student params are already sharded, so a deep copy would clone empty shards. + model_init_kwargs = self.args.model_init_kwargs or {} + if self.args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model_init_kwargs.setdefault("trust_remote_code", self.args.trust_remote_code) + self.teacher_model = create_model_from_path(get_config_model_id(self.model.config), **model_init_kwargs) + self.teacher_model.requires_grad_(False) + self.teacher_model.eval() + if self.is_deepspeed_enabled: + self.teacher_model = prepare_deepspeed(self.teacher_model, self.accelerator) + elif self.is_fsdp_enabled: + self.teacher_model = prepare_fsdp(self.teacher_model, self.accelerator) + else: + self.teacher_model = self.accelerator.prepare_model(self.teacher_model, evaluation_mode=True) + + if teacher_model_kind == "ema": + self.add_callback(SyncTeacherModelCallback(teacher_model=self.teacher_model, accelerator=self.accelerator)) + + def _use_peft_ema_teacher_adapter(self) -> bool: + return self.args.teacher_model_kind == "ema" and is_pure_lora_training(self.model, self.accelerator) + + def get_train_dataloader(self): + if self.train_dataset is None: + raise ValueError("Trainer: training requires a train_dataset.") + + train_dataset = self.train_dataset + data_collator = self.data_collator + if is_datasets_available() and isinstance(train_dataset, datasets.Dataset): + train_dataset = self._remove_unused_columns(train_dataset, description="training") + else: + data_collator = self._get_collator_with_removed_columns(data_collator, description="training") + + dataloader_params = { + "batch_size": self._train_batch_size * self.args.steps_per_generation, + "collate_fn": data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "persistent_workers": self.args.dataloader_persistent_workers, + } + if not isinstance(train_dataset, torch.utils.data.IterableDataset): + dataloader_params["sampler"] = self._get_train_sampler() + dataloader_params["drop_last"] = self.args.dataloader_drop_last + dataloader_params["worker_init_fn"] = partial( + seed_worker, num_workers=self.args.dataloader_num_workers, rank=self.args.process_index + ) + dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor + return self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params)) + + def _get_train_sampler(self, dataset=None) -> Sampler: + if dataset is None: + dataset = self.train_dataset + return RepeatSampler( + data_source=dataset, + mini_repeat_count=self.num_generations, + batch_size=self.args.generation_batch_size // self.num_generations, + repeat_count=self.num_iterations * self.args.steps_per_generation, + shuffle=self.shuffle_dataset, + seed=self.args.seed, + ) + + def _get_eval_sampler(self, eval_dataset) -> Sampler: + return RepeatSampler( + data_source=eval_dataset, + mini_repeat_count=self.num_generations_eval, + seed=self.args.seed, + ) + + def training_step(self, model, inputs, num_items_in_batch): + # Gather spans forward+backward: the fused JSD computes the lm_head grad in backward. + with self._get_liger_zero3_lm_head_gather_ctx(model): + output = super().training_step(model, inputs, num_items_in_batch) + self._step += 1 + return output + + def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys=None): + if not isinstance(inputs, dict): + inputs = self._prepare_inputs(inputs) + with torch.no_grad(): + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + return loss.detach(), None, None + + def _prepare_inputs(self, generation_batch): + """Return the per-step training batch, regenerating rollouts and buffering them for reuse in train mode. + + In train mode, rollouts are generated once every `steps_per_generation * num_iterations` steps and split into + per-step slices reused until the next regeneration. In eval mode, every batch is freshly prepared. + """ + mode = "train" if self.model.training else "eval" + if mode == "train": + generate_every = self.args.steps_per_generation * self.num_iterations + if self._step % generate_every == 0 or self._buffered_inputs is None: + buffered_batch = self._prepare_training_batch(generation_batch) + self._buffered_inputs = split_tensor_dict(buffered_batch, self.args.steps_per_generation) + self._dispatch_self_distillation_callback( + "on_generation_batch_built", + generate_every=generate_every, + steps_per_generation=self.args.steps_per_generation, + ) + return self._buffered_inputs[self._step % self.args.steps_per_generation] + return self._prepare_training_batch(generation_batch) + + def _prepare_training_batch(self, inputs: list[dict[str, Any]]) -> TrainingBatch: + """Sample student rollouts and construct teacher prompts""" + batch = self.sample_rollouts(inputs) + mode = "train" if self.model.training else "eval" + self._record_completion_metrics(mode, batch) + prompts = [example["prompt"] for example in inputs] + privileged_contexts = [example.get("privileged_context") for example in inputs] + teacher_batch = self.teacher_context_builder.build( + prompts, + privileged_contexts, + batch["completion_ids"], + batch["completion_mask"], + ) + batch.update( + { + "teacher_input_ids": teacher_batch["teacher_input_ids"], + "teacher_attention_mask": teacher_batch["teacher_attention_mask"], + } + ) + + self._dispatch_self_distillation_callback( + "on_self_distillation_batch_prepared", + old_per_token_logps=batch.get("old_per_token_logps"), + prompt_ids=batch["prompt_ids"], + completion_ids=batch["completion_ids"], + teacher_input_ids=batch["teacher_input_ids"], + teacher_attention_mask=batch["teacher_attention_mask"], + ) + return batch + + def sample_rollouts(self, inputs: list[dict[str, Any]]) -> TrainingBatch: + """Generate completions for a batch of prompts and assemble the training batch.""" + prompts = [example["prompt"] for example in inputs] + privileged_contexts = [example.get("privileged_context") for example in inputs] + + student_prompt_ids_list = self._tokenize_prompts(prompts) + if self.generate_from_teacher: + generation_prompts = self.teacher_context_builder.select_generation_prompts(prompts, privileged_contexts) + generation_prompt_ids_list = self._tokenize_prompts(generation_prompts) + else: + generation_prompts = prompts + generation_prompt_ids_list = student_prompt_ids_list + + self._dispatch_self_distillation_callback( + "on_generation_prompts_selected", + generation_prompts=generation_prompts, + generation_prompt_text=None, + ) + + _, completion_ids_list = self._generate(generation_prompt_ids_list) + device = self.accelerator.device + prompt_ids = [torch.tensor(ids) for ids in student_prompt_ids_list] + prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids] + prompt_ids = pad(prompt_ids, padding_value=self._tokenizer.pad_token_id, padding_side="left").to(device=device) + prompt_mask = pad(prompt_mask, padding_value=0, padding_side="left").to(device=device) + + completion_ids = [torch.tensor(ids) for ids in completion_ids_list] + completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids] + completion_ids = pad(completion_ids, padding_value=self._tokenizer.pad_token_id, padding_side="right").to( + device=device + ) + completion_mask = pad(completion_mask, padding_value=0, padding_side="right").to(device=device) + + old_per_token_logps = None + if not self.generate_from_teacher: + old_per_token_logps = self._compute_rollout_logps( + prompt_ids=prompt_ids, + prompt_mask=prompt_mask, + completion_ids=completion_ids, + completion_mask=completion_mask, + ) + batch: TrainingBatch = { + "prompt_ids": prompt_ids, + "prompt_mask": prompt_mask, + "completion_ids": completion_ids, + "completion_mask": completion_mask, + "raw_completion_lengths": torch.tensor( + [len(ids) for ids in completion_ids_list], device=device, dtype=torch.long + ), + } + if old_per_token_logps is not None: + batch["old_per_token_logps"] = old_per_token_logps + return batch + + def _get_completion_ids_list(self, batch: TrainingBatch) -> list[list[int]]: + raw_completion_lengths = batch["raw_completion_lengths"].detach().cpu().tolist() + return [ + ids[:length].tolist() + for ids, length in zip(batch["completion_ids"].detach().cpu(), raw_completion_lengths, strict=True) + ] + + def _tokenize_prompts(self, prompts: list[Any]) -> list[list[int]]: + if is_conversational({"prompt": prompts[0]}): + tokenized = self.processing_class.apply_chat_template( + conversation=prompts, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + **self.chat_template_kwargs, + ) + prompt_ids = tokenized["input_ids"] + else: + prompt_ids = self.processing_class(text=prompts)["input_ids"] + if self.max_prompt_length is not None: + prompt_ids = [ids[-self.max_prompt_length :] for ids in prompt_ids] + return prompt_ids + + def _generate(self, prompt_ids: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]: + if self.use_vllm: + return self._generate_vllm(prompt_ids) + return self._generate_transformers(prompt_ids) + + def _generate_vllm(self, prompt_ids: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]: + if self.state.global_step != self._last_loaded_step: + self.vllm_generation.sync_weights() + self._last_loaded_step = self.state.global_step + + mode = "train" if self.model.training else "eval" + num_generations = self.num_generations if mode == "train" else self.num_generations_eval + prompt_ids_out, completion_ids_list, _, _ = self.vllm_generation.generate( + prompts=prompt_ids, + images=None, + num_generations=num_generations, + ) + return prompt_ids_out, completion_ids_list + + def _generate_transformers(self, prompt_ids: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]: + device = self.accelerator.device + prompt_tensors = [torch.tensor(ids) for ids in prompt_ids] + padded_ids = pad(prompt_tensors, padding_value=self._tokenizer.pad_token_id, padding_side="left").to( + device=device + ) + attention_mask = pad([torch.ones_like(t) for t in prompt_tensors], padding_value=0, padding_side="left").to( + device=device + ) + generate_inputs: dict[str, torch.Tensor | Any] = {"input_ids": padded_ids, "attention_mask": attention_mask} + + with ( + unwrap_model_for_generation( + self.model_wrapped, + self.accelerator, + gather_deepspeed3_params=self.args.ds3_gather_for_generation, + generation_kwargs=self.generation_kwargs, + ) as unwrapped_model, + torch.no_grad(), + FSDP.summon_full_params(self.model_wrapped, recurse=False) if self.is_fsdp_enabled else nullcontext(), + ): + prompt_completion_ids = unwrapped_model.generate( + **generate_inputs, generation_config=self.generation_config + ) + + prompt_length = generate_inputs["input_ids"].size(1) + completion_ids = prompt_completion_ids[:, prompt_length:] + is_eos = completion_ids == self._tokenizer.eos_token_id + eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device) + eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)] + seq_idx = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1) + completion_mask = (seq_idx <= eos_idx.unsqueeze(1)).int() + completion_ids_list = [ + c[m].tolist() for c, m in zip(completion_ids.cpu(), completion_mask.bool().cpu(), strict=True) + ] + return prompt_ids, completion_ids_list + + def _compute_rollout_logps( + self, + prompt_ids: torch.Tensor, + prompt_mask: torch.Tensor, + completion_ids: torch.Tensor, + completion_mask: torch.Tensor, + ) -> torch.Tensor | None: + generate_every = self.args.steps_per_generation * self.num_iterations + old_per_token_logps = None + + if self.args.gradient_accumulation_steps % generate_every != 0: + prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) + with torch.no_grad(): + logits = self._forward_logits( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + ) + old_per_token_logps = selective_log_softmax(logits, completion_ids) + + return old_per_token_logps + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + if return_outputs: + raise ValueError("The SDFTTrainer does not support returning outputs") + + if self.use_teacher_server: + loss = self._compute_server_distillation_loss(model, inputs) + elif self.use_liger_loss: + loss = self._compute_liger_loss(model, inputs) + else: + distillation_logits = self._compute_teacher_student_logits(model, self.teacher_model, inputs) + loss = self._compute_self_distillation_loss(model, inputs, distillation_logits) + accumulation_scale = self.current_gradient_accumulation_steps if self.model.training else 1.0 + return loss / accumulation_scale + + def _compute_self_distillation_loss( + self, + model, + inputs: TrainingBatch, + distillation_logits: DistillationLogits, + ) -> torch.Tensor: + """Compute the per-token distillation loss and aggregate by normalizing over sequence length. + + Dispatches between three objectives based on `distillation_mode`: + + - `"topk_logits"`: top-k approximation of the divergence, optionally with a tail bucket for the remaining + probability mass (`distillation_add_tail`). + - `"full_logits"`: full-vocab divergence. + - `"sampled_token"`: token-level (reverse-KL) distillation on sampled `completion_ids`. + + When `distillation_is_clip` is set and `old_per_token_logps` are available, the loss is corrected by a clipped + importance-sampling ratio between the current student and the student at rollout time. + """ + if distillation_logits.loss_mask.sum() == 0: + mode = "train" if model.training else "eval" + self._log_self_distillation_metric(mode, 0.0) + # Keep the zero loss attached to the student graph so backward produces zero gradients instead of stopping. + return distillation_logits.student_logits.sum() * 0.0 + + if self.args.distillation_mode == "topk_logits": + if self.args.distillation_topk is None: + raise ValueError("`distillation_mode='topk_logits'` requires `distillation_topk` to be set.") + per_token_loss = compute_topk_self_distillation_loss( + distillation_logits.student_logits, + distillation_logits.teacher_logits, + distillation_topk=self.args.distillation_topk, + distillation_alpha=self.args.distillation_alpha, + distillation_add_tail=self.args.distillation_add_tail, + ) + elif self.args.distillation_mode == "full_logits": + per_token_loss = compute_full_logit_self_distillation_loss( + distillation_logits.student_logits, + distillation_logits.teacher_logits, + distillation_alpha=self.args.distillation_alpha, + ) + elif self.args.distillation_mode == "sampled_token": + per_token_loss = compute_sampled_token_self_distillation_loss( + distillation_logits.student_logits, + distillation_logits.teacher_logits, + distillation_logits.completion_ids, + distillation_alpha=self.args.distillation_alpha, + ) + else: + raise ValueError( + "distillation_mode must be one of: 'sampled_token', 'full_logits', 'topk_logits', " + f"got {self.args.distillation_mode!r}" + ) + + old_per_token_logps = inputs.get("old_per_token_logps") + if self.args.distillation_is_clip is not None and old_per_token_logps is not None: + student_per_token_logps = selective_log_softmax( + distillation_logits.student_logits, + distillation_logits.completion_ids, + ) + per_token_loss = apply_importance_sampling_clipping( + per_token_loss, + student_per_token_logps, + old_per_token_logps, + self.args.distillation_is_clip, + ) + + loss = (per_token_loss * distillation_logits.loss_mask).sum(-1) / distillation_logits.loss_mask.sum(-1).clamp( + min=1.0 + ) + loss = loss.mean() + + mode = "train" if model.training else "eval" + mean_distill_loss = ( + per_token_loss * distillation_logits.loss_mask + ).sum() / distillation_logits.loss_mask.sum().clamp(min=1.0) + self._log_self_distillation_metric( + mode, + self.accelerator.gather(mean_distill_loss).mean().item(), + ) + return loss + + def _compute_server_distillation_loss(self, model, inputs: TrainingBatch) -> torch.Tensor: + """Distillation loss with teacher logprobs served by the vLLM generation server (`teacher_model_kind='live'`). + + The student is forwarded locally (grad) for its logits; the teacher logprobs are fetched from the server (no + local teacher forward). `sampled_token` distills the realized token (reverse KL); `topk_logits` distills over + the teacher's own top-k support (the server cannot score the student's top-k indices). + """ + # Buffered batches are reused across optimizer steps (`num_iterations > 1`), so the server weights can lag the + # live student; re-sync before scoring. + if self.state.global_step != self._last_loaded_step: + self.vllm_generation.sync_weights() + # Only the main process pushes weights to the server, so hold every rank here until the push completes; + # otherwise non-main ranks could score against half-updated weights. + self.accelerator.wait_for_everyone() + self._last_loaded_step = self.state.global_step + + completion_ids = inputs["completion_ids"] + completion_mask = inputs["completion_mask"] + logits_to_keep = completion_ids.size(1) + + # SDFT skips the first few completion tokens in the distillation loss to suppress teacher-prompt artifacts. + loss_mask = completion_mask + if self.num_loss_tokens_to_skip > 0: + token_positions = torch.arange(completion_mask.size(1), device=completion_mask.device).unsqueeze(0) + loss_mask = completion_mask * (token_positions >= self.num_loss_tokens_to_skip).long() + + student_input_ids = torch.cat([inputs["prompt_ids"], completion_ids], dim=1) + student_attention_mask = torch.cat([inputs["prompt_mask"], completion_mask], dim=1) + student_logits = self._forward_logits( + model=model, + input_ids=student_input_ids, + attention_mask=student_attention_mask, + logits_to_keep=logits_to_keep, + ) + + mode = "train" if model.training else "eval" + teacher = self._get_teacher_token_logprobs_from_server(inputs, logits_to_keep) + # Padding positions come back as `-inf`; the masked-out positions are neutralized to finite values below so the + # divergence does not leak `+inf` through them (mirrors the distillation trainer). + required = loss_mask.bool() + student_per_token_logps = selective_log_softmax(student_logits, completion_ids) + + teacher_per_token_logps = teacher["actual_logprobs"] + if (required & ~torch.isfinite(teacher_per_token_logps)).any(): + raise ValueError("Teacher server returned no logprob for a required completion token.") + teacher_per_token_logps = torch.where( + required, teacher_per_token_logps, torch.zeros_like(teacher_per_token_logps) + ) + + # Diagnostic for disagreement between local student scores and server teacher scores on realized tokens. + # Sudden jumps can indicate stale server weights or numerical drift. + abs_diff = ((student_per_token_logps.detach() - teacher_per_token_logps).abs() * loss_mask).sum() / ( + loss_mask.sum().clamp(min=1.0) + ) + self._metrics[mode]["self_distillation/server_logprob_abs_diff"].append( + self.accelerator.gather(abs_diff).mean().item() + ) + + if self.args.distillation_mode == "sampled_token": + # Reverse-KL token-level objective, matching `compute_sampled_token_self_distillation_loss`. + per_token_loss = (student_per_token_logps - teacher_per_token_logps).detach() * student_per_token_logps + else: + teacher_topk_logps = teacher["topk_logprobs"] + teacher_topk_ids = teacher["topk_token_ids"] + # Project the student onto the teacher's top-k support, then renormalize (or add a tail bucket) before the + # divergence, matching `compute_topk_self_distillation_loss` on the teacher's support. + keep = required.unsqueeze(-1) + student_topk_logps = torch.gather( + torch.log_softmax(student_logits, dim=-1), dim=-1, index=teacher_topk_ids + ) + student_topk_logps = torch.where(keep, student_topk_logps, torch.zeros_like(student_topk_logps)) + teacher_topk_logps = torch.where(keep, teacher_topk_logps, torch.zeros_like(teacher_topk_logps)) + if self.args.distillation_add_tail: + student_topk_logps = add_tail_bucket(student_topk_logps) + teacher_topk_logps = add_tail_bucket(teacher_topk_logps) + else: + student_topk_logps = student_topk_logps - torch.logsumexp(student_topk_logps, dim=-1, keepdim=True) + teacher_topk_logps = teacher_topk_logps - torch.logsumexp(teacher_topk_logps, dim=-1, keepdim=True) + per_token_loss = compute_divergence(student_topk_logps, teacher_topk_logps, self.args.distillation_alpha) + + old_per_token_logps = inputs.get("old_per_token_logps") + if self.args.distillation_is_clip is not None and old_per_token_logps is not None: + per_token_loss = apply_importance_sampling_clipping( + per_token_loss, student_per_token_logps, old_per_token_logps, self.args.distillation_is_clip + ) + + loss = (per_token_loss * loss_mask).sum(-1) / loss_mask.sum(-1).clamp(min=1.0) + loss = loss.mean() + mean_distill_loss = (per_token_loss * loss_mask).sum() / loss_mask.sum().clamp(min=1.0) + self._log_self_distillation_metric(mode, self.accelerator.gather(mean_distill_loss).mean().item()) + return loss + + def _get_teacher_token_logprobs_from_server( + self, inputs: TrainingBatch, logits_to_keep: int + ) -> dict[str, torch.Tensor]: + """Per-token teacher logprobs from the vLLM server. + + Returns a dict with `actual_logprobs` (`(B, T)`, the realized-token logprob for reverse KL) and `topk_logprobs` + / `topk_token_ids` (`(B, T, K)`, the teacher's top-k support for top-k logit distillation). Completions are + right-padded, so server values fill the leading positions of each row and the trailing padding keeps the `-inf` + / `0` sentinels (neutralized by the caller). + """ + import numpy as np + + teacher_input_ids = inputs["teacher_input_ids"] + teacher_attention_mask = inputs["teacher_attention_mask"] + device = teacher_input_ids.device + batch_size = teacher_input_ids.size(0) + prompt_attention_mask = teacher_attention_mask[:, : teacher_attention_mask.size(1) - logits_to_keep] + if self.args.distillation_mode == "topk_logits" and self.args.distillation_topk is None: + raise ValueError("`distillation_mode='topk_logits'` requires `distillation_topk` to be set.") + top_logprobs = self.args.distillation_topk if self.args.distillation_mode == "topk_logits" else 1 + + sequences, prompt_lengths, _ = build_teacher_request_inputs( + teacher_input_ids, teacher_attention_mask, prompt_attention_mask + ) + result = self.teacher_client.get_sequence_logprobs( + sequences=sequences, + prompt_lengths=prompt_lengths, + top_logprobs=top_logprobs, + temperature=self.temperature, + ) + + actual = np.full((batch_size, logits_to_keep), float("-inf"), dtype=np.float32) + topk = np.full((batch_size, logits_to_keep, top_logprobs), float("-inf"), dtype=np.float32) + topk_ids = np.zeros((batch_size, logits_to_keep, top_logprobs), dtype=np.int64) + for i in range(batch_size): + seq_actual = result["actual_logprobs"][i] + n = min(len(seq_actual), logits_to_keep) + if n: + actual[i, :n] = np.array(seq_actual, dtype=np.float32)[:n, 0] + topk[i, :n] = np.array(result["logprobs"][i], dtype=np.float32)[:n] + topk_ids[i, :n] = np.array(result["logprob_token_ids"][i], dtype=np.int64)[:n] + return { + "actual_logprobs": torch.from_numpy(actual).to(device), + "topk_logprobs": torch.from_numpy(topk).to(device), + "topk_token_ids": torch.from_numpy(topk_ids).to(device), + } + + def _compute_teacher_student_logits( + self, + model, + teacher_model, + inputs: TrainingBatch, + ) -> DistillationLogits: + """Compute the per-token logits of the student and teacher over the completion tokens. + + The student is forwarded on its own input (original prompt plus the sampled completion) while the teacher is + forwarded on its input (prompt, privileged context, and the same completion). Both sets of logits are aligned + to the completion tokens so they can be compared position-by-position in the distillation loss. + + The teacher forward runs under `torch.no_grad()` and the context resolved by + `_get_teacher_context_for_self_distillation`, which routes it to the correct weights. + """ + prompt_ids = inputs["prompt_ids"] + prompt_mask = inputs["prompt_mask"] + completion_ids = inputs["completion_ids"] + completion_mask = inputs["completion_mask"] + logits_to_keep = completion_ids.size(1) + + # SDFT skips the first few completion tokens in the distillation loss to suppress teacher-prompt artifacts. + loss_mask = completion_mask + if self.num_loss_tokens_to_skip > 0: + token_positions = torch.arange(completion_mask.size(1), device=completion_mask.device).unsqueeze(0) + loss_mask = completion_mask * (token_positions >= self.num_loss_tokens_to_skip).long() + + student_input_ids = torch.cat([prompt_ids, completion_ids], dim=1) + student_attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + student_logits = self._forward_logits( + model=model, + input_ids=student_input_ids, + attention_mask=student_attention_mask, + logits_to_keep=logits_to_keep, + ) + + with torch.no_grad(), self._get_teacher_context_for_self_distillation(): + teacher_logits = self._forward_logits( + model=teacher_model, + input_ids=inputs["teacher_input_ids"], + attention_mask=inputs["teacher_attention_mask"], + logits_to_keep=logits_to_keep, + ) + + return DistillationLogits( + completion_ids=completion_ids, + loss_mask=loss_mask, + student_logits=student_logits, + teacher_logits=teacher_logits, + ) + + def _forward_logits( + self, + model, + input_ids: torch.Tensor, + attention_mask: torch.Tensor, + logits_to_keep: int, + ) -> torch.Tensor: + """Forward the model and return temperature-scaled logits aligned to the completion tokens.""" + model_inputs = { + "input_ids": input_ids, + "attention_mask": attention_mask, + "use_cache": False, + } + if "logits_to_keep" in self.model_kwarg_keys: + model_inputs["logits_to_keep"] = logits_to_keep + 1 + + logits = model(**model_inputs).logits + logits = logits[:, :-1, :] + logits = logits[:, -logits_to_keep:, :] + return logits / self.temperature + + def _compute_liger_loss(self, model, inputs: TrainingBatch) -> torch.Tensor: + """`full_logits` distillation via the Liger fused JSD kernel: forwards the base models for hidden states and + fuses the lm_head projection with the divergence, never materializing the full-vocab logits. + + Each model is forwarded through its own wrapper via `_forward_redirection` so FSDP2/DeepSpeed materialize the + sharded params during the unwrapped base forward. The fused kernel needs both lm_head weights live at once, so + the frozen teacher weight is captured while the teacher is materialized and handed to the student pass. + """ + logits_to_keep = inputs["completion_ids"].size(1) + completion_mask = inputs["completion_mask"] + loss_mask = completion_mask + if self.num_loss_tokens_to_skip > 0: + token_positions = torch.arange(completion_mask.size(1), device=completion_mask.device).unsqueeze(0) + loss_mask = completion_mask * (token_positions >= self.num_loss_tokens_to_skip).long() + + unwrapped_student = self.accelerator.unwrap_model(model) + unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model) + + with torch.no_grad(), self._get_teacher_context_for_self_distillation(): + teacher_hidden, teacher_weight, teacher_bias = self._forward_redirection( + self.teacher_model, + unwrapped_teacher, + self._liger_teacher_side, + unwrapped_teacher, + inputs, + logits_to_keep, + ) + + return self._forward_redirection( + model, + unwrapped_student, + self._liger_student_loss, + unwrapped_student, + inputs, + logits_to_keep, + loss_mask, + teacher_hidden, + teacher_weight, + teacher_bias, + ) + + def _liger_teacher_side(self, teacher, inputs: TrainingBatch, logits_to_keep: int): + """Teacher hidden states + frozen lm_head weight, captured while the teacher params are materialized.""" + hidden = teacher.get_decoder()( + input_ids=inputs["teacher_input_ids"], + attention_mask=inputs["teacher_attention_mask"], + use_cache=False, + ).last_hidden_state + hidden = hidden[:, :-1][:, -logits_to_keep:] + head = teacher.get_output_embeddings() + # Clone so the weight survives re-sharding once this forward context exits. + weight = head.weight.detach().clone() + bias = head.bias.detach().clone() if head.bias is not None else None + return hidden, weight, bias + + def _liger_student_loss( + self, + student, + inputs: TrainingBatch, + logits_to_keep, + loss_mask, + teacher_hidden, + teacher_weight, + teacher_bias, + ): + student_input_ids = torch.cat([inputs["prompt_ids"], inputs["completion_ids"]], dim=1) + student_attention_mask = torch.cat([inputs["prompt_mask"], inputs["completion_mask"]], dim=1) + student_hidden = student.get_decoder()( + input_ids=student_input_ids, + attention_mask=student_attention_mask, + use_cache=False, + ).last_hidden_state + # Align hidden states to the completion-predicting positions, matching `_forward_logits`. + student_hidden = student_hidden[:, :-1][:, -logits_to_keep:] + + # `ignore_index` masks non-response positions; the token values only feed the disabled hard-CE term. + completion_ids = inputs["completion_ids"] + true_labels = torch.where(loss_mask.bool(), completion_ids, torch.full_like(completion_ids, -100)) + + student_head = student.get_output_embeddings() + # Per-sequence then batch mean (grpo), matching the non-Liger path: the fused kernel reduces by total tokens + # (bnpo), so we call it per sequence and average. + seq_losses = [ + self.liger_jsd_loss( + student_input=student_hidden[i], + student_weight=student_head.weight, + teacher_input=teacher_hidden[i], + teacher_weight=teacher_weight, + true_labels=true_labels[i], + student_bias=student_head.bias, + teacher_bias=teacher_bias, + ) + for i in range(student_hidden.size(0)) + ] + loss = torch.stack(seq_losses).mean() + + mode = "train" if student.training else "eval" + self._log_self_distillation_metric(mode, self.accelerator.gather(loss.detach()).mean().item()) + return loss + + def _get_liger_zero3_lm_head_gather_ctx(self, model): + """Gather the sharded student/teacher lm_head weights for the fused matmul under ZeRO-3. Liger reads + `lm_head.weight` by attribute, so the gather hook never fires; the decoder forward gathers itself. No-op + outside ZeRO-3.""" + if not self.use_liger_loss: + return nullcontext() + + deepspeed_plugin = self.accelerator.state.deepspeed_plugin + if deepspeed_plugin is None or deepspeed_plugin.zero_stage != 3: + return nullcontext() + + import deepspeed + + unwrapped_student = self.accelerator.unwrap_model(model) + unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model) + student_head = unwrapped_student.get_output_embeddings() + teacher_head = unwrapped_teacher.get_output_embeddings() + params = [student_head.weight, teacher_head.weight] + if student_head.bias is not None: + params.append(student_head.bias) + if teacher_head.bias is not None: + params.append(teacher_head.bias) + return deepspeed.zero.GatheredParameters(params, modifier_rank=None) + + def _get_teacher_context_for_self_distillation(self): + """Return the context manager that routes the teacher forward to the correct weights. + + For non-PEFT models this is a no-op. For PEFT models: + + - `teacher_model_kind == "base"`: disable the student adapter so the teacher forward uses the base weights. + - `teacher_model_kind == "ema"` under pure-LoRA training: switch to the `"teacher"` LoRA adapter. + - otherwise: no-op; the teacher is a separate deepcopy. + """ + teacher_model_kind = self.args.teacher_model_kind + if not is_peft_model(self.model): + return nullcontext() + + target_model = self.accelerator.unwrap_model(self.teacher_model) + + if teacher_model_kind == "base": + return use_adapter(target_model, adapter_name=None) + if teacher_model_kind == "ema" and self._use_peft_ema_teacher_adapter(): + return use_adapter(target_model, adapter_name="teacher") + return nullcontext() + + def _record_completion_metrics(self, mode: str, batch: TrainingBatch) -> None: + device = self.accelerator.device + completion_ids_list = self._get_completion_ids_list(batch) + agg_completion_lengths = self.accelerator.gather(batch["raw_completion_lengths"]) + self._metrics[mode]["completions/mean_length"].append(agg_completion_lengths.float().mean().item()) + self._metrics[mode]["completions/min_length"].append(agg_completion_lengths.float().min().item()) + self._metrics[mode]["completions/max_length"].append(agg_completion_lengths.float().max().item()) + + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device) + agg_is_truncated = self.accelerator.gather(is_truncated) + self._metrics[mode]["completions/clipped_ratio"].append(agg_is_truncated.float().mean().item()) + term_completion_lengths = agg_completion_lengths[~agg_is_truncated] + if len(term_completion_lengths) == 0: + term_completion_lengths = torch.zeros(1, device=device) + self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_lengths.float().mean().item()) + self._metrics[mode]["completions/min_terminated_length"].append(term_completion_lengths.float().min().item()) + self._metrics[mode]["completions/max_terminated_length"].append(term_completion_lengths.float().max().item()) + + def _log_self_distillation_metric(self, mode: str, value: float) -> None: + metric_prefix = self._name.lower().replace(" ", "_") + self._metrics[mode]["self_distillation/distillation_loss"].append(value) + self._metrics[mode][f"{metric_prefix}/distillation_loss"].append(value) + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + metrics = {k: sum(v) / len(v) for k, v in self._metrics[mode].items() if v} + if mode == "eval": + metrics = {f"eval_{k}": v for k, v in metrics.items()} + logs = {**logs, **metrics} + super().log(logs, start_time) + self._metrics[mode].clear() diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdft/teacher_sync.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdft/teacher_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..132032646ec65e2e60aa1e015af9082418924d5e --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdft/teacher_sync.py @@ -0,0 +1,184 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging + +import torch +from accelerate.utils import is_peft_model +from transformers import ( + TrainerCallback, + TrainerControl, + TrainerState, + TrainingArguments, +) + +from ...trainer.callbacks import SyncRefModelCallback + + +logger = logging.getLogger(__name__) + + +def is_pure_lora_training(model, accelerator=None) -> bool: + """Return `True` when the active adapter is LoRA and every trainable parameter is a LoRA parameter.""" + if not is_peft_model(model): + return False + + if accelerator is not None: + model = accelerator.unwrap_model(model) + + adapter_name = model.active_adapter + if adapter_name is None: + adapter_name = "default" + adapter_config = model.peft_config.get(adapter_name) + peft_type = adapter_config.peft_type + if peft_type is None or str(peft_type).split(".")[-1] != "LORA": + return False + + for name, param in model.named_parameters(): + if param.requires_grad and "lora_" not in name: + return False + return True + + +class SyncTeacherModelCallback(SyncRefModelCallback): + """Synchronize an EMA teacher model with the student model on each configured sync step.""" + + def __init__(self, teacher_model, accelerator=None): + super().__init__(ref_model=teacher_model, accelerator=accelerator) + + def on_step_end(self, args, state, control, **kwargs): + model = kwargs["model"] + if self.ref_model is not None and state.global_step % args.teacher_sync_steps == 0: + if self.accelerator: + model = self.accelerator.unwrap_model(model) + self.sync_target_model(model, self.ref_model, args.teacher_update_rate) + + +class PEFTAdapterEMACallback(TrainerCallback): + """ + Callback that maintains an EMA copy of PEFT adapter weights for use as a teacher model in self-distillation. + + The callback creates a secondary adapter ("teacher") with zero-initialized weights and maintains shadow weights + that are updated via exponential moving average: `teacher_weight = (1-α) * teacher_weight + α * student_weight` + + Usage: + ```python + >>> trainer.add_callback( + ... PEFTAdapterEMACallback( + ... model=model, + ... teacher_adapter_name="teacher", + ... update_rate=0.05, + ... ) + ... ) + ``` + """ + + def __init__( + self, + model, + teacher_adapter_name: str = "teacher", + update_rate: float = 0.05, + sync_steps: int = 1, + accelerator=None, + ): + self.model = model + self.teacher_adapter_name = teacher_adapter_name + self.update_rate = update_rate + self.sync_steps = sync_steps + self.accelerator = accelerator + self.shadow_weights: dict[str, torch.Tensor] | None = None + self.teacher_adapter_config = None + self._initialized = False + + def _get_student_state_dict(self): + """Get student adapter state dict using PEFT keys (without adapter name).""" + from peft import get_peft_model_state_dict + + if self.accelerator is not None: + model = self.accelerator.unwrap_model(self.model) + else: + model = self.model + return get_peft_model_state_dict(model) + + def _initialize_teacher_adapter(self): + """Create teacher adapter with zero weights initialized from student adapter.""" + from peft import get_peft_model_state_dict, set_peft_model_state_dict + + if self._initialized: + return + + if self.accelerator is not None: + model = self.accelerator.unwrap_model(self.model) + else: + model = self.model + + adapter_name = model.active_adapter + if adapter_name is None: + adapter_name = "default" + + self.teacher_adapter_config = model.peft_config.get(adapter_name) + + student_state = get_peft_model_state_dict(model) + + teacher_state = {k: torch.zeros_like(v) for k, v in student_state.items()} + + model.add_adapter(self.teacher_adapter_name, self.teacher_adapter_config) + + model.set_adapter(self.teacher_adapter_name) + set_peft_model_state_dict(model, teacher_state, adapter_name=self.teacher_adapter_name) + + model.set_adapter(adapter_name) + + self.shadow_weights = {k: v.clone().zero_() for k, v in teacher_state.items()} + + self._initialized = True + logger.info(f"Initialized PEFT adapter EMA teacher with adapter name: {self.teacher_adapter_name}") + + @torch.no_grad() + def on_step_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): + if state.global_step % self.sync_steps != 0: + return + + if not self._initialized: + self._initialize_teacher_adapter() + + if self.shadow_weights is None: + return + + if self.accelerator is None and "accelerator" in kwargs: + self.accelerator = kwargs["accelerator"] + + student_state = self._get_student_state_dict() + + for key, student_param in student_state.items(): + if key in self.shadow_weights: + shadow = self.shadow_weights[key] + shadow.data = (1 - self.update_rate) * shadow.data + self.update_rate * student_param.data + + from peft import set_peft_model_state_dict + + if self.accelerator is not None: + unwrapped_model = self.accelerator.unwrap_model(self.model) + else: + unwrapped_model = self.model + + original_adapter = unwrapped_model.active_adapter + unwrapped_model.set_adapter(self.teacher_adapter_name) + set_peft_model_state_dict(unwrapped_model, self.shadow_weights, adapter_name=self.teacher_adapter_name) + unwrapped_model.set_adapter(original_adapter) + + def on_train_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): + if self.accelerator is None and "accelerator" in kwargs: + self.accelerator = kwargs["accelerator"] + self._initialize_teacher_adapter() diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdpo/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdpo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f50a54cf7c8d3dcc907361da9caa07e53cd21d9f --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdpo/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .sdpo_config import SDPOConfig +from .sdpo_trainer import SDPOTrainer + + +__all__ = ["SDPOConfig", "SDPOTrainer"] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdpo/loss_utils.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdpo/loss_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5caa8c88713d2088c9c4c728dcea3e62236cf4e4 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdpo/loss_utils.py @@ -0,0 +1,135 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Pure helper functions for self-distillation loss computation.""" + +import torch +import torch.nn.functional as F + +from ...trainer.utils import selective_log_softmax + + +def compute_divergence( + student_log_probs: torch.Tensor, + teacher_log_probs: torch.Tensor, + alpha: float, +) -> torch.Tensor: + if alpha == 0.0: + kl = F.kl_div(student_log_probs, teacher_log_probs, reduction="none", log_target=True) + elif alpha == 1.0: + kl = F.kl_div(teacher_log_probs, student_log_probs, reduction="none", log_target=True) + else: + alpha_t = torch.tensor(alpha, dtype=student_log_probs.dtype, device=student_log_probs.device) + mixture = torch.logsumexp( + torch.stack([student_log_probs + torch.log(1 - alpha_t), teacher_log_probs + torch.log(alpha_t)]), + dim=0, + ) + kl_teacher = F.kl_div(mixture, teacher_log_probs, reduction="none", log_target=True) + kl_student = F.kl_div(mixture, student_log_probs, reduction="none", log_target=True) + kl = torch.lerp(kl_student, kl_teacher, alpha) + return kl.sum(-1) + + +def add_tail_bucket(log_probs: torch.Tensor) -> torch.Tensor: + """Append a bucket holding the leftover probability mass to a top-k log-prob support. + + `log_probs` are true log-probabilities over a top-k subset, so they sum to the captured mass `P_topk <= 1`. This + appends one extra category equal to the tail mass `1 - P_topk`, yielding a distribution that sums to exactly 1. + """ + log_s = torch.logsumexp(log_probs, dim=-1, keepdim=True) + log_s = torch.clamp(log_s, max=-1e-7) + tail_log = torch.log(-torch.expm1(log_s)) + return torch.cat([log_probs, tail_log], dim=-1) + + +def apply_importance_sampling_clipping( + per_token_loss: torch.Tensor, + student_log_probs: torch.Tensor, + old_log_probs: torch.Tensor, + clip_coeff: float, +) -> torch.Tensor: + negative_approx_kl = (student_log_probs - old_log_probs).detach() + negative_approx_kl = torch.clamp(negative_approx_kl, min=-20.0, max=20.0) + ratio = torch.exp(negative_approx_kl).clamp(max=clip_coeff) + return per_token_loss * ratio + + +def compute_topk_self_distillation_loss( + student_logits: torch.Tensor, + teacher_logits: torch.Tensor, + *, + distillation_topk: int, + distillation_alpha: float, + distillation_add_tail: bool, +) -> torch.Tensor: + """Compute distillation loss on the student's top-k token support. + + The student's top-k logits define the support. The teacher distribution is projected onto the same token indices. + The selected support is then either renormalized or augmented with a tail bucket before the divergence is computed. + """ + student_logsumexp = torch.logsumexp(student_logits, dim=-1, keepdim=True) + topk_student_logits, topk_indices = torch.topk(student_logits, k=distillation_topk, dim=-1) + topk_student_log_probs = topk_student_logits - student_logsumexp + + teacher_logsumexp = torch.logsumexp(teacher_logits, dim=-1, keepdim=True) + topk_teacher_logits = torch.gather(teacher_logits, dim=-1, index=topk_indices) + topk_teacher_log_probs = topk_teacher_logits - teacher_logsumexp + + # Top-k log-probs sum to the captured mass P_topk <= 1; the rest (1 - P_topk) is the "tail". + if distillation_add_tail: + # Lump the tail into one bucket so the divergence approximates the full-vocab divergence. + topk_student_log_probs = add_tail_bucket(topk_student_log_probs) + topk_teacher_log_probs = add_tail_bucket(topk_teacher_log_probs) + else: + # Drop the tail and renormalize the top-k to sum to 1: divergence over the top-k conditional only. + topk_student_log_probs = topk_student_log_probs - torch.logsumexp(topk_student_log_probs, dim=-1, keepdim=True) + topk_teacher_log_probs = topk_teacher_log_probs - torch.logsumexp(topk_teacher_log_probs, dim=-1, keepdim=True) + + return compute_divergence(topk_student_log_probs, topk_teacher_log_probs, distillation_alpha) + + +def compute_full_logit_self_distillation_loss( + student_logits: torch.Tensor, + teacher_logits: torch.Tensor, + *, + distillation_alpha: float, +) -> torch.Tensor: + """Compute full-vocabulary self-distillation loss between student and teacher logits.""" + student_log_probs = torch.log_softmax(student_logits, dim=-1) + teacher_log_probs = torch.log_softmax(teacher_logits, dim=-1) + return compute_divergence(student_log_probs, teacher_log_probs, distillation_alpha) + + +def compute_sampled_token_self_distillation_loss( + student_logits: torch.Tensor, + teacher_logits: torch.Tensor, + completion_ids: torch.Tensor, + *, + distillation_alpha: float, +) -> torch.Tensor: + """Compute token-level self-distillation loss only on the sampled completion tokens. + + This path compares student and teacher log-probabilities on the realized completion tokens rather than over a + larger token support. + """ + if distillation_alpha != 1.0: + raise ValueError( + "Only reverse KL (alpha=1.0) is supported for token-level distillation when " + f"`distillation_mode='sampled_token'`, got alpha={distillation_alpha}" + ) + + student_per_token_logps = selective_log_softmax(student_logits, completion_ids) + teacher_per_token_logps = selective_log_softmax(teacher_logits, completion_ids) + log_ratio = student_per_token_logps - teacher_per_token_logps + return log_ratio.detach() * student_per_token_logps diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdpo/sdpo_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdpo/sdpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..1981a6c4d6c82a39f68634a21aee2a712cd0d71a --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdpo/sdpo_config.py @@ -0,0 +1,644 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any, Literal + +from transformers import TrainingArguments + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class SDPOConfig(_BaseConfig): + r""" + Configuration class for the [`SDPOTrainer`]. + + Parameters: + > Parameters that control the online policy objective + + beta (`float`, *optional*, defaults to `0.0`): + KL coefficient. If `0.0` (default), the reference model is not loaded, reducing memory usage and improving + training speed. [DeepSeek-R1 incentivizes reasoning in LLMs through reinforcement + learning](https://huggingface.co/papers/2501.12948) use a value of `0.001`. + epsilon (`float`, *optional*, defaults to `0.2`): + Epsilon value for clipping. + epsilon_high (`float`, *optional*): + Upper-bound epsilon value for clipping. If not specified, it defaults to the same value as the lower-bound + specified in argument `epsilon`. Paper DAPO recommends `0.28`. + importance_sampling_level (`str`, *optional*, defaults to `"token"`): + Controls whether importance sampling ratios are computed at the `'token'` or `'sequence'` level. `'token'` + keeps the raw per-token log-probability ratios (one weight per token). `'sequence'` averages the + log-probability ratios across valid tokens to produce a single ratio per sequence. The GSPO paper shows + that sequence-level sampling often yields more stable training and better alignment with sequence-level + rewards. + reward_weights (`list[float]`, *optional*): + Weights for each reward function. Must match the number of reward functions. If `None`, all rewards are + weighted equally with weight `1.0`. + scale_rewards (`str` or `bool`, *optional*, defaults to `"group"`): + Specifies the scaling strategy for rewards. Supported values are: `True` or `'group'` (default): rewards + are scaled by the standard deviation within each group, ensuring unit variance within a group. `'batch'`: + rewards are scaled by the standard deviation across the entire batch, as recommended in the PPO Lite paper. + `False` or `'none'`: no scaling is applied. The Dr. GRPO paper recommends not scaling rewards, as scaling + by the standard deviation introduces a question-level difficulty bias. + + > Parameters that control the SDPO loss + + distillation_weight (`float`, *optional*, defaults to `1.0`): + Convex combination weight between the policy and self-distillation objectives. The loss is `(1 - + distillation_weight) * policy_loss + distillation_weight * distillation_loss`. Must be in `[0, 1]`. `1.0` + (default) trains purely on self-distillation, `0.0` falls back to the standard GRPO-style policy gradient, + and intermediate values blend both. + distillation_alpha (`float`, *optional*, defaults to `1.0`): + Divergence interpolation coefficient. Sampled-token SDPO requires the official reverse-KL setting + `distillation_alpha=1.0`. + distillation_mode (`Literal["sampled_token", "full_logits", "topk_logits"]`, *optional*, defaults to `"sampled_token"`): + Distillation objective mode. `sampled_token` is the default SDPO mode and requires + `distillation_alpha=1.0`. + distillation_topk (`int`, *optional*): + Top-k approximation for logit-level SDPO. Must be set when `distillation_mode=topk_logits` and left unset + otherwise. + distillation_is_clip (`float`, *optional*, defaults to `2.0`): + Clipping coefficient for importance sampling in self-distillation. `None` disables clipping. + distillation_add_tail (`bool`, *optional*, defaults to `False`): + Whether to add a tail bucket for non-top-k probability mass. + + > Parameters that control the teacher + + teacher_model_kind (`str`, *optional*, defaults to `"ema"`): + Semantic teacher choice. `base` uses the initial student, `live` uses the current student, and `ema` uses + an exponentially averaged teacher. + teacher_update_rate (`float`, *optional*, defaults to `0.05`): + Teacher update rate used for EMA teacher synchronization. + teacher_sync_steps (`int`, *optional*, defaults to `1`): + How often to synchronize the EMA teacher model. + + > Parameters that control reprompting + + use_successful_as_teacher (`bool`, *optional*, defaults to `True`): + Use successful rollouts as implicit feedback for self-distillation. + success_reward_threshold (`float`, *optional*, defaults to `1.0`): + Minimum reward for a rollout to be considered a successful demonstration. + dont_reprompt_on_self_success (`bool`, *optional*, defaults to `True`): + Skip reprompting when model generates correct response. + max_reprompt_len (`int`, *optional*, defaults to `10240`): + Maximum length for reprompting in self-distillation. + reprompt_template (`str`, *optional*, defaults to `"{prompt}{solution}{feedback}\n\nCorrectly solve the original question.\n"`): + Template for reprompting the teacher with a successful demonstration. + solution_template (`str`, *optional*, defaults to `"\nCorrect solution: + \n\n{successful_previous_attempt}\n\n"`): Template for formatting the successful demonstration text. + feedback_template (`str`, *optional*, defaults to `"\nThe following is feedback from your unsuccessful earlier attempt: + \n\n{feedback_raw}\n\n"`): Template for formatting environment feedback for reprompting. + include_environment_feedback (`bool`, *optional*, defaults to `False`): + Whether to include environment feedback in teacher reprompts when available. + environment_feedback_only_without_solution (`bool`, *optional*, defaults to `False`): + Whether to use feedback only when no successful solution is available. + remove_thinking_from_demonstration (`bool`, *optional*, defaults to `False`): + Whether to remove ... blocks from the demonstration text. + + > Parameters that control diagnostics + + diagnostics_warning_interval (`int`, *optional*, defaults to `10`): + Emit repeated trainer diagnostics every N consecutive degenerate steps. Set to 0 to disable. + diagnostics_flat_tolerance (`float`, *optional*, defaults to `1e-8`): + Tolerance used to decide whether reward variance or reprompt activity is effectively zero. + + > Parameters that control the model + + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments for `transformers.AutoModelForCausalLM.from_pretrained`, used when the `model` argument + of the `SDPOTrainer` is provided as a string. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to + [`~transformers.AutoModelForCausalLM.from_pretrained`] and [`~transformers.AutoProcessor.from_pretrained`]. + Also applied to reward-model and reward-tokenizer loads. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. This is useful for training with a reference model, as it prevents + the model from generating different logprobs for the same input. + + > Parameters that control data preprocessing + + remove_unused_columns (`bool`, *optional*, defaults to `False`): + Whether to only keep the column 'prompt' in the dataset. If you use a custom reward function that requires + any column other than 'prompts' and 'completions', you should keep this to `False`. + max_prompt_length (`int`, *optional*, defaults to `512`): + Maximum prompt length. Longer prompts are truncated from the left. + shuffle_dataset (`bool`, *optional*, defaults to `True`): + Whether to shuffle the training dataset. + + > Parameters that control generation + + num_generations (`int`, *optional*, defaults to `8`): + Number of generations to sample. The effective batch size (num_processes * per_device_batch_size * + gradient_accumulation_steps) must be evenly divisible by this value. + num_generations_eval (`int`, *optional*): + Number of generations to sample during evaluation. This allows using fewer generations during evaluation to + save computation. If `None`, uses the value of `num_generations`. + max_completion_length (`int`, *optional*, defaults to `256`): + Maximum length of the generated completion. + temperature (`float`, *optional*, defaults to `1.0`): + Temperature for sampling. The higher the temperature, the more random the completions. + top_p (`float`, *optional*, defaults to `1.0`): + Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to 1.0 + to consider all tokens. + top_k (`int`, *optional*, defaults to `0`): + Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is + disabled and all tokens are considered. + min_p (`float`, *optional*): + Minimum token probability, which will be scaled by the probability of the most likely token. It must be a + value between 0.0 and 1.0. Typical values are in the 0.01-0.2 range. + repetition_penalty (`float`, *optional*, defaults to `1.0`): + Float that penalizes new tokens based on whether they appear in the prompt and the generated text so far. + Values > 1.0 encourage the model to use new tokens, while values < 1.0 encourage the model to repeat + tokens. + cache_implementation (`str`, *optional*): + Implementation of the cache method for faster generation when use_vllm is set to False. + generation_kwargs (`dict[str, Any]`, *optional*): + Additional keyword arguments to pass to `GenerationConfig` (if using transformers) or `SamplingParams` (if + using vLLM) when sampling completions. This can be used to further customize the generation behavior, such + as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that conflict with the other generation + parameters (like `min_p`, `top_p`, etc.), they will override them. + chat_template_kwargs (`dict[str, Any]`, *optional*): + Additional keyword arguments to pass to the `apply_chat_template` function when generating completions. + ds3_gather_for_generation (`bool`, *optional*, defaults to `True`): + This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation, + improving generation speed. However, disabling this option allows training models that exceed the VRAM + capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible + with vLLM generation. + + > Parameters that control generation acceleration powered by vLLM + + use_vllm (`bool`, *optional*, defaults to `False`): + Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for generation + instead of the default model.generate(). Requires `vllm` to be installed. + use_teacher_server (`bool`, *optional*, defaults to `False`): + Compute teacher logprobs from the running vLLM generation server instead of a local teacher forward. Only + supported for `teacher_model_kind='live'` with `use_vllm=True`, `vllm_mode='server'`, + `distillation_weight=1.0` (pure distillation), and `distillation_mode` in {'sampled_token', 'topk_logits'} + (the server returns the teacher's top-k logprobs, not the full vocabulary; `topk_logits` distills over the + teacher's own top-k support). + vllm_mode (`str`, *optional*, defaults to `"colocate"`): + Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `'server'` or + `'colocate'`. `'server'`: The trainer will send generation requests to a separate vLLM server. Make sure a + TRL vLLM server is running (start with `trl vllm-serve`). `'colocate'`: vLLM will run in the same process + and share the training GPUs. This avoids the need for a separate server but may cause resource contention + with training. + vllm_model_impl (`str`, *optional*, defaults to `"vllm"`): + Model implementation to use for vLLM. Must be one of `transformers` or `vllm`. `transformers`: Use the + `transformers` backend for model implementation. `vllm`: Use the `vllm` library for model implementation. + vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`): + Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but + waking the engine adds host–device transfer latency. + vllm_server_base_url (`str`, *optional*): + Base URL for the vLLM server (e.g., 'http://localhost:8000'). If provided, `vllm_server_host` and + `vllm_server_port` are ignored. + vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`): + Host of the vLLM server to connect to. Ignored if vllm_server_base_url is provided. + vllm_server_port (`int`, *optional*, defaults to `8000`): + Port of the vLLM server to connect to. Ignored if vllm_server_base_url is provided. + vllm_group_port (`int`, *optional*, defaults to `51216`): + Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port + is occupied, there is no need to change it. + vllm_server_timeout (`float`, *optional*, defaults to `240.0`): + Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up after the + timeout, a `ConnectionError` is raised. + vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`): + Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set to + `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when + launching the vLLM server via the `--vllm_tensor_parallel_size` flag. + vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.3`): + Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set to + `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when + launching the vLLM server via the `--vllm_gpu_memory_utilization` flag. + vllm_max_model_length (`int`, *optional*): + Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus + `max_completion_length`; if omitted, it is inferred from the model config. + + > Parameters that control the training + + loss_type (`str`, *optional*, defaults to `"dapo"`): + Specifies the loss formulation to use. Supported values are 'grpo', 'bnpo', 'dr_grpo', and 'dapo'. 'grpo': + Aggregates token-level losses by normalizing over sequence length. Not recommended due to length bias—this + approach tends to prefer shorter completions with positive advantages and longer ones with negative + advantages. 'dapo' (default): Aggregates token-level losses by normalizing with the number of active tokens + in the global accumulated batch. This method was introduced in the DAPO paper to eliminate length bias. + 'dr_grpo': Aggregates token-level losses by normalizing with a global constant. This method was introduced + in the Dr. GRPO paper to eliminate length bias. The value of the constant corresponds to + `max_completion_length`. 'bnpo': Aggregates token-level losses by normalizing with the number of active + tokens in the local batch. Note that normalization is performed over the local batch only, so results may + slightly vary depending on the local batch size, despite a constant effective batch size. When using + `per_device_train_batch_size==1`, the loss is equivalent to the GRPO loss. + num_iterations (`int`, *optional*, defaults to `1`): + Number of iterations per batch (denoted as μ in the algorithm). + generation_batch_size (`int`, *optional*): + Batch size to use for generation. If `None`, it defaults to the effective training batch size: + `per_device_train_batch_size * num_processes * steps_per_generation`. + steps_per_generation (`int`, *optional*): + Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`. + mask_truncated_completions (`bool`, *optional*, defaults to `False`): + When enabled, truncated completions are excluded from the loss calculation, preventing them from being + incorrectly penalized and introducing noise during training. According to the DAPO paper, this is a good + practice for training stability. + """ + + _VALID_DICT_FIELDS = TrainingArguments._VALID_DICT_FIELDS + ["model_init_kwargs"] + + model_init_kwargs: dict[str, Any] | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `transformers.AutoModelForCausalLM.from_pretrained`, used when the `model` argument of the `SDPOTrainer` is provided as a string." + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. " + "Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoProcessor.from_pretrained`. Also applied to " + "reward-model and reward-tokenizer loads." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={ + "help": "Whether to disable dropout in the model. This is useful for training with a reference model, as it prevents the model from generating different logprobs for the same input." + }, + ) + remove_unused_columns: bool = field( + default=False, + metadata={ + "help": "Whether to only keep the column 'prompt' in the dataset. If you use a custom reward function that requires any column other than 'prompts' and 'completions', you should keep this to `False`." + }, + ) + max_prompt_length: int | None = field( + default=512, + metadata={"help": "Maximum prompt length. Longer prompts are truncated from the left."}, + ) + num_generations: int = field( + default=8, + metadata={ + "help": "Number of generations to sample. The effective batch size (num_processes * per_device_batch_size * gradient_accumulation_steps) must be evenly divisible by this value." + }, + ) + num_generations_eval: int | None = field( + default=None, + metadata={ + "help": "Number of generations to sample during evaluation. This allows using fewer generations during evaluation to save computation. If `None`, uses the value of `num_generations`." + }, + ) + max_completion_length: int | None = field( + default=256, + metadata={"help": "Maximum length of the generated completion."}, + ) + ds3_gather_for_generation: bool = field( + default=True, + metadata={ + "help": "This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation, improving generation speed. However, disabling this option allows training models that exceed the VRAM capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible with vLLM generation." + }, + ) + shuffle_dataset: bool = field( + default=True, + metadata={"help": "Whether to shuffle the training dataset."}, + ) + generation_batch_size: int | None = field( + default=None, + metadata={ + "help": "Batch size to use for generation. If `None`, it defaults to the effective training batch size: `per_device_train_batch_size * num_processes * steps_per_generation`." + }, + ) + steps_per_generation: int | None = field( + default=None, + metadata={"help": "Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`."}, + ) + temperature: float = field( + default=1.0, + metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."}, + ) + top_p: float = field( + default=1.0, + metadata={ + "help": "Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to 1.0 to consider all tokens." + }, + ) + top_k: int = field( + default=0, + metadata={ + "help": "Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is disabled and all tokens are considered." + }, + ) + min_p: float | None = field( + default=None, + metadata={ + "help": "Minimum token probability, which will be scaled by the probability of the most likely token. It must be a value between 0.0 and 1.0. Typical values are in the 0.01-0.2 range." + }, + ) + generation_kwargs: dict[str, Any] | None = field( + default=None, + metadata={ + "help": "Additional keyword arguments to pass to `GenerationConfig` (if using transformers) or `SamplingParams` (if using vLLM) when sampling completions. This can be used to further customize the generation behavior, such as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that conflict with the other generation parameters (like `min_p`, `top_p`, etc.), they will override them." + }, + ) + chat_template_kwargs: dict[str, Any] | None = field( + default=None, + metadata={ + "help": "Additional keyword arguments to pass to the `apply_chat_template` function when generating completions." + }, + ) + repetition_penalty: float = field( + default=1.0, + metadata={ + "help": "Float that penalizes new tokens based on whether they appear in the prompt and the generated text so far. Values > 1.0 encourage the model to use new tokens, while values < 1.0 encourage the model to repeat tokens." + }, + ) + cache_implementation: str | None = field( + default=None, + metadata={"help": "Implementation of the cache method for faster generation when use_vllm is set to False."}, + ) + use_vllm: bool = field( + default=False, + metadata={ + "help": "Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for generation instead of the default model.generate(). Requires `vllm` to be installed." + }, + ) + use_teacher_server: bool = field( + default=False, + metadata={ + "help": "Compute teacher logprobs from the running vLLM generation server instead of a local teacher " + "forward. Only supported for `teacher_model_kind='live'` with `use_vllm=True`, `vllm_mode='server'`, " + "`distillation_weight=1.0` (pure distillation), and `distillation_mode` in {'sampled_token', " + "'topk_logits'} (the server returns the teacher's top-k logprobs, not the full vocabulary; `topk_logits` " + "distills over the teacher's own top-k support)." + }, + ) + vllm_mode: str = field( + default="colocate", + metadata={ + "help": "Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `'server'` or `'colocate'`. `'server'`: The trainer will send generation requests to a separate vLLM server. Make sure a TRL vLLM server is running (start with `trl vllm-serve`). `'colocate'`: vLLM will run in the same process and share the training GPUs. This avoids the need for a separate server but may cause resource contention with training." + }, + ) + vllm_model_impl: str = field( + default="vllm", + metadata={ + "help": "Model implementation to use for vLLM. Must be one of `transformers` or `vllm`. `transformers`: Use the `transformers` backend for model implementation. `vllm`: Use the `vllm` library for model implementation." + }, + ) + vllm_enable_sleep_mode: bool = field( + default=False, + metadata={ + "help": "Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but waking the engine adds host–device transfer latency." + }, + ) + vllm_server_base_url: str | None = field( + default=None, + metadata={ + "help": "Base URL for the vLLM server (e.g., 'http://localhost:8000'). If provided, `vllm_server_host` and `vllm_server_port` are ignored." + }, + ) + vllm_server_host: str = field( + default="0.0.0.0", + metadata={"help": "Host of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."}, + ) + vllm_server_port: int = field( + default=8000, + metadata={"help": "Port of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."}, + ) + vllm_group_port: int = field( + default=51216, + metadata={ + "help": "Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port is occupied, there is no need to change it." + }, + ) + vllm_server_timeout: float = field( + default=240.0, + metadata={ + "help": "Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up after the timeout, a `ConnectionError` is raised." + }, + ) + vllm_tensor_parallel_size: int = field( + default=1, + metadata={ + "help": "Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when launching the vLLM server via the `--vllm_tensor_parallel_size` flag." + }, + ) + vllm_gpu_memory_utilization: float = field( + default=0.3, + metadata={ + "help": "Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when launching the vLLM server via the `--vllm_gpu_memory_utilization` flag." + }, + ) + vllm_max_model_length: int | None = field( + default=None, + metadata={ + "help": "Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus `max_completion_length`; if omitted, it is inferred from the model config." + }, + ) + num_iterations: int = field( + default=1, + metadata={"help": "Number of iterations per batch (denoted as μ in the algorithm)."}, + ) + loss_type: str = field( + default="dapo", + metadata={ + "help": "Specifies the loss formulation to use. Supported values are 'grpo', 'bnpo', 'dr_grpo', and 'dapo'. 'grpo': Aggregates token-level losses by normalizing over sequence length. Not recommended due to length bias—this approach tends to prefer shorter completions with positive advantages and longer ones with negative advantages. 'dapo' (default): Aggregates token-level losses by normalizing with the number of active tokens in the global accumulated batch. This method was introduced in the DAPO paper to eliminate length bias. 'dr_grpo': Aggregates token-level losses by normalizing with a global constant. This method was introduced in the Dr. GRPO paper to eliminate length bias. The value of the constant corresponds to `max_completion_length`. 'bnpo': Aggregates token-level losses by normalizing with the number of active tokens in the local batch. Note that normalization is performed over the local batch only, so results may slightly vary depending on the local batch size, despite a constant effective batch size. When using `per_device_train_batch_size==1`, the loss is equivalent to the GRPO loss." + }, + ) + mask_truncated_completions: bool = field( + default=False, + metadata={ + "help": "When enabled, truncated completions are excluded from the loss calculation, preventing them from being incorrectly penalized and introducing noise during training. According to the DAPO paper, this is a good practice for training stability." + }, + ) + dont_reprompt_on_self_success: bool = field( + default=True, + metadata={"help": "Skip reprompting when model generates correct response."}, + ) + beta: float = field( + default=0.0, + metadata={ + "help": "KL coefficient. If `0.0` (default), the reference model is not loaded, reducing memory usage and improving training speed. [DeepSeek-R1 incentivizes reasoning in LLMs through reinforcement learning](https://huggingface.co/papers/2501.12948) use a value of `0.001`." + }, + ) + epsilon: float = field( + default=0.2, + metadata={"help": "Epsilon value for clipping."}, + ) + epsilon_high: float | None = field( + default=None, + metadata={ + "help": "Upper-bound epsilon value for clipping. If not specified, it defaults to the same value as the lower-bound specified in argument `epsilon`. Paper DAPO recommends `0.28`." + }, + ) + importance_sampling_level: str = field( + default="token", + metadata={ + "help": "Controls whether importance sampling ratios are computed at the `'token'` or `'sequence'` level. `'token'` keeps the raw per-token log-probability ratios (one weight per token). `'sequence'` averages the log-probability ratios across valid tokens to produce a single ratio per sequence. The GSPO paper shows that sequence-level sampling often yields more stable training and better alignment with sequence-level rewards." + }, + ) + reward_weights: list[float] | None = field( + default=None, + metadata={ + "help": "Weights for each reward function. Must match the number of reward functions. If `None`, all rewards are weighted equally with weight `1.0`." + }, + ) + scale_rewards: str | bool = field( + default="group", + metadata={ + "help": "Specifies the scaling strategy for rewards. Supported values are: `True` or `'group'` (default): rewards are scaled by the standard deviation within each group, ensuring unit variance within a group. `'batch'`: rewards are scaled by the standard deviation across the entire batch, as recommended in the PPO Lite paper. `False` or `'none'`: no scaling is applied. The Dr. GRPO paper recommends not scaling rewards, as scaling by the standard deviation introduces a question-level difficulty bias." + }, + ) + distillation_alpha: float = field( + default=1.0, + metadata={ + "help": "Divergence interpolation coefficient. Sampled-token SDPO requires the official reverse-KL setting " + "`distillation_alpha=1.0`." + }, + ) + distillation_mode: Literal["sampled_token", "full_logits", "topk_logits"] = field( + default="sampled_token", + metadata={ + "help": "Distillation objective mode. `sampled_token` is the default SDPO mode and requires " + "`distillation_alpha=1.0`." + }, + ) + distillation_topk: int | None = field( + default=None, + metadata={ + "help": "Top-k approximation for logit-level SDPO. Must be set when `distillation_mode=topk_logits` and left " + "unset otherwise." + }, + ) + distillation_is_clip: float | None = field( + default=2.0, + metadata={ + "help": "Clipping coefficient for importance sampling in self-distillation. `None` disables clipping." + }, + ) + distillation_add_tail: bool = field( + default=False, + metadata={"help": "Whether to add a tail bucket for non-top-k probability mass."}, + ) + distillation_weight: float = field( + default=1.0, + metadata={ + "help": "Convex combination weight between the policy and self-distillation objectives. The loss is " + "`(1 - distillation_weight) * policy_loss + distillation_weight * distillation_loss`. Must be in `[0, 1]`. " + "`1.0` (default) trains purely on self-distillation, `0.0` falls back to the standard GRPO-style policy " + "gradient, and intermediate values blend both." + }, + ) + teacher_model_kind: str = field( + default="ema", + metadata={ + "help": "Semantic teacher choice. `base` uses the initial student, `live` uses the current student, " + "and `ema` uses an exponentially averaged teacher." + }, + ) + teacher_update_rate: float = field( + default=0.05, + metadata={"help": "Teacher update rate used for EMA teacher synchronization."}, + ) + teacher_sync_steps: int = field( + default=1, + metadata={"help": "How often to synchronize the EMA teacher model."}, + ) + max_reprompt_len: int = field( + default=10240, + metadata={"help": "Maximum length for reprompting in self-distillation."}, + ) + use_successful_as_teacher: bool = field( + default=True, + metadata={"help": "Use successful rollouts as implicit feedback for self-distillation."}, + ) + success_reward_threshold: float = field( + default=1.0, + metadata={"help": "Minimum reward for a rollout to be considered a successful demonstration."}, + ) + reprompt_template: str = field( + default="{prompt}{solution}{feedback}\n\nCorrectly solve the original question.\n", + metadata={"help": "Template for reprompting the teacher with a successful demonstration."}, + ) + solution_template: str = field( + default="\nCorrect solution:\n\n{successful_previous_attempt}\n\n", + metadata={"help": "Template for formatting the successful demonstration text."}, + ) + feedback_template: str = field( + default="\nThe following is feedback from your unsuccessful earlier attempt:\n\n{feedback_raw}\n\n", + metadata={"help": "Template for formatting environment feedback for reprompting."}, + ) + include_environment_feedback: bool = field( + default=False, + metadata={"help": "Whether to include environment feedback in teacher reprompts when available."}, + ) + environment_feedback_only_without_solution: bool = field( + default=False, + metadata={"help": "Whether to use feedback only when no successful solution is available."}, + ) + remove_thinking_from_demonstration: bool = field( + default=False, + metadata={"help": "Whether to remove ... blocks from the demonstration text."}, + ) + diagnostics_warning_interval: int = field( + default=10, + metadata={ + "help": "Emit repeated trainer diagnostics every N consecutive degenerate steps. Set to 0 to disable." + }, + ) + diagnostics_flat_tolerance: float = field( + default=1e-8, + metadata={ + "help": "Tolerance used to decide whether reward variance or reprompt activity is effectively zero." + }, + ) + + def __post_init__(self): + super().__post_init__() + if not 0.0 <= self.distillation_weight <= 1.0: + raise ValueError(f"`distillation_weight` must be in [0, 1], got {self.distillation_weight}.") + if self.distillation_mode == "sampled_token" and self.distillation_alpha != 1.0: + raise ValueError( + "`distillation_mode='sampled_token'` only supports reverse KL, so it requires " + f"`distillation_alpha=1.0`, got {self.distillation_alpha}." + ) + num_processes = self.world_size + if self.generation_batch_size is None and self.steps_per_generation is None: + self.steps_per_generation = self.gradient_accumulation_steps + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + elif self.generation_batch_size is not None and self.steps_per_generation is None: + global_batch_size = self.per_device_train_batch_size * num_processes + if self.generation_batch_size % global_batch_size != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by the global batch size ({global_batch_size})." + ) + self.steps_per_generation = self.generation_batch_size // global_batch_size + elif self.generation_batch_size is None and self.steps_per_generation is not None: + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + else: + raise ValueError("'generation_batch_size' and 'steps_per_generation' can not both be configured") + + if self.generation_batch_size % self.num_generations != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by num_generations ({self.num_generations})." + ) + + if self.do_eval and self.eval_strategy != "no": + num_generations_eval = self.num_generations_eval or self.num_generations + if (self.per_device_eval_batch_size * num_processes) % num_generations_eval != 0: + raise ValueError( + f"The global eval batch size ({self.per_device_eval_batch_size} * {num_processes}) must be " + f"divisible by the number of generations used for evaluation ({num_generations_eval})." + ) + + self.scale_rewards = {True: "group", False: "none"}.get(self.scale_rewards, self.scale_rewards) + + if self.epsilon_high is None: + self.epsilon_high = self.epsilon diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdpo/sdpo_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdpo/sdpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..a0441fe6ea18c1ee2a70591c067e30981973a98a --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdpo/sdpo_trainer.py @@ -0,0 +1,1781 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import math +import re +import textwrap +from collections import defaultdict +from contextlib import nullcontext +from dataclasses import dataclass +from functools import partial +from typing import Any + +import datasets +import torch +from accelerate.logging import get_logger +from accelerate.utils import gather_object, is_peft_model +from datasets import Dataset, IterableDataset +from torch import nn +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from torch.utils.data import DataLoader, Sampler +from transformers import ( + AutoModelForSequenceClassification, + AutoProcessor, + AutoTokenizer, + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, +) +from transformers.trainer_utils import seed_worker +from transformers.utils import is_datasets_available, is_liger_kernel_available, is_peft_available + +from ...data_utils import apply_chat_template, is_conversational +from ...models import prepare_deepspeed, prepare_fsdp, unwrap_model_for_generation +from ...models.utils import _ForwardRedirection +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import ( + RepeatSampler, + create_model_from_path, + disable_dropout_in_model, + get_config_model_id, + identity, + pad, + selective_log_softmax, + split_tensor_dict, + use_adapter, +) +from ..utils import prepare_peft_model +from .loss_utils import ( + add_tail_bucket, + apply_importance_sampling_clipping, + compute_divergence, + compute_full_logit_self_distillation_loss, + compute_sampled_token_self_distillation_loss, + compute_topk_self_distillation_loss, +) +from .sdpo_config import SDPOConfig +from .teacher_sync import PEFTAdapterEMACallback, SyncTeacherModelCallback, is_pure_lora_training + + +logger = get_logger(__name__) + + +if is_peft_available(): + from peft import PeftConfig + +if is_liger_kernel_available(): + from liger_kernel.chunked_loss import LigerFusedLinearJSDLoss + + +TrainingBatch = dict[str, torch.Tensor | Any] + + +def build_teacher_request_inputs( + input_ids: torch.Tensor, + attention_mask: torch.Tensor, + prompt_attention_mask: torch.Tensor, +) -> tuple[list[list[int]], list[int], list[int]]: + """Trim padded batch tensors into per-sample (prompt+completion) sequences for teacher-server requests.""" + if input_ids.shape != attention_mask.shape: + raise ValueError( + f"input_ids and attention_mask must have the same shape, got {input_ids.shape} and {attention_mask.shape}." + ) + + input_ids_cpu = input_ids.detach().cpu() + attention_mask_cpu = attention_mask.detach().cpu().bool() + prompt_lengths = prompt_attention_mask.detach().cpu().sum(dim=1).to(torch.long) + + trimmed_input_ids: list[list[int]] = [] + prompt_lengths_list: list[int] = [] + completion_lengths_list: list[int] = [] + for row, mask, prompt_length in zip(input_ids_cpu, attention_mask_cpu, prompt_lengths, strict=True): + trimmed_row = row[mask] + prompt_len = int(prompt_length.item()) + if prompt_len < 0 or prompt_len > trimmed_row.numel(): + raise ValueError( + f"Invalid prompt length {prompt_len} for trimmed sequence of length {trimmed_row.numel()}." + ) + trimmed_input_ids.append(trimmed_row.tolist()) + prompt_lengths_list.append(prompt_len) + completion_lengths_list.append(int(trimmed_row.numel()) - prompt_len) + return trimmed_input_ids, prompt_lengths_list, completion_lengths_list + + +@dataclass +class DistillationLogits: + """Aligned logits and masks used to compute a self-distillation objective.""" + + completion_ids: torch.Tensor + completion_mask: torch.Tensor + loss_mask: torch.Tensor + student_logits: torch.Tensor + teacher_logits: torch.Tensor + + +def _extract_last_user_text(messages: list[dict[str, Any]]) -> str: + """Extract the text content from the last user message in a conversational prompt.""" + last_message = messages[-1] + if last_message.get("role") != "user": + raise ValueError( + f"Self-distillation teacher prompt construction expects the conversation to end with a user turn, " + f"but the last message has role '{last_message.get('role')}'. " + f"Prompts ending with assistant prefills or tool turns are not supported." + ) + content = last_message.get("content", "") + if isinstance(content, list): + return " ".join(part.get("text", "") for part in content if part.get("type") == "text") + return content + + +class SuccessfulRolloutTeacherContextBuilder: + """Builds teacher contexts from successful rollouts""" + + def __init__(self, trainer): + self.trainer = trainer + self.last_metrics: dict[str, float] = {} + + def _build_reprompt_text(self, prompt_text: str, solution_text: str, feedback_text: str) -> str: + return self.trainer.args.reprompt_template.format( + prompt=prompt_text, + solution=solution_text, + feedback=feedback_text, + ) + + def _tokenize_teacher_messages( + self, teacher_messages_list: list[str | list[dict[str, Any]]] + ) -> dict[str, torch.Tensor]: + device = self.trainer.accelerator.device + teacher_prompt_ids_list = self.trainer._tokenize_prompts_untruncated(teacher_messages_list) + teacher_prompt_ids = [ + torch.as_tensor(ids[-self.trainer.args.max_reprompt_len :], device=device) + for ids in teacher_prompt_ids_list + ] + teacher_prompt_mask = [torch.ones(len(ids), dtype=torch.long, device=device) for ids in teacher_prompt_ids] + return { + "prompt_ids": pad( + teacher_prompt_ids, padding_value=self.trainer._tokenizer.pad_token_id, padding_side="left" + ), + "prompt_mask": pad(teacher_prompt_mask, padding_value=0, padding_side="left"), + } + + def build( + self, + output: dict[str, torch.Tensor | Any], + prompts: list[Any], + rewards: torch.Tensor, + feedbacks: list[Any] | None = None, + ) -> dict[str, torch.Tensor]: + device = self.trainer.accelerator.device + mode = "train" if self.trainer.model.training else "eval" + num_generations = self.trainer.num_generations if mode == "train" else self.trainer.num_generations_eval + completion_ids = output["completion_ids"] + completion_mask = output["completion_mask"] + + num_local = len(prompts) + process_start = self.trainer.accelerator.process_index * num_local + process_slice = slice(process_start, process_start + num_local) + + # Rewards arrive already locally sliced (per-process) from the rollout mixin; re-gather them so + # the mining loop can find successful rollouts across all processes within each generation group. + all_rewards = self.trainer.accelerator.gather(rewards) + # Completion tensors are padded to the local max length per rank; align shapes before gathering. + # Use separate variables so the original completion_ids/completion_mask stay unpadded for the + # teacher concat (they must match the student's sequence length for logits_to_keep alignment). + padded_completion_ids = self.trainer.accelerator.pad_across_processes( + completion_ids, dim=1, pad_index=self.trainer._tokenizer.pad_token_id + ) + all_completion_ids = self.trainer.accelerator.gather(padded_completion_ids) + all_prompts = gather_object(prompts) + total_samples = all_rewards.shape[0] + all_feedbacks = gather_object(feedbacks) if feedbacks is not None else [None] * total_samples + + threshold = self.trainer.args.success_reward_threshold + dont_reprompt_self = self.trainer.args.dont_reprompt_on_self_success + feedback_only_without_solution = self.trainer.args.environment_feedback_only_without_solution + self_distillation_mask = torch.zeros(total_samples, device=device) + num_with_solution = 0 + num_with_feedback_available = 0 + num_with_feedback_used = 0 + success_group_count = 0 + successful_demo_indices: list[int | None] = [None] * total_samples + use_feedback_flags: list[bool] = [False] * total_samples + has_solution_flags: list[bool] = [False] * total_samples + + for i in range(total_samples): + group_start = (i // num_generations) * num_generations + group_end = group_start + num_generations + + successful = [] + if self.trainer.args.use_successful_as_teacher: + for j in range(group_start, group_end): + if dont_reprompt_self and j == i: + continue + if all_rewards[j].item() >= threshold: + successful.append(j) + + if i % num_generations == 0: + # Count groups with any successful rollout, ignoring self-exclusion which only + # affects per-sample teacher assignment, not whether the group has successes. + group_has_success = any(all_rewards[j].item() >= threshold for j in range(group_start, group_end)) + if group_has_success: + success_group_count += 1 + + raw_feedback = all_feedbacks[i] + has_feedback = isinstance(raw_feedback, str) and raw_feedback.strip() != "" + if has_feedback: + num_with_feedback_available += 1 + + has_solution = len(successful) > 0 + has_solution_flags[i] = has_solution + if has_solution: + successful_demo_indices[i] = successful[0] + use_feedback = ( + self.trainer.args.include_environment_feedback + and has_feedback + and (not feedback_only_without_solution or not has_solution) + ) + use_feedback_flags[i] = use_feedback + if use_feedback: + num_with_feedback_used += 1 + if has_solution or use_feedback: + self_distillation_mask[i] = 1.0 + if has_solution: + num_with_solution += 1 + + local_teacher_messages = [] + local_self_distillation_mask = self_distillation_mask[process_slice] + for global_idx in range(process_start, process_start + num_local): + original_prompt = all_prompts[global_idx] + raw_feedback = all_feedbacks[global_idx] + has_solution = has_solution_flags[global_idx] + use_feedback = use_feedback_flags[global_idx] + + if not has_solution and not use_feedback: + local_teacher_messages.append(original_prompt) + continue + + solution_text = "" + if has_solution: + demo_idx = successful_demo_indices[global_idx] + if demo_idx is None: + raise RuntimeError("Expected a successful demonstration index for an active SDPO teacher prompt.") + demo_ids = all_completion_ids[demo_idx] + demo_ids = demo_ids[demo_ids != self.trainer._tokenizer.pad_token_id] + demo_text = self.trainer.processing_class.decode(demo_ids, skip_special_tokens=True) + + if self.trainer.args.remove_thinking_from_demonstration: + demo_text = re.sub(r".*?", "", demo_text, flags=re.DOTALL).strip() + + solution_text = self.trainer.args.solution_template.format(successful_previous_attempt=demo_text) + + feedback_text = "" + if use_feedback: + feedback_text = self.trainer.args.feedback_template.format(feedback_raw=raw_feedback) + + if isinstance(original_prompt, list): + system_messages = original_prompt[:-1] + prompt_text = _extract_last_user_text(original_prompt) + reprompt_text = self._build_reprompt_text(prompt_text, solution_text, feedback_text) + local_teacher_messages.append(system_messages + [{"role": "user", "content": reprompt_text}]) + else: + local_teacher_messages.append(self._build_reprompt_text(original_prompt, solution_text, feedback_text)) + + teacher_batch = self._tokenize_teacher_messages(local_teacher_messages) + teacher_input_ids = torch.cat([teacher_batch["prompt_ids"], completion_ids], dim=1) + teacher_attention_mask = torch.cat([teacher_batch["prompt_mask"], completion_mask], dim=1) + + batch_size = total_samples if total_samples > 0 else 1 + num_groups = max(1, total_samples // max(1, num_generations)) + self.last_metrics = { + "self_distillation/success_group_fraction": success_group_count / num_groups, + "self_distillation/success_sample_fraction": num_with_solution / batch_size, + "self_distillation/feedback_available_fraction": num_with_feedback_available / batch_size, + "self_distillation/feedback_used_fraction": num_with_feedback_used / batch_size, + "self_distillation/reprompt_sample_fraction": self_distillation_mask.float().mean().item(), + } + + return { + "teacher_input_ids": teacher_input_ids, + "teacher_attention_mask": teacher_attention_mask, + "self_distillation_mask": local_self_distillation_mask, + } + + +class SDPOTrainer(_BaseTrainer): + """ + Trainer for Self-Distillation Policy Optimization (SDPO). + + SDPO augments on-policy optimization with self-distillation from the model's own high-reward trajectories. It + converts tokenized feedback into a dense learning signal without any external teacher or explicit reward model. + SDPO treats the current model conditioned on feedback as a self-teacher and distills its feedback-informed + next-token predictions back into the policy. + """ + + config_cls = SDPOConfig + _tag_names = ["trl", "sdpo"] + _name = "SDPO" + # docstyle-ignore + _paper = { + "title": "Reinforcement Learning via Self-Distillation", + "id": "2601.20802", + "citation": textwrap.dedent("""\ + @article{hubotter2026sdpo, + title = {{Reinforcement Learning via Self-Distillation}}, + author = {Jonas H\\"ubotter and Frederike L\\"ubeck and Lejs Behric and Anton Baumann and Marco Bagatella and Daniel Marta and Ido Hakimi and Idan Shenfeld and Thomas Kleine Buening and Carlos Guestrin and Andreas Krause}, + year = 2026, + eprint = {arXiv:2601.20802} + }"""), + } + + def __init__( + self, + model: str | PreTrainedModel | nn.Module, + reward_funcs: Any | list[Any] | None = None, + args: SDPOConfig | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + peft_config=None, + ): + if reward_funcs is None or (isinstance(reward_funcs, list) and len(reward_funcs) == 0): + raise ValueError("`reward_funcs` is required for SDPOTrainer because SDPO must score rollouts.") + if train_dataset is None: + raise ValueError("`train_dataset` is required") + + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + model = create_model_from_path(model, **model_init_kwargs) + elif args.model_init_kwargs is not None: + logger.warning( + "You passed `model_init_kwargs` to the self-distillation config, but `model` is already " + "instantiated. The `model_init_kwargs` will be ignored." + ) + + self.model_kwarg_keys = ( + inspect.signature(model.forward).parameters.keys() + if not hasattr(model, "get_base_model") + else inspect.signature(model.get_base_model().forward).parameters.keys() + ) + + if peft_config is None and getattr(model, "peft_config", None) is not None: + logger.warning( + "The provided self-distillation student model already contains a PEFT adapter. " + "This setup is accepted but not directly supported. In particular, `teacher_model_kind='base'` " + "may refer to the underlying base weights rather than the exact initially loaded student state " + "including its adapter. For unambiguous teacher behavior, start from a merged/non-adapter model " + "or manage separate adapters explicitly." + ) + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config`. Pass either a base " + "model with `peft_config`, or a pre-wrapped PEFT model." + ) + if peft_config is not None or (is_peft_available() and getattr(model, "peft_config", None) is not None): + model = prepare_peft_model(model, peft_config, args) + + if processing_class is None: + processing_class = AutoProcessor.from_pretrained( + get_config_model_id(model.config), + truncation_side="left", + padding_side="left", + trust_remote_code=args.trust_remote_code, + ) + + if isinstance(processing_class, ProcessorMixin): + self._tokenizer = processing_class.tokenizer + elif isinstance(processing_class, PreTrainedTokenizerBase): + self._tokenizer = processing_class + else: + raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`") + + if self._tokenizer.pad_token is None: + self._tokenizer.pad_token = self._tokenizer.eos_token + + self.max_prompt_length = args.max_prompt_length + self.max_completion_length = args.max_completion_length + self.num_generations = args.num_generations + self.num_generations_eval = args.num_generations_eval or args.num_generations + self.num_iterations = args.num_iterations + self.shuffle_dataset = args.shuffle_dataset + self.loss_type = args.loss_type + self.mask_truncated_completions = args.mask_truncated_completions + self.temperature = args.temperature + self.use_vllm = args.use_vllm + self.chat_template_kwargs = args.chat_template_kwargs or {} + self._step = 0 + self._buffered_inputs = None + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + self._diagnostic_counters = { + "train": defaultdict(int), + "eval": defaultdict(int), + } + + self.generation_kwargs = { + "max_new_tokens": self.max_completion_length, + "do_sample": True, + "pad_token_id": self._tokenizer.pad_token_id, + "bos_token_id": self._tokenizer.bos_token_id, + "eos_token_id": self._tokenizer.eos_token_id, + "temperature": args.temperature, + "top_p": args.top_p, + "top_k": args.top_k, + "min_p": args.min_p, + "repetition_penalty": args.repetition_penalty, + "cache_implementation": args.cache_implementation, + } + if args.generation_kwargs is not None: + self.generation_kwargs.update(args.generation_kwargs) + self.generation_config = GenerationConfig(**self.generation_kwargs, disable_compile=True) + + if hasattr(model, "warnings_issued"): + model.warnings_issued["estimate_tokens"] = True + + # Teacher logprobs from the running vLLM generation server (reuses the synced student weights) instead of a + # local teacher forward. MVP: `live` teacher only — the generation server holds the current student weights. + self.use_teacher_server = args.use_teacher_server + if self.use_teacher_server: + if not (args.use_vllm and args.vllm_mode == "server"): + raise ValueError( + "`use_teacher_server=True` requires `use_vllm=True` and `vllm_mode='server'`: teacher logprobs are " + "served by the same vLLM server used for generation." + ) + if args.teacher_model_kind != "live": + raise ValueError( + "`use_teacher_server=True` only supports `teacher_model_kind='live'` (the generation server holds " + f"the current student weights), got {args.teacher_model_kind!r}." + ) + if args.distillation_weight != 1.0: + raise ValueError( + "`use_teacher_server=True` only supports pure self-distillation with `distillation_weight=1.0`, " + f"got {args.distillation_weight}. A convex blend with the policy loss needs the full-vocabulary " + "logits, which the server does not return." + ) + if args.distillation_mode not in ("sampled_token", "topk_logits"): + raise ValueError( + "`use_teacher_server=True` only supports `distillation_mode` in {'sampled_token', 'topk_logits'}, " + f"got {args.distillation_mode!r}. The server returns the teacher's top-k logprobs, not the full " + "vocabulary, so `full_logits` is unavailable. Note `topk_logits` distills over the teacher's own " + "top-k support (the server cannot score the student's top-k indices)." + ) + if args.use_liger_kernel: + raise ValueError( + "`use_teacher_server=True` is incompatible with `use_liger_kernel`: the server returns top-k " + "logprobs while the Liger fused loss needs full-vocabulary hidden states." + ) + # Liger fused JSD loss for `full_logits`: same generalized JSD as `compute_divergence`, so alpha maps to beta. + self.use_liger_loss = False + if args.use_liger_kernel: + if not is_liger_kernel_available(): + raise ImportError( + "Liger is required to use `use_liger_kernel` as the self-distillation loss. Run " + "`pip install liger-kernel`." + ) + if args.distillation_weight != 1.0: + raise ValueError( + "`use_liger_kernel` only supports pure self-distillation with `distillation_weight=1.0`, got " + f"{args.distillation_weight}. A convex blend with the policy loss needs the policy-gradient term, " + "so the fused distillation kernel offers no benefit there." + ) + if args.distillation_mode != "full_logits": + raise ValueError( + "`use_liger_kernel` only supports `distillation_mode='full_logits'`, got " + f"{args.distillation_mode!r}. The fused JSD kernel operates on the full vocabulary and cannot " + "express the top-k support or sampled-token objectives." + ) + if args.distillation_is_clip is not None: + raise ValueError( + "`use_liger_kernel` is incompatible with `distillation_is_clip`: the fused kernel does not expose " + "per-token losses for importance-sampling clipping." + ) + if args.loss_type != "bnpo": + logger.warning( + "The Liger fused loss reduces with a token-level mean (equivalent to `loss_type='bnpo'`); the " + f"configured `loss_type={args.loss_type!r}` is ignored on the Liger path." + ) + self.liger_jsd_loss = LigerFusedLinearJSDLoss( + beta=args.distillation_alpha, + ignore_index=-100, + temperature=args.temperature, + compiled=False, + weight_hard_loss=0.0, + weight_soft_loss=1.0, + ) + self._forward_redirection = _ForwardRedirection() + self.use_liger_loss = True + + super().__init__( + model=model, + args=args, + data_collator=identity, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + callbacks=callbacks, + optimizers=optimizers, + compute_loss_func="non-None value to disable scaling", + ) + + self._last_loaded_step = -1 if self.use_vllm else 0 + if self.use_vllm: + from ...generation.vllm_generation import VLLMGeneration + + self.vllm_generation = VLLMGeneration( + model=self.model, + accelerator=self.accelerator, + processing_class=self.processing_class, + mode=args.vllm_mode, + server_base_url=args.vllm_server_base_url, + server_host=args.vllm_server_host, + server_port=args.vllm_server_port, + group_port=args.vllm_group_port, + server_timeout=args.vllm_server_timeout, + tensor_parallel_size=args.vllm_tensor_parallel_size, + gpu_memory_utilization=args.vllm_gpu_memory_utilization, + max_model_length=args.vllm_max_model_length, + max_num_seqs=args.per_device_train_batch_size + * args.vllm_tensor_parallel_size + * args.steps_per_generation, + enable_sleep_mode=args.vllm_enable_sleep_mode, + model_impl=args.vllm_model_impl, + repetition_penalty=args.repetition_penalty, + temperature=self.temperature, + top_p=args.top_p, + top_k=args.top_k, + min_p=args.min_p, + max_completion_length=self.max_completion_length, + logprobs=None, + generation_kwargs=args.generation_kwargs, + ) + + # Per-rank read-only client to the same generation server for teacher scoring (weights are synced there by + # `VLLMGeneration`; scoring needs no weight-update communicator). Mirrors the distillation trainer's + # `teacher_client`. + self.teacher_client = None + if self.use_teacher_server: + from ...generation.vllm_client import VLLMClient + + base_url = args.vllm_server_base_url or f"http://{args.vllm_server_host}:{args.vllm_server_port}" + self.teacher_client = VLLMClient(base_url=base_url, connection_timeout=args.vllm_server_timeout) + + if args.disable_dropout: + disable_dropout_in_model(self.model) + + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + self._setup_teacher_model() + self.model_accepts_loss_kwargs = False + + self.importance_sampling_level = args.importance_sampling_level + self.scale_rewards = args.scale_rewards + self.epsilon_low = args.epsilon + self.epsilon_high = args.epsilon_high + self.beta = args.beta + + if args.importance_sampling_level == "sequence" and args.loss_type in ["bnpo", "dr_grpo", "dapo"]: + logger.warning( + f"When using `importance_sampling_level='sequence'`, the `'{args.loss_type}'` loss sums per-token " + "contributions, which effectively weights each sequence by its completion length instead of " + "optimizing the per-sequence objective. To reproduce the GSPO paper's setup, set `loss_type='grpo'` " + "(see https://huggingface.co/docs/trl/main/en/paper_index#group-sequence-policy-optimization)." + ) + + if not isinstance(reward_funcs, list): + reward_funcs = [reward_funcs] + self.reward_func_names = [] + for i, reward_func in enumerate(reward_funcs): + if isinstance(reward_func, str): + reward_model_init_kwargs = args.model_init_kwargs or {} + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + reward_model_init_kwargs["device_map"] = None + reward_model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + reward_funcs[i] = AutoModelForSequenceClassification.from_pretrained( + reward_func, + num_labels=1, + **reward_model_init_kwargs, + ) + if isinstance(reward_funcs[i], nn.Module): + self.reward_func_names.append(get_config_model_id(reward_funcs[i].config).split("/")[-1]) + else: + self.reward_func_names.append(reward_funcs[i].__name__) + self.reward_funcs = reward_funcs + + if args.reward_weights is not None: + if len(args.reward_weights) != len(self.reward_funcs): + raise ValueError("Number of reward weights must match number of reward functions") + self.reward_weights = torch.tensor(args.reward_weights, dtype=torch.float32) + else: + self.reward_weights = torch.ones(len(self.reward_funcs), dtype=torch.float32) + + if reward_processing_classes is None: + reward_processing_classes = [None] * len(self.reward_funcs) + elif not isinstance(reward_processing_classes, list): + reward_processing_classes = [reward_processing_classes] + if len(reward_processing_classes) != len(self.reward_funcs): + raise ValueError("Number of reward processing classes must match number of reward functions") + + for i, (reward_processing_class, reward_func) in enumerate( + zip(reward_processing_classes, self.reward_funcs, strict=True) + ): + if isinstance(reward_func, PreTrainedModel): + if reward_processing_class is None: + reward_processing_class = AutoTokenizer.from_pretrained( + get_config_model_id(reward_func.config), trust_remote_code=args.trust_remote_code + ) + if reward_processing_class.pad_token_id is None: + reward_processing_class.pad_token = reward_processing_class.eos_token + reward_func.config.pad_token_id = reward_processing_class.pad_token_id + reward_processing_classes[i] = reward_processing_class + self.reward_processing_classes = reward_processing_classes + + for i, reward_func in enumerate(self.reward_funcs): + if isinstance(reward_func, nn.Module): + if self.is_deepspeed_enabled: + self.reward_funcs[i] = prepare_deepspeed(reward_func, self.accelerator) + elif self.is_fsdp_enabled: + self.reward_funcs[i] = prepare_fsdp(reward_func, self.accelerator) + else: + self.reward_funcs[i] = self.accelerator.prepare_model(reward_func, evaluation_mode=True) + + self.teacher_context_builder = SuccessfulRolloutTeacherContextBuilder(self) + + def _set_signature_columns_if_needed(self): + if self._signature_columns is None: + self._signature_columns = ["prompt", "privileged_context"] + + def _dispatch_self_distillation_callback(self, event_name: str, **payload) -> None: + for callback in self.callback_handler.callbacks: + callback_fn = getattr(callback, event_name, None) + if callback_fn is not None: + callback_fn( + args=self.args, + state=self.state, + control=self.control, + model=self.model, + processing_class=self.processing_class, + **payload, + ) + + def _setup_teacher_model(self) -> None: + """Prepare teacher state according to the semantic teacher choice. + + Resolve `teacher_model_kind` × PEFT state into the effective teacher: + + - `"live"` (any model): + Teacher is the student. No divergence, no callback. + - `"base"` + PEFT model: + Teacher reuses `self.model`; the base weights are recovered downstream by disabling the adapter via + `use_adapter` during teacher forward. + - `"base"` + non-PEFT model: + Teacher is a frozen deepcopy of the initial student (falls through to the copy branch below). + - `"ema"` + pure-LoRA training: + Teacher reuses `self.model`; a dedicated `"teacher"` LoRA adapter is attached and updated by + `PEFTAdapterEMACallback`. Teacher forward switches to that adapter downstream. + - `"ema"` (otherwise): + Teacher is a frozen deepcopy synchronized each step by `SyncTeacherModelCallback`. + + Must be called after `super().__init__` so that `self.callback_handler` is available. + """ + + teacher_model_kind = self.args.teacher_model_kind + + if teacher_model_kind == "live": + self.teacher_model = self.model + return + + if teacher_model_kind == "base" and is_peft_model(self.model): + self.teacher_model = self.model + return + + if self._use_peft_ema_teacher_adapter(): + # Must run after super().__init__ so self.callback_handler exists. + self.add_callback( + PEFTAdapterEMACallback( + model=self.model, + teacher_adapter_name="teacher", + update_rate=self.args.teacher_update_rate, + sync_steps=self.args.teacher_sync_steps, + accelerator=self.accelerator, + ) + ) + self.teacher_model = self.model + return + + if is_peft_model(self.model): + raise ValueError( + "`teacher_model_kind='ema'` with a non-pure-LoRA PEFT model is not supported: the separate EMA " + "teacher cannot be parameter-matched to the PEFT student. Use pure-LoRA training, a non-PEFT model, " + "or `teacher_model_kind` in {'live', 'base'}." + ) + + # Build the teacher from the model path (like the GRPO/DPO reference model) rather than deep-copying the + # student: under ZeRO-3 the student params are already sharded, so a deep copy would clone empty shards. + model_init_kwargs = self.args.model_init_kwargs or {} + if self.args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model_init_kwargs.setdefault("trust_remote_code", self.args.trust_remote_code) + self.teacher_model = create_model_from_path(get_config_model_id(self.model.config), **model_init_kwargs) + self.teacher_model.requires_grad_(False) + self.teacher_model.eval() + if self.is_deepspeed_enabled: + self.teacher_model = prepare_deepspeed(self.teacher_model, self.accelerator) + elif self.is_fsdp_enabled: + self.teacher_model = prepare_fsdp(self.teacher_model, self.accelerator) + else: + self.teacher_model = self.accelerator.prepare_model(self.teacher_model, evaluation_mode=True) + + if teacher_model_kind == "ema": + self.add_callback(SyncTeacherModelCallback(teacher_model=self.teacher_model, accelerator=self.accelerator)) + + def _use_peft_ema_teacher_adapter(self) -> bool: + return self.args.teacher_model_kind == "ema" and is_pure_lora_training(self.model, self.accelerator) + + def get_train_dataloader(self): + if self.train_dataset is None: + raise ValueError("Trainer: training requires a train_dataset.") + + train_dataset = self.train_dataset + data_collator = self.data_collator + if is_datasets_available() and isinstance(train_dataset, datasets.Dataset): + train_dataset = self._remove_unused_columns(train_dataset, description="training") + else: + data_collator = self._get_collator_with_removed_columns(data_collator, description="training") + + dataloader_params = { + "batch_size": self._train_batch_size * self.args.steps_per_generation, + "collate_fn": data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "persistent_workers": self.args.dataloader_persistent_workers, + } + if not isinstance(train_dataset, torch.utils.data.IterableDataset): + dataloader_params["sampler"] = self._get_train_sampler() + dataloader_params["drop_last"] = self.args.dataloader_drop_last + dataloader_params["worker_init_fn"] = partial( + seed_worker, num_workers=self.args.dataloader_num_workers, rank=self.args.process_index + ) + dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor + return self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params)) + + def _get_train_sampler(self, dataset=None) -> Sampler: + if dataset is None: + dataset = self.train_dataset + return RepeatSampler( + data_source=dataset, + mini_repeat_count=self.num_generations, + batch_size=self.args.generation_batch_size // self.num_generations, + repeat_count=self.num_iterations * self.args.steps_per_generation, + shuffle=self.shuffle_dataset, + seed=self.args.seed, + ) + + def _get_eval_sampler(self, eval_dataset) -> Sampler: + return RepeatSampler( + data_source=eval_dataset, + mini_repeat_count=self.num_generations_eval, + seed=self.args.seed, + ) + + def training_step(self, model, inputs, num_items_in_batch): + # Gather spans forward+backward: the fused JSD computes the lm_head grad in backward. + with self._get_liger_zero3_lm_head_gather_ctx(model): + output = super().training_step(model, inputs, num_items_in_batch) + self._step += 1 + return output + + def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys=None): + if not isinstance(inputs, dict): + inputs = self._prepare_inputs(inputs) + with torch.no_grad(): + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + return loss.detach(), None, None + + def _prepare_inputs(self, generation_batch): + """Return the per-step training batch, regenerating rollouts and buffering them for reuse in train mode. + + In train mode, rollouts are generated once every `steps_per_generation * num_iterations` steps and split into + per-step slices reused until the next regeneration. In eval mode, every batch is freshly prepared. + """ + mode = "train" if self.model.training else "eval" + if mode == "train": + generate_every = self.args.steps_per_generation * self.num_iterations + if self._step % generate_every == 0 or self._buffered_inputs is None: + buffered_batch = self._prepare_training_batch(generation_batch) + self._buffered_inputs = split_tensor_dict(buffered_batch, self.args.steps_per_generation) + self._dispatch_self_distillation_callback( + "on_generation_batch_built", + generate_every=generate_every, + steps_per_generation=self.args.steps_per_generation, + ) + return self._buffered_inputs[self._step % self.args.steps_per_generation] + return self._prepare_training_batch(generation_batch) + + def _prepare_training_batch(self, inputs: list[dict[str, Any]]) -> TrainingBatch: + """Sample student rollouts, calculate advantage and construct teacher prompts""" + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + + # Generate student rollouts and decode completions for reward functions + batch = self.sample_rollouts(inputs) + prompts = [example["prompt"] for example in inputs] + privileged_contexts = [example.get("privileged_context") for example in inputs] + completion_ids_list = self._get_completion_ids_list(batch) + if is_conversational({"prompt": prompts[0]}): + completions_text = self.processing_class.batch_decode(batch["completion_ids"], skip_special_tokens=True) + completions = [[{"role": "assistant", "content": content}] for content in completions_text] + else: + completions = self.processing_class.batch_decode(batch["completion_ids"], skip_special_tokens=True) + + # Compute rewards over the globally gathered rollout batch + rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list) + if rewards_per_func.numel() == 0: + rewards = torch.zeros(self.accelerator.num_processes * len(prompts), device=device) + else: + rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1) + + # Normalize rewards within generation groups to produce local policy advantages + num_generations = self.num_generations if mode == "train" else self.num_generations_eval + mean_grouped_rewards = rewards.view(-1, num_generations).mean(dim=1).repeat_interleave(num_generations, dim=0) + if self.scale_rewards == "batch": + std_rewards = rewards.std().expand_as(rewards) if rewards.numel() > 1 else torch.zeros_like(rewards) + group_std_rewards = rewards.view(-1, num_generations).std(dim=1) + elif self.scale_rewards == "none": + std_rewards = torch.ones_like(rewards) + group_std_rewards = torch.ones(rewards.numel() // num_generations, device=device, dtype=rewards.dtype) + else: + group_std_rewards = rewards.view(-1, num_generations).std(dim=1) + std_rewards = group_std_rewards.repeat_interleave(num_generations, dim=0) + advantages = (rewards - mean_grouped_rewards) / (std_rewards + 1e-4) + local_batch_size = batch["completion_ids"].size(0) + process_start = self.accelerator.process_index * local_batch_size + process_slice = slice(process_start, process_start + local_batch_size) + local_rewards = rewards[process_slice] + local_advantages = advantages[process_slice] + + self._record_reward_diagnostics(mode, rewards, rewards_per_func, group_std_rewards) + self._record_completion_metrics(mode, batch) + + batch["rewards"] = local_rewards + batch["advantages"] = local_advantages + teacher_context = self.teacher_context_builder.build( + batch, + prompts, + batch["rewards"], + feedbacks=privileged_contexts, + ) + + for key, value in self.teacher_context_builder.last_metrics.items(): + self._metrics[mode][key].append(value) + self._warn_on_inactive_self_distillation(mode) + + self._dispatch_self_distillation_callback( + "on_teacher_context_built", + teacher_input_ids=teacher_context["teacher_input_ids"], + teacher_attention_mask=teacher_context["teacher_attention_mask"], + completion_mask=batch["completion_mask"], + self_distillation_mask=teacher_context["self_distillation_mask"], + ) + + batch.update( + { + "teacher_input_ids": teacher_context["teacher_input_ids"], + "teacher_attention_mask": teacher_context["teacher_attention_mask"], + "self_distillation_mask": teacher_context["self_distillation_mask"], + } + ) + + self._dispatch_self_distillation_callback( + "on_self_distillation_batch_prepared", + old_per_token_logps=batch.get("old_per_token_logps"), + prompt_ids=batch["prompt_ids"], + completion_ids=batch["completion_ids"], + teacher_input_ids=batch["teacher_input_ids"], + teacher_attention_mask=batch["teacher_attention_mask"], + self_distillation_mask=batch.get("self_distillation_mask"), + ) + return batch + + def sample_rollouts(self, inputs: list[dict[str, Any]]) -> TrainingBatch: + """Generate completions for a batch of prompts and assemble the training batch.""" + prompts = [example["prompt"] for example in inputs] + prompt_ids = self._tokenize_prompts(prompts) + self._dispatch_self_distillation_callback( + "on_generation_prompts_selected", + generation_prompts=prompts, + generation_prompt_text=None, + ) + + prompt_ids_list, completion_ids_list = self._generate(prompt_ids) + device = self.accelerator.device + prompt_ids = [torch.tensor(ids) for ids in prompt_ids_list] + prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids] + prompt_ids = pad(prompt_ids, padding_value=self._tokenizer.pad_token_id, padding_side="left").to(device=device) + prompt_mask = pad(prompt_mask, padding_value=0, padding_side="left").to(device=device) + + completion_ids = [torch.tensor(ids) for ids in completion_ids_list] + completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids] + completion_ids = pad(completion_ids, padding_value=self._tokenizer.pad_token_id, padding_side="right").to( + device=device + ) + completion_mask = pad(completion_mask, padding_value=0, padding_side="right").to(device=device) + + if self.mask_truncated_completions: + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device) + completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int() + + old_per_token_logps = self._compute_rollout_logps( + prompt_ids=prompt_ids, + prompt_mask=prompt_mask, + completion_ids=completion_ids, + completion_mask=completion_mask, + ) + batch: TrainingBatch = { + "prompt_ids": prompt_ids, + "prompt_mask": prompt_mask, + "completion_ids": completion_ids, + "completion_mask": completion_mask, + "raw_completion_lengths": torch.tensor( + [len(ids) for ids in completion_ids_list], device=device, dtype=torch.long + ), + } + if old_per_token_logps is not None: + batch["old_per_token_logps"] = old_per_token_logps + return batch + + def _get_completion_ids_list(self, batch: TrainingBatch) -> list[list[int]]: + raw_completion_lengths = batch["raw_completion_lengths"].detach().cpu().tolist() + return [ + ids[:length].tolist() + for ids, length in zip(batch["completion_ids"].detach().cpu(), raw_completion_lengths, strict=True) + ] + + def _tokenize_prompts_untruncated(self, prompts: list[Any]) -> list[list[int]]: + if is_conversational({"prompt": prompts[0]}): + tokenized = self.processing_class.apply_chat_template( + conversation=prompts, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + **self.chat_template_kwargs, + ) + prompt_ids = tokenized["input_ids"] + else: + prompt_ids = self.processing_class(text=prompts)["input_ids"] + return prompt_ids + + def _tokenize_prompts(self, prompts: list[Any]) -> list[list[int]]: + prompt_ids = self._tokenize_prompts_untruncated(prompts) + if self.max_prompt_length is not None: + prompt_ids = [ids[-self.max_prompt_length :] for ids in prompt_ids] + return prompt_ids + + def _generate(self, prompt_ids: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]: + if self.use_vllm: + return self._generate_vllm(prompt_ids) + return self._generate_transformers(prompt_ids) + + def _generate_vllm(self, prompt_ids: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]: + if self.state.global_step != self._last_loaded_step: + self.vllm_generation.sync_weights() + self._last_loaded_step = self.state.global_step + + mode = "train" if self.model.training else "eval" + num_generations = self.num_generations if mode == "train" else self.num_generations_eval + prompt_ids_out, completion_ids_list, _, _ = self.vllm_generation.generate( + prompts=prompt_ids, + images=None, + num_generations=num_generations, + ) + return prompt_ids_out, completion_ids_list + + def _generate_transformers(self, prompt_ids: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]: + device = self.accelerator.device + prompt_tensors = [torch.tensor(ids) for ids in prompt_ids] + padded_ids = pad(prompt_tensors, padding_value=self._tokenizer.pad_token_id, padding_side="left").to( + device=device + ) + attention_mask = pad([torch.ones_like(t) for t in prompt_tensors], padding_value=0, padding_side="left").to( + device=device + ) + generate_inputs: dict[str, torch.Tensor | Any] = {"input_ids": padded_ids, "attention_mask": attention_mask} + + with ( + unwrap_model_for_generation( + self.model_wrapped, + self.accelerator, + gather_deepspeed3_params=self.args.ds3_gather_for_generation, + generation_kwargs=self.generation_kwargs, + ) as unwrapped_model, + torch.no_grad(), + FSDP.summon_full_params(self.model_wrapped, recurse=False) if self.is_fsdp_enabled else nullcontext(), + ): + prompt_completion_ids = unwrapped_model.generate( + **generate_inputs, generation_config=self.generation_config + ) + + prompt_length = generate_inputs["input_ids"].size(1) + completion_ids = prompt_completion_ids[:, prompt_length:] + is_eos = completion_ids == self._tokenizer.eos_token_id + eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device) + eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)] + seq_idx = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1) + completion_mask = (seq_idx <= eos_idx.unsqueeze(1)).int() + completion_ids_list = [ + c[m].tolist() for c, m in zip(completion_ids.cpu(), completion_mask.bool().cpu(), strict=True) + ] + return prompt_ids, completion_ids_list + + def _compute_rollout_logps( + self, + prompt_ids: torch.Tensor, + prompt_mask: torch.Tensor, + completion_ids: torch.Tensor, + completion_mask: torch.Tensor, + ) -> torch.Tensor | None: + generate_every = self.args.steps_per_generation * self.num_iterations + old_per_token_logps = None + + if self.args.gradient_accumulation_steps % generate_every != 0: + prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) + with torch.no_grad(): + logits = self._forward_logits( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + ) + old_per_token_logps = selective_log_softmax(logits, completion_ids) + + return old_per_token_logps + + def _calculate_rewards(self, inputs, prompts, completions, completion_ids_list): + device = self.accelerator.device + if len(self.reward_funcs) == 0: + return torch.zeros((len(prompts), 0), device=device) + + rewards_per_func = torch.zeros(len(prompts), len(self.reward_funcs), device=device) + keys = [key for key in inputs[0] if key not in ["prompt", "completion", "completion_ids"]] + reward_kwargs = {key: [example[key] for example in inputs] for key in keys} + reward_kwargs["trainer_state"] = self.state + + for i, (reward_func, reward_processing_class) in enumerate( + zip(self.reward_funcs, self.reward_processing_classes, strict=True) + ): + if isinstance(reward_func, nn.Module): + if is_conversational(inputs[0]): + messages = [{"messages": p + c} for p, c in zip(prompts, completions, strict=True)] + texts = [ + apply_chat_template(x, reward_processing_class, **self.chat_template_kwargs)["text"] + for x in messages + ] + else: + texts = [p + c for p, c in zip(prompts, completions, strict=True)] + reward_inputs = reward_processing_class( + text=texts, + return_tensors="pt", + padding=True, + padding_side="right", + add_special_tokens=False, + ) + reward_inputs = _BaseTrainer._prepare_inputs(self, reward_inputs) + with torch.inference_mode(): + rewards_per_func[:, i] = reward_func(**reward_inputs).logits[:, 0] + else: + output_reward_func = reward_func( + prompts=prompts, + completions=completions, + completion_ids=completion_ids_list, + **reward_kwargs, + ) + output_reward_func = [reward if reward is not None else torch.nan for reward in output_reward_func] + rewards_per_func[:, i] = torch.tensor(output_reward_func, dtype=torch.float32, device=device) + + return self.accelerator.gather(rewards_per_func) + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + if return_outputs: + raise ValueError("The SDPOTrainer does not support returning outputs") + + if self.args.distillation_weight == 1.0: + if self.use_teacher_server: + loss = self._compute_server_distillation_loss(model, inputs) + elif self.use_liger_loss: + accumulation_scale = self.current_gradient_accumulation_steps if self.model.training else 1.0 + return self._compute_liger_loss(model, inputs) / accumulation_scale + else: + distillation_logits = self._compute_teacher_student_logits(model, self.teacher_model, inputs) + loss = self._compute_self_distillation_loss(model, inputs, distillation_logits) + elif self.args.distillation_weight == 0.0: + student_input_ids = torch.cat([inputs["prompt_ids"], inputs["completion_ids"]], dim=1) + student_attention_mask = torch.cat([inputs["prompt_mask"], inputs["completion_mask"]], dim=1) + student_logits = self._forward_logits( + model=model, + input_ids=student_input_ids, + attention_mask=student_attention_mask, + logits_to_keep=inputs["completion_ids"].size(1), + ) + loss = self._compute_policy_loss(inputs, student_logits) + else: + distillation_logits = self._compute_teacher_student_logits(model, self.teacher_model, inputs) + policy_loss = self._compute_policy_loss(inputs, distillation_logits.student_logits) + distillation_loss = self._compute_self_distillation_loss(model, inputs, distillation_logits) + loss = ( + 1 - self.args.distillation_weight + ) * policy_loss + self.args.distillation_weight * distillation_loss + + accumulation_scale = self.current_gradient_accumulation_steps if self.model.training else 1.0 + return loss / accumulation_scale + + def _compute_policy_loss( + self, + inputs, + student_logits, + ) -> torch.Tensor: + completion_ids = inputs["completion_ids"] + completion_mask = inputs["completion_mask"] + per_token_logps = selective_log_softmax(student_logits, completion_ids) + old_per_token_logps = inputs.get("old_per_token_logps") + old_per_token_logps = per_token_logps.detach() if old_per_token_logps is None else old_per_token_logps + advantages = inputs["advantages"] + if advantages.dim() == 1: + advantages = advantages.unsqueeze(1) + log_ratio = per_token_logps - old_per_token_logps + if self.importance_sampling_level == "sequence": + log_ratio = (log_ratio * completion_mask).sum(-1, keepdim=True) / completion_mask.sum( + -1, keepdim=True + ).clamp(min=1.0) + coef_1 = torch.exp(log_ratio) + coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high) + per_token_loss = -torch.min(coef_1 * advantages, coef_2 * advantages) + + if self.loss_type == "grpo": + loss = (per_token_loss * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0) + loss = loss.mean() + elif self.loss_type == "bnpo": + loss = (per_token_loss * completion_mask).sum() / completion_mask.sum().clamp(min=1.0) + elif self.loss_type == "dr_grpo": + loss = (per_token_loss * completion_mask).sum() / (per_token_loss.size(0) * self.max_completion_length) + elif self.loss_type == "dapo": + loss = (per_token_loss * completion_mask).sum() / completion_mask.sum().clamp(min=1.0) + else: + raise ValueError(f"Unsupported loss_type: {self.loss_type}") + + mode = "train" if self.model.training else "eval" + self._metrics[mode]["self_distillation/policy_loss"].append( + self.accelerator.gather(loss.detach()).mean().item() + ) + + return loss + + def _compute_self_distillation_loss( + self, + model, + inputs: TrainingBatch, + distillation_logits: DistillationLogits, + ) -> torch.Tensor: + """Compute the per-token distillation loss and aggregate by normalizing over sequence length. + + Dispatches between three objectives based on `distillation_mode`: + + - `"topk_logits"`: top-k approximation of the divergence, optionally with a tail bucket for the remaining + probability mass (`distillation_add_tail`). + - `"full_logits"`: full-vocab divergence. + - `"sampled_token"`: token-level (reverse-KL) distillation on sampled `completion_ids`. + + When `distillation_is_clip` is set and `old_per_token_logps` are available, the loss is corrected by a clipped + importance-sampling ratio between the current student and the student at rollout time. + """ + if distillation_logits.loss_mask.sum() == 0: + mode = "train" if model.training else "eval" + self._log_self_distillation_metric(mode, 0.0) + # Keep the zero loss attached to the student graph so backward produces zero gradients instead of stopping. + return distillation_logits.student_logits.sum() * 0.0 + + if self.args.distillation_mode == "topk_logits": + if self.args.distillation_topk is None: + raise ValueError("`distillation_mode='topk_logits'` requires `distillation_topk` to be set.") + per_token_loss = compute_topk_self_distillation_loss( + distillation_logits.student_logits, + distillation_logits.teacher_logits, + distillation_topk=self.args.distillation_topk, + distillation_alpha=self.args.distillation_alpha, + distillation_add_tail=self.args.distillation_add_tail, + ) + elif self.args.distillation_mode == "full_logits": + per_token_loss = compute_full_logit_self_distillation_loss( + distillation_logits.student_logits, + distillation_logits.teacher_logits, + distillation_alpha=self.args.distillation_alpha, + ) + elif self.args.distillation_mode == "sampled_token": + per_token_loss = compute_sampled_token_self_distillation_loss( + distillation_logits.student_logits, + distillation_logits.teacher_logits, + distillation_logits.completion_ids, + distillation_alpha=self.args.distillation_alpha, + ) + else: + raise ValueError( + "distillation_mode must be one of: 'sampled_token', 'full_logits', 'topk_logits', " + f"got {self.args.distillation_mode!r}" + ) + + old_per_token_logps = inputs.get("old_per_token_logps") + if self.args.distillation_is_clip is not None and old_per_token_logps is not None: + student_per_token_logps = selective_log_softmax( + distillation_logits.student_logits, + distillation_logits.completion_ids, + ) + per_token_loss = apply_importance_sampling_clipping( + per_token_loss, + student_per_token_logps, + old_per_token_logps, + self.args.distillation_is_clip, + ) + + loss = (per_token_loss * distillation_logits.loss_mask).sum(-1) / distillation_logits.loss_mask.sum(-1).clamp( + min=1.0 + ) + loss = loss.mean() + + mode = "train" if model.training else "eval" + mean_distill_loss = ( + per_token_loss * distillation_logits.loss_mask + ).sum() / distillation_logits.loss_mask.sum().clamp(min=1.0) + self._log_self_distillation_metric( + mode, + self.accelerator.gather(mean_distill_loss).mean().item(), + ) + return loss + + def _compute_server_distillation_loss(self, model, inputs: TrainingBatch) -> torch.Tensor: + """Distillation loss with teacher logprobs served by the vLLM generation server (`teacher_model_kind='live'`). + + The student is forwarded locally (grad) for its logits; the teacher logprobs are fetched from the server (no + local teacher forward). `sampled_token` distills the realized token (reverse KL); `topk_logits` distills over + the teacher's own top-k support (the server cannot score the student's top-k indices). + """ + # Buffered batches are reused across optimizer steps (`num_iterations > 1`), so the server weights can lag the + # live student; re-sync before scoring. + if self.state.global_step != self._last_loaded_step: + self.vllm_generation.sync_weights() + # Only the main process pushes weights to the server, so hold every rank here until the push completes; + # otherwise non-main ranks could score against half-updated weights. + self.accelerator.wait_for_everyone() + self._last_loaded_step = self.state.global_step + + completion_ids = inputs["completion_ids"] + completion_mask = inputs["completion_mask"] + logits_to_keep = completion_ids.size(1) + + self_distillation_mask = inputs.get("self_distillation_mask") + if self_distillation_mask is None: + loss_mask = completion_mask + else: + loss_mask = completion_mask * self_distillation_mask.unsqueeze(1) + + student_input_ids = torch.cat([inputs["prompt_ids"], completion_ids], dim=1) + student_attention_mask = torch.cat([inputs["prompt_mask"], completion_mask], dim=1) + student_logits = self._forward_logits( + model=model, + input_ids=student_input_ids, + attention_mask=student_attention_mask, + logits_to_keep=logits_to_keep, + ) + + mode = "train" if model.training else "eval" + teacher = self._get_teacher_token_logprobs_from_server(inputs, logits_to_keep) + # Padding positions come back as `-inf`; the masked-out positions are neutralized to finite values below so the + # divergence does not leak `+inf` through them (mirrors the distillation trainer). + required = loss_mask.bool() + student_per_token_logps = selective_log_softmax(student_logits, completion_ids) + + teacher_per_token_logps = teacher["actual_logprobs"] + if (required & ~torch.isfinite(teacher_per_token_logps)).any(): + raise ValueError("Teacher server returned no logprob for a required completion token.") + teacher_per_token_logps = torch.where( + required, teacher_per_token_logps, torch.zeros_like(teacher_per_token_logps) + ) + + # Diagnostic for disagreement between local student scores and server teacher scores on realized tokens. + # Sudden jumps can indicate stale server weights or numerical drift. + abs_diff = ((student_per_token_logps.detach() - teacher_per_token_logps).abs() * loss_mask).sum() / ( + loss_mask.sum().clamp(min=1.0) + ) + self._metrics[mode]["self_distillation/server_logprob_abs_diff"].append( + self.accelerator.gather(abs_diff).mean().item() + ) + + if self.args.distillation_mode == "sampled_token": + # Reverse-KL token-level objective, matching `compute_sampled_token_self_distillation_loss`. + per_token_loss = (student_per_token_logps - teacher_per_token_logps).detach() * student_per_token_logps + else: + teacher_topk_logps = teacher["topk_logprobs"] + teacher_topk_ids = teacher["topk_token_ids"] + # Project the student onto the teacher's top-k support, then renormalize (or add a tail bucket) before the + # divergence, matching `compute_topk_self_distillation_loss` on the teacher's support. + keep = required.unsqueeze(-1) + student_topk_logps = torch.gather( + torch.log_softmax(student_logits, dim=-1), dim=-1, index=teacher_topk_ids + ) + student_topk_logps = torch.where(keep, student_topk_logps, torch.zeros_like(student_topk_logps)) + teacher_topk_logps = torch.where(keep, teacher_topk_logps, torch.zeros_like(teacher_topk_logps)) + if self.args.distillation_add_tail: + student_topk_logps = add_tail_bucket(student_topk_logps) + teacher_topk_logps = add_tail_bucket(teacher_topk_logps) + else: + student_topk_logps = student_topk_logps - torch.logsumexp(student_topk_logps, dim=-1, keepdim=True) + teacher_topk_logps = teacher_topk_logps - torch.logsumexp(teacher_topk_logps, dim=-1, keepdim=True) + per_token_loss = compute_divergence(student_topk_logps, teacher_topk_logps, self.args.distillation_alpha) + + old_per_token_logps = inputs.get("old_per_token_logps") + if self.args.distillation_is_clip is not None and old_per_token_logps is not None: + per_token_loss = apply_importance_sampling_clipping( + per_token_loss, student_per_token_logps, old_per_token_logps, self.args.distillation_is_clip + ) + + loss = (per_token_loss * loss_mask).sum(-1) / loss_mask.sum(-1).clamp(min=1.0) + loss = loss.mean() + mean_distill_loss = (per_token_loss * loss_mask).sum() / loss_mask.sum().clamp(min=1.0) + self._log_self_distillation_metric(mode, self.accelerator.gather(mean_distill_loss).mean().item()) + return loss + + def _get_teacher_token_logprobs_from_server( + self, inputs: TrainingBatch, logits_to_keep: int + ) -> dict[str, torch.Tensor]: + """Per-token teacher logprobs from the vLLM server. + + Returns a dict with `actual_logprobs` (`(B, T)`, the realized-token logprob for reverse KL) and `topk_logprobs` + / `topk_token_ids` (`(B, T, K)`, the teacher's top-k support for top-k logit distillation). Completions are + right-padded, so server values fill the leading positions of each row and the trailing padding keeps the `-inf` + / `0` sentinels (neutralized by the caller). + """ + import numpy as np + + teacher_input_ids = inputs["teacher_input_ids"] + teacher_attention_mask = inputs["teacher_attention_mask"] + device = teacher_input_ids.device + batch_size = teacher_input_ids.size(0) + prompt_attention_mask = teacher_attention_mask[:, : teacher_attention_mask.size(1) - logits_to_keep] + if self.args.distillation_mode == "topk_logits" and self.args.distillation_topk is None: + raise ValueError("`distillation_mode='topk_logits'` requires `distillation_topk` to be set.") + top_logprobs = self.args.distillation_topk if self.args.distillation_mode == "topk_logits" else 1 + + sequences, prompt_lengths, _ = build_teacher_request_inputs( + teacher_input_ids, teacher_attention_mask, prompt_attention_mask + ) + result = self.teacher_client.get_sequence_logprobs( + sequences=sequences, + prompt_lengths=prompt_lengths, + top_logprobs=top_logprobs, + temperature=self.temperature, + ) + + actual = np.full((batch_size, logits_to_keep), float("-inf"), dtype=np.float32) + topk = np.full((batch_size, logits_to_keep, top_logprobs), float("-inf"), dtype=np.float32) + topk_ids = np.zeros((batch_size, logits_to_keep, top_logprobs), dtype=np.int64) + for i in range(batch_size): + seq_actual = result["actual_logprobs"][i] + n = min(len(seq_actual), logits_to_keep) + if n: + actual[i, :n] = np.array(seq_actual, dtype=np.float32)[:n, 0] + topk[i, :n] = np.array(result["logprobs"][i], dtype=np.float32)[:n] + topk_ids[i, :n] = np.array(result["logprob_token_ids"][i], dtype=np.int64)[:n] + return { + "actual_logprobs": torch.from_numpy(actual).to(device), + "topk_logprobs": torch.from_numpy(topk).to(device), + "topk_token_ids": torch.from_numpy(topk_ids).to(device), + } + + def _compute_teacher_student_logits( + self, + model, + teacher_model, + inputs: TrainingBatch, + ) -> DistillationLogits: + """Compute the per-token logits of the student and teacher over the completion tokens. + + The student is forwarded on its own input (original prompt plus the sampled completion) while the teacher is + forwarded on its input (prompt, privileged context, and the same completion). Both sets of logits are aligned + to the completion tokens so they can be compared position-by-position in the distillation loss. + + The teacher forward runs under `torch.no_grad()` and the context resolved by + `_get_teacher_context_for_self_distillation`, which routes it to the correct weights. + """ + prompt_ids = inputs["prompt_ids"] + prompt_mask = inputs["prompt_mask"] + completion_ids = inputs["completion_ids"] + completion_mask = inputs["completion_mask"] + logits_to_keep = completion_ids.size(1) + + self_distillation_mask = inputs.get("self_distillation_mask") + if self_distillation_mask is None: + loss_mask = completion_mask + else: + loss_mask = completion_mask * self_distillation_mask.unsqueeze(1) + student_input_ids = torch.cat([prompt_ids, completion_ids], dim=1) + student_attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + student_logits = self._forward_logits( + model=model, + input_ids=student_input_ids, + attention_mask=student_attention_mask, + logits_to_keep=logits_to_keep, + ) + + with torch.no_grad(), self._get_teacher_context_for_self_distillation(): + teacher_logits = self._forward_logits( + model=teacher_model, + input_ids=inputs["teacher_input_ids"], + attention_mask=inputs["teacher_attention_mask"], + logits_to_keep=logits_to_keep, + ) + + return DistillationLogits( + completion_ids=completion_ids, + completion_mask=completion_mask, + loss_mask=loss_mask, + student_logits=student_logits, + teacher_logits=teacher_logits, + ) + + def _forward_logits( + self, + model, + input_ids: torch.Tensor, + attention_mask: torch.Tensor, + logits_to_keep: int, + ) -> torch.Tensor: + """Forward the model and return temperature-scaled logits aligned to the completion tokens.""" + model_inputs = { + "input_ids": input_ids, + "attention_mask": attention_mask, + "use_cache": False, + } + if "logits_to_keep" in self.model_kwarg_keys: + model_inputs["logits_to_keep"] = logits_to_keep + 1 + + logits = model(**model_inputs).logits + logits = logits[:, :-1, :] + logits = logits[:, -logits_to_keep:, :] + return logits / self.temperature + + def _compute_liger_loss(self, model, inputs: TrainingBatch) -> torch.Tensor: + """`full_logits` distillation via the Liger fused JSD kernel: forwards the base models for hidden states and + fuses the lm_head projection with the divergence, never materializing the full-vocab logits. + + Each model is forwarded through its own wrapper via `_forward_redirection` so FSDP2/DeepSpeed materialize the + sharded params during the unwrapped base forward. The fused kernel needs both lm_head weights live at once, so + the frozen teacher weight is captured while the teacher is materialized and handed to the student pass. + """ + logits_to_keep = inputs["completion_ids"].size(1) + self_distillation_mask = inputs.get("self_distillation_mask") + if self_distillation_mask is None: + loss_mask = inputs["completion_mask"] + else: + loss_mask = inputs["completion_mask"] * self_distillation_mask.unsqueeze(1) + + unwrapped_student = self.accelerator.unwrap_model(model) + unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model) + + with torch.no_grad(), self._get_teacher_context_for_self_distillation(): + teacher_hidden, teacher_weight, teacher_bias = self._forward_redirection( + self.teacher_model, + unwrapped_teacher, + self._liger_teacher_side, + unwrapped_teacher, + inputs, + logits_to_keep, + ) + + return self._forward_redirection( + model, + unwrapped_student, + self._liger_student_loss, + unwrapped_student, + inputs, + logits_to_keep, + loss_mask, + teacher_hidden, + teacher_weight, + teacher_bias, + ) + + def _liger_teacher_side(self, teacher, inputs: TrainingBatch, logits_to_keep: int): + """Teacher hidden states + frozen lm_head weight, captured while the teacher params are materialized.""" + hidden = teacher.get_decoder()( + input_ids=inputs["teacher_input_ids"], + attention_mask=inputs["teacher_attention_mask"], + use_cache=False, + ).last_hidden_state + hidden = hidden[:, :-1][:, -logits_to_keep:] + head = teacher.get_output_embeddings() + # Clone so the weight survives re-sharding once this forward context exits. + weight = head.weight.detach().clone() + bias = head.bias.detach().clone() if head.bias is not None else None + return hidden, weight, bias + + def _liger_student_loss( + self, + student, + inputs: TrainingBatch, + logits_to_keep, + loss_mask, + teacher_hidden, + teacher_weight, + teacher_bias, + ): + student_input_ids = torch.cat([inputs["prompt_ids"], inputs["completion_ids"]], dim=1) + student_attention_mask = torch.cat([inputs["prompt_mask"], inputs["completion_mask"]], dim=1) + student_hidden = student.get_decoder()( + input_ids=student_input_ids, + attention_mask=student_attention_mask, + use_cache=False, + ).last_hidden_state + # Align hidden states to the completion-predicting positions, matching `_forward_logits`. + student_hidden = student_hidden[:, :-1][:, -logits_to_keep:] + + # `ignore_index` masks non-response positions; the token values only feed the disabled hard-CE term. + completion_ids = inputs["completion_ids"] + true_labels = torch.where(loss_mask.bool(), completion_ids, torch.full_like(completion_ids, -100)) + + student_head = student.get_output_embeddings() + # Per-sequence then batch mean (grpo), matching the non-Liger path: the fused kernel reduces by total tokens + # (bnpo), so we call it per sequence and average. + seq_losses = [ + self.liger_jsd_loss( + student_input=student_hidden[i], + student_weight=student_head.weight, + teacher_input=teacher_hidden[i], + teacher_weight=teacher_weight, + true_labels=true_labels[i], + student_bias=student_head.bias, + teacher_bias=teacher_bias, + ) + for i in range(student_hidden.size(0)) + ] + loss = torch.stack(seq_losses).mean() + + mode = "train" if student.training else "eval" + self._log_self_distillation_metric(mode, self.accelerator.gather(loss.detach()).mean().item()) + return loss + + def _get_liger_zero3_lm_head_gather_ctx(self, model): + """Gather the sharded student/teacher lm_head weights for the fused matmul under ZeRO-3. Liger reads + `lm_head.weight` by attribute, so the gather hook never fires; the decoder forward gathers itself. No-op + outside ZeRO-3.""" + if not self.use_liger_loss: + return nullcontext() + + deepspeed_plugin = self.accelerator.state.deepspeed_plugin + if deepspeed_plugin is None or deepspeed_plugin.zero_stage != 3: + return nullcontext() + + import deepspeed + + unwrapped_student = self.accelerator.unwrap_model(model) + unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model) + student_head = unwrapped_student.get_output_embeddings() + teacher_head = unwrapped_teacher.get_output_embeddings() + params = [student_head.weight, teacher_head.weight] + if student_head.bias is not None: + params.append(student_head.bias) + if teacher_head.bias is not None: + params.append(teacher_head.bias) + return deepspeed.zero.GatheredParameters(params, modifier_rank=None) + + def _get_teacher_context_for_self_distillation(self): + """Return the context manager that routes the teacher forward to the correct weights. + + For non-PEFT models this is a no-op. For PEFT models: + + - `teacher_model_kind == "base"`: disable the student adapter so the teacher forward uses the base weights. + - `teacher_model_kind == "ema"` under pure-LoRA training: switch to the `"teacher"` LoRA adapter. + - otherwise: no-op; the teacher is a separate deepcopy. + """ + teacher_model_kind = self.args.teacher_model_kind + if not is_peft_model(self.model): + return nullcontext() + + target_model = self.accelerator.unwrap_model(self.teacher_model) + + if teacher_model_kind == "base": + return use_adapter(target_model, adapter_name=None) + if teacher_model_kind == "ema" and self._use_peft_ema_teacher_adapter(): + return use_adapter(target_model, adapter_name="teacher") + return nullcontext() + + def _record_completion_metrics(self, mode: str, batch: TrainingBatch) -> None: + device = self.accelerator.device + completion_ids_list = self._get_completion_ids_list(batch) + agg_completion_lengths = self.accelerator.gather(batch["raw_completion_lengths"]) + self._metrics[mode]["completions/mean_length"].append(agg_completion_lengths.float().mean().item()) + self._metrics[mode]["completions/min_length"].append(agg_completion_lengths.float().min().item()) + self._metrics[mode]["completions/max_length"].append(agg_completion_lengths.float().max().item()) + + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device) + agg_is_truncated = self.accelerator.gather(is_truncated) + self._metrics[mode]["completions/clipped_ratio"].append(agg_is_truncated.float().mean().item()) + term_completion_lengths = agg_completion_lengths[~agg_is_truncated] + if len(term_completion_lengths) == 0: + term_completion_lengths = torch.zeros(1, device=device) + self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_lengths.float().mean().item()) + self._metrics[mode]["completions/min_terminated_length"].append(term_completion_lengths.float().min().item()) + self._metrics[mode]["completions/max_terminated_length"].append(term_completion_lengths.float().max().item()) + + def _log_self_distillation_metric(self, mode: str, value: float) -> None: + metric_prefix = self._name.lower().replace(" ", "_") + self._metrics[mode]["self_distillation/distillation_loss"].append(value) + self._metrics[mode][f"{metric_prefix}/distillation_loss"].append(value) + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + # Average the metrics + metrics = {} + for key, val in self._metrics[mode].items(): + # Filter out NaN values before averaging. A reward function that returns None for all samples + # in a batch produces NaN for that batch's metric. With logging_steps > 1, a naive sum()/len() + # would let a single NaN contaminate valid data from other batches. Only return None when no + # valid values remain (e.g. JSON loggers crash on float NaN). + valid = [v for v in val if not math.isnan(v)] + metrics[key] = sum(valid) / len(valid) if valid else None + + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + def _record_reward_diagnostics( + self, + mode: str, + rewards: torch.Tensor, + rewards_per_func: torch.Tensor, + group_std_rewards: torch.Tensor, + ) -> None: + tolerance = self.args.diagnostics_flat_tolerance + + reward_mean = rewards.mean() if rewards.numel() > 0 else torch.tensor(0.0, device=self.accelerator.device) + reward_std = rewards.std() if rewards.numel() > 1 else torch.tensor(0.0, device=self.accelerator.device) + reward_min = rewards.min() if rewards.numel() > 0 else torch.tensor(0.0, device=self.accelerator.device) + reward_max = rewards.max() if rewards.numel() > 0 else torch.tensor(0.0, device=self.accelerator.device) + flat_group_fraction = ( + (group_std_rewards <= tolerance).float().mean() + if group_std_rewards.numel() > 0 + else torch.tensor(1.0, device=self.accelerator.device) + ) + + self._metrics[mode]["self_distillation/reward_mean"].append(self.accelerator.gather(reward_mean).mean().item()) + self._metrics[mode]["self_distillation/reward_std"].append(self.accelerator.gather(reward_std).mean().item()) + self._metrics[mode]["self_distillation/reward_min"].append(self.accelerator.gather(reward_min).min().item()) + self._metrics[mode]["self_distillation/reward_max"].append(self.accelerator.gather(reward_max).max().item()) + self._metrics[mode]["self_distillation/group_reward_std_mean"].append( + self.accelerator.gather(group_std_rewards.mean() if group_std_rewards.numel() > 0 else reward_std) + .mean() + .item() + ) + self._metrics[mode]["self_distillation/flat_group_fraction"].append( + self.accelerator.gather(flat_group_fraction).mean().item() + ) + + if rewards_per_func.numel() > 0: + reward_func_means = rewards_per_func.nanmean(dim=0) + gathered_means = self.accelerator.gather(reward_func_means).view(-1, reward_func_means.numel()).mean(dim=0) + for reward_name, reward_func_mean in zip(self.reward_func_names, gathered_means.tolist(), strict=True): + self._metrics[mode][f"self_distillation/rewards/{reward_name}"].append(reward_func_mean) + + reward_is_flat = reward_std.item() <= tolerance + grouped_rewards_are_flat = flat_group_fraction.item() >= 1.0 - tolerance + if reward_is_flat and grouped_rewards_are_flat: + self._warn_on_degenerate_diagnostics( + mode=mode, + counter_key="flat_rewards", + message=( + "Observed flat SDPO rewards across all sampled generations. " + "Policy advantages will collapse to zero, and SDPO will not learn. " + "Check reward density, reward shaping, or `success_reward_threshold`." + ), + ) + else: + self._diagnostic_counters[mode]["flat_rewards"] = 0 + + def _warn_on_inactive_self_distillation(self, mode: str) -> None: + metrics = self.teacher_context_builder.last_metrics + tolerance = self.args.diagnostics_flat_tolerance + + reprompt_fraction = metrics.get("self_distillation/reprompt_sample_fraction", 0.0) + success_fraction = metrics.get("self_distillation/success_group_fraction", 0.0) + + if reprompt_fraction <= tolerance: + self._warn_on_degenerate_diagnostics( + mode=mode, + counter_key="inactive_self_distillation", + message=( + "SDPO self-distillation is inactive because no reprompted samples were constructed. " + "This usually means no rollout exceeded `success_reward_threshold` and no usable privileged " + "feedback was available." + ), + ) + else: + self._diagnostic_counters[mode]["inactive_self_distillation"] = 0 + + if success_fraction <= tolerance: + self._warn_on_degenerate_diagnostics( + mode=mode, + counter_key="no_successful_rollouts", + message=( + "SDPO did not find any successful rollouts in the current generation groups. " + "If this persists, reduce task difficulty, adjust reward shaping, or lower " + "`success_reward_threshold`." + ), + ) + else: + self._diagnostic_counters[mode]["no_successful_rollouts"] = 0 + + def _warn_on_degenerate_diagnostics(self, mode: str, counter_key: str, message: str) -> None: + interval = self.args.diagnostics_warning_interval + if interval == 0: + return + + self._diagnostic_counters[mode][counter_key] += 1 + count = self._diagnostic_counters[mode][counter_key] + if count == 1 or count % interval == 0: + logger.warning("%s Consecutive degenerate steps: %s.", message, count) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdpo/teacher_sync.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdpo/teacher_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..132032646ec65e2e60aa1e015af9082418924d5e --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/sdpo/teacher_sync.py @@ -0,0 +1,184 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging + +import torch +from accelerate.utils import is_peft_model +from transformers import ( + TrainerCallback, + TrainerControl, + TrainerState, + TrainingArguments, +) + +from ...trainer.callbacks import SyncRefModelCallback + + +logger = logging.getLogger(__name__) + + +def is_pure_lora_training(model, accelerator=None) -> bool: + """Return `True` when the active adapter is LoRA and every trainable parameter is a LoRA parameter.""" + if not is_peft_model(model): + return False + + if accelerator is not None: + model = accelerator.unwrap_model(model) + + adapter_name = model.active_adapter + if adapter_name is None: + adapter_name = "default" + adapter_config = model.peft_config.get(adapter_name) + peft_type = adapter_config.peft_type + if peft_type is None or str(peft_type).split(".")[-1] != "LORA": + return False + + for name, param in model.named_parameters(): + if param.requires_grad and "lora_" not in name: + return False + return True + + +class SyncTeacherModelCallback(SyncRefModelCallback): + """Synchronize an EMA teacher model with the student model on each configured sync step.""" + + def __init__(self, teacher_model, accelerator=None): + super().__init__(ref_model=teacher_model, accelerator=accelerator) + + def on_step_end(self, args, state, control, **kwargs): + model = kwargs["model"] + if self.ref_model is not None and state.global_step % args.teacher_sync_steps == 0: + if self.accelerator: + model = self.accelerator.unwrap_model(model) + self.sync_target_model(model, self.ref_model, args.teacher_update_rate) + + +class PEFTAdapterEMACallback(TrainerCallback): + """ + Callback that maintains an EMA copy of PEFT adapter weights for use as a teacher model in self-distillation. + + The callback creates a secondary adapter ("teacher") with zero-initialized weights and maintains shadow weights + that are updated via exponential moving average: `teacher_weight = (1-α) * teacher_weight + α * student_weight` + + Usage: + ```python + >>> trainer.add_callback( + ... PEFTAdapterEMACallback( + ... model=model, + ... teacher_adapter_name="teacher", + ... update_rate=0.05, + ... ) + ... ) + ``` + """ + + def __init__( + self, + model, + teacher_adapter_name: str = "teacher", + update_rate: float = 0.05, + sync_steps: int = 1, + accelerator=None, + ): + self.model = model + self.teacher_adapter_name = teacher_adapter_name + self.update_rate = update_rate + self.sync_steps = sync_steps + self.accelerator = accelerator + self.shadow_weights: dict[str, torch.Tensor] | None = None + self.teacher_adapter_config = None + self._initialized = False + + def _get_student_state_dict(self): + """Get student adapter state dict using PEFT keys (without adapter name).""" + from peft import get_peft_model_state_dict + + if self.accelerator is not None: + model = self.accelerator.unwrap_model(self.model) + else: + model = self.model + return get_peft_model_state_dict(model) + + def _initialize_teacher_adapter(self): + """Create teacher adapter with zero weights initialized from student adapter.""" + from peft import get_peft_model_state_dict, set_peft_model_state_dict + + if self._initialized: + return + + if self.accelerator is not None: + model = self.accelerator.unwrap_model(self.model) + else: + model = self.model + + adapter_name = model.active_adapter + if adapter_name is None: + adapter_name = "default" + + self.teacher_adapter_config = model.peft_config.get(adapter_name) + + student_state = get_peft_model_state_dict(model) + + teacher_state = {k: torch.zeros_like(v) for k, v in student_state.items()} + + model.add_adapter(self.teacher_adapter_name, self.teacher_adapter_config) + + model.set_adapter(self.teacher_adapter_name) + set_peft_model_state_dict(model, teacher_state, adapter_name=self.teacher_adapter_name) + + model.set_adapter(adapter_name) + + self.shadow_weights = {k: v.clone().zero_() for k, v in teacher_state.items()} + + self._initialized = True + logger.info(f"Initialized PEFT adapter EMA teacher with adapter name: {self.teacher_adapter_name}") + + @torch.no_grad() + def on_step_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): + if state.global_step % self.sync_steps != 0: + return + + if not self._initialized: + self._initialize_teacher_adapter() + + if self.shadow_weights is None: + return + + if self.accelerator is None and "accelerator" in kwargs: + self.accelerator = kwargs["accelerator"] + + student_state = self._get_student_state_dict() + + for key, student_param in student_state.items(): + if key in self.shadow_weights: + shadow = self.shadow_weights[key] + shadow.data = (1 - self.update_rate) * shadow.data + self.update_rate * student_param.data + + from peft import set_peft_model_state_dict + + if self.accelerator is not None: + unwrapped_model = self.accelerator.unwrap_model(self.model) + else: + unwrapped_model = self.model + + original_adapter = unwrapped_model.active_adapter + unwrapped_model.set_adapter(self.teacher_adapter_name) + set_peft_model_state_dict(unwrapped_model, self.shadow_weights, adapter_name=self.teacher_adapter_name) + unwrapped_model.set_adapter(original_adapter) + + def on_train_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): + if self.accelerator is None and "accelerator" in kwargs: + self.accelerator = kwargs["accelerator"] + self._initialize_teacher_adapter() diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ssd/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ssd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d62e42ef96cc9cd6e4ff4de23ce39460420e34b7 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ssd/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .ssd_config import SSDConfig +from .ssd_trainer import SSDTrainer + + +__all__ = ["SSDConfig", "SSDTrainer"] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ssd/ssd_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ssd/ssd_config.py new file mode 100644 index 0000000000000000000000000000000000000000..7a52b9c65a2293194cd132347564e374a39c526d --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ssd/ssd_config.py @@ -0,0 +1,263 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any + +from transformers import TrainingArguments + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class SSDConfig(_BaseConfig): + r""" + Configuration class for [`SSDTrainer`]. + + Implements Simple Self-Distillation (SSD) from [*Embarrassingly Simple Self-Distillation Improves Code + Generation*](https://huggingface.co/papers/2604.01193). SSD samples completions from the model at a training-time + temperature and truncation configuration, then fine-tunes on those raw, unverified samples with standard + cross-entropy loss. + + The `temperature`, `top_k`, and `top_p` parameters control the training-time sampling configuration (T_train, + rho_train in the paper). The evaluation-time configuration (T_eval, rho_eval) is set independently at inference + time. + + Parameters: + > Parameters that control generation and rollout reuse + + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments used when the `model` argument is passed as a string. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to + [`~transformers.AutoModelForCausalLM.from_pretrained`] and [`~transformers.AutoProcessor.from_pretrained`]. + max_prompt_length (`int` or `None`, *optional*, defaults to `512`): + Maximum prompt length. Longer prompts are truncated from the left. + max_completion_length (`int` or `None`, *optional*, defaults to `256`): + Maximum generated completion length. + generation_batch_size (`int` or `None`, *optional*): + Global batch size used for generation. Mutually exclusive with `steps_per_generation`. + steps_per_generation (`int` or `None`, *optional*): + Number of optimizer steps that reuse one generated batch. Mutually exclusive with `generation_batch_size`. + + > Parameters that control sampling + + temperature (`float`, *optional*, defaults to `1.0`): + Sampling temperature (T_train in the paper). + top_k (`int`, *optional*, defaults to `0`): + Top-k sampling parameter. `0` disables top-k filtering. + top_p (`float`, *optional*, defaults to `1.0`): + Top-p (nucleus) sampling parameter. + min_p (`float` or `None`, *optional*): + Minimum token probability for sampling. + repetition_penalty (`float`, *optional*, defaults to `1.0`): + Repetition penalty used during generation. + generation_kwargs (`dict[str, Any]` or `None`, *optional*): + Extra generation kwargs passed to `GenerationConfig`. + + > Parameters that control vLLM generation + + use_vllm (`bool`, *optional*, defaults to `False`): + Whether to use vLLM for generation instead of the training model. + vllm_mode (`str`, *optional*, defaults to `"colocate"`): + vLLM mode: `"colocate"` (shared GPU) or `"server"` (separate vLLM server). + vllm_model_impl (`str`, *optional*, defaults to `"vllm"`): + Model implementation for vLLM: `"vllm"`, `"transformers"`, or `"auto"`. + vllm_server_base_url (`str` or `None`, *optional*): + Base URL for the vLLM server. If provided, `vllm_server_host` and `vllm_server_port` are ignored. + vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`): + Host of the vLLM server (server mode only). + vllm_server_port (`int`, *optional*, defaults to `8000`): + Port of the vLLM server (server mode only). + vllm_server_timeout (`float`, *optional*, defaults to `240.0`): + Timeout in seconds to wait for the vLLM server. + vllm_group_port (`int`, *optional*, defaults to `51216`): + Port for the weight update group (server mode only). + vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`): + Tensor parallel size for colocated vLLM. + vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.3`): + GPU memory utilization ratio for colocated vLLM. + vllm_max_model_length (`int` or `None`, *optional*): + Model context length for vLLM. Inferred from model config if not set. + vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`): + Whether to enable sleep mode for colocated vLLM engine. + + > Parameters that control training behavior + + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model during training. + filter_empty (`bool`, *optional*, defaults to `True`): + Whether to filter out empty or single-line stub completions from the generated data. + num_iterations (`int`, *optional*, defaults to `1`): + Number of optimization iterations per generated batch. + shuffle_dataset (`bool`, *optional*, defaults to `True`): + Whether to shuffle the training dataset. + ds3_gather_for_generation (`bool`, *optional*, defaults to `True`): + Whether to gather ZeRO-3 weights for generation. + cache_implementation (`str` or `None`, *optional*): + Cache implementation used by transformers generation. + chat_template_kwargs (`dict[str, Any]` or `None`, *optional*): + Extra kwargs forwarded to chat template application. + """ + + _VALID_DICT_FIELDS = TrainingArguments._VALID_DICT_FIELDS + ["model_init_kwargs"] + + model_init_kwargs: dict[str, Any] | None = field( + default=None, + metadata={"help": "Keyword arguments for model initialization when `model` is passed as a string."}, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. " + "Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoProcessor.from_pretrained`." + }, + ) + max_prompt_length: int | None = field( + default=512, + metadata={"help": "Maximum prompt length. Longer prompts are truncated from the left."}, + ) + max_completion_length: int | None = field( + default=256, + metadata={"help": "Maximum generated completion length."}, + ) + generation_batch_size: int | None = field( + default=None, + metadata={"help": "Global batch size used for generation. Mutually exclusive with `steps_per_generation`."}, + ) + steps_per_generation: int | None = field( + default=None, + metadata={"help": "Number of optimizer steps that reuse one generated batch."}, + ) + temperature: float = field( + default=1.0, + metadata={"help": "Sampling temperature (T_train in the paper)."}, + ) + top_k: int = field( + default=0, + metadata={"help": "Top-k sampling parameter. `0` disables top-k filtering."}, + ) + top_p: float = field( + default=1.0, + metadata={"help": "Top-p (nucleus) sampling parameter."}, + ) + min_p: float | None = field( + default=None, + metadata={"help": "Minimum token probability for sampling."}, + ) + repetition_penalty: float = field( + default=1.0, + metadata={"help": "Repetition penalty used during generation."}, + ) + generation_kwargs: dict[str, Any] | None = field( + default=None, + metadata={"help": "Extra generation kwargs passed to `GenerationConfig`."}, + ) + cache_implementation: str | None = field( + default=None, + metadata={"help": "Cache implementation used by transformers generation."}, + ) + chat_template_kwargs: dict[str, Any] | None = field( + default=None, + metadata={"help": "Extra kwargs forwarded to chat template application."}, + ) + use_vllm: bool = field( + default=False, + metadata={"help": "Whether to use vLLM for generation."}, + ) + vllm_mode: str = field( + default="colocate", + metadata={"help": "vLLM mode: 'colocate' (shared GPU) or 'server' (separate vLLM server)."}, + ) + vllm_model_impl: str = field( + default="vllm", + metadata={"help": "Model implementation for vLLM: 'vllm', 'transformers', or 'auto'."}, + ) + vllm_server_base_url: str | None = field( + default=None, + metadata={ + "help": "Base URL for the vLLM server. If provided, vllm_server_host and vllm_server_port are ignored." + }, + ) + vllm_server_host: str = field( + default="0.0.0.0", + metadata={"help": "Host of the vLLM server (server mode only)."}, + ) + vllm_server_port: int = field( + default=8000, + metadata={"help": "Port of the vLLM server (server mode only)."}, + ) + vllm_server_timeout: float = field( + default=240.0, + metadata={"help": "Timeout in seconds to wait for the vLLM server."}, + ) + vllm_group_port: int = field( + default=51216, + metadata={"help": "Port for the weight update group (server mode only)."}, + ) + vllm_tensor_parallel_size: int = field( + default=1, + metadata={"help": "Tensor parallel size for colocated vLLM."}, + ) + vllm_gpu_memory_utilization: float = field( + default=0.3, + metadata={"help": "GPU memory utilization ratio for colocated vLLM."}, + ) + vllm_max_model_length: int | None = field( + default=None, + metadata={"help": "Model context length for vLLM. Inferred from model config if not set."}, + ) + vllm_enable_sleep_mode: bool = field( + default=False, + metadata={"help": "Whether to enable sleep mode for colocated vLLM engine."}, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the model during training."}, + ) + filter_empty: bool = field( + default=True, + metadata={"help": "Whether to filter out empty or single-line stub completions."}, + ) + num_iterations: int = field( + default=1, + metadata={"help": "Number of optimization iterations per generated batch."}, + ) + shuffle_dataset: bool = field( + default=True, + metadata={"help": "Whether to shuffle the training dataset."}, + ) + ds3_gather_for_generation: bool = field( + default=True, + metadata={"help": "Whether to gather ZeRO-3 weights for generation."}, + ) + + def __post_init__(self): + super().__post_init__() + + num_processes = self.world_size + if self.generation_batch_size is None and self.steps_per_generation is None: + self.steps_per_generation = self.gradient_accumulation_steps + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + elif self.generation_batch_size is not None and self.steps_per_generation is None: + global_batch_size = self.per_device_train_batch_size * num_processes + if self.generation_batch_size % global_batch_size != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by the global batch size ({global_batch_size})." + ) + self.steps_per_generation = self.generation_batch_size // global_batch_size + elif self.generation_batch_size is None and self.steps_per_generation is not None: + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + else: + raise ValueError("'generation_batch_size' and 'steps_per_generation' can not both be configured") diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ssd/ssd_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ssd/ssd_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..3a7f83c3f171719fcdeb56d5f85bf6e5f99e97d5 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/ssd/ssd_trainer.py @@ -0,0 +1,532 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Trainer for Simple Self-Distillation (SSD). + +Implements the method from *Embarrassingly Simple Self-Distillation Improves Code Generation* (Zhang et al., 2026): +sample completions from the frozen model at a training-time temperature and truncation configuration, then fine-tune on +those raw, unverified samples with standard cross-entropy loss. No reward model, verifier, teacher model, or +reinforcement learning is needed. +""" + +from __future__ import annotations + +import inspect +import math +import textwrap +from collections import defaultdict +from functools import partial +from typing import Any + +import datasets +import torch +from accelerate.logging import get_logger +from accelerate.utils import is_peft_model +from datasets import Dataset, IterableDataset +from torch import nn +from torch.utils.data import DataLoader, Sampler +from transformers import ( + AutoProcessor, + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, +) +from transformers.trainer_utils import seed_worker +from transformers.utils import is_datasets_available, is_peft_available + +from ...data_utils import maybe_apply_chat_template +from ...models import unwrap_model_for_generation +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import ( + RepeatSampler, + create_model_from_path, + disable_dropout_in_model, + get_config_model_id, + identity, + pad, + selective_log_softmax, + split_tensor_dict, +) +from ..utils import prepare_peft_model +from .ssd_config import SSDConfig + + +if is_peft_available(): + from peft import PeftConfig + + +logger = get_logger(__name__) + + +class SSDTrainer(_BaseTrainer): + """Trainer for SSD-style on-policy self-distillation with cross-entropy loss. + + SSD generates completions from the model at a specified training-time temperature and truncation configuration, + then fine-tunes on those raw, unverified samples using standard cross-entropy loss. The dataset only requires a + ``prompt`` column. + """ + + _tag_names = ["trl", "ssd"] + _name = "SSD" + config_cls = SSDConfig + # docstyle-ignore + _paper = { + "title": "Embarrassingly Simple Self-Distillation Improves Code Generation", + "id": "2604.01193", + "citation": textwrap.dedent("""\ + @article{zhang2026ssd, + title = {{Embarrassingly Simple Self-Distillation Improves Code Generation}}, + author = {Ruixiang Zhang and Richard He Bai and Huangjie Zheng and Navdeep Jaitly and Ronan Collobert and Yizhe Zhang}, + year = 2026, + eprint = {arXiv:2604.01193} + }"""), + } + + def __init__( + self, + model: str | PreTrainedModel | nn.Module, + args: SSDConfig | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + peft_config: PeftConfig | None = None, + ): + if train_dataset is None: + raise ValueError("`train_dataset` is required") + if isinstance(train_dataset, IterableDataset): + raise NotImplementedError("Iterable datasets are not yet supported in SSDTrainer.") + if isinstance(eval_dataset, IterableDataset) or ( + isinstance(eval_dataset, dict) and any(isinstance(ds, IterableDataset) for ds in eval_dataset.values()) + ): + raise NotImplementedError("Iterable eval datasets are not yet supported in SSDTrainer.") + if args is None: + model_name = model if isinstance(model, str) else get_config_model_id(model.config) + model_name = model_name.split("/")[-1] + args = SSDConfig(f"{model_name}-SSD") + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + model = create_model_from_path(model, **model_init_kwargs) + elif args.model_init_kwargs is not None: + logger.warning( + "You passed `model_init_kwargs` to `SSDConfig`, but `model` is already instantiated. " + "The `model_init_kwargs` will be ignored." + ) + + self.model_kwarg_keys = ( + inspect.signature(model.forward).parameters.keys() + if not hasattr(model, "get_base_model") + else inspect.signature(model.get_base_model().forward).parameters.keys() + ) + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to SSDTrainer. Pass either a base " + "model with `peft_config`, or a pre-wrapped PEFT model." + ) + if peft_config is not None or (is_peft_available() and getattr(model, "peft_config", None) is not None): + model = prepare_peft_model(model, peft_config, args) + + if processing_class is None: + processing_class = AutoProcessor.from_pretrained( + get_config_model_id(model.config), + truncation_side="left", + padding_side="left", + trust_remote_code=args.trust_remote_code, + ) + + if isinstance(processing_class, ProcessorMixin): + self._tokenizer = processing_class.tokenizer + elif isinstance(processing_class, PreTrainedTokenizerBase): + self._tokenizer = processing_class + else: + raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`") + + if self._tokenizer.pad_token is None: + self._tokenizer.pad_token = self._tokenizer.eos_token + + self.max_prompt_length = args.max_prompt_length + self.max_completion_length = args.max_completion_length + # SSD always samples a single completion per prompt (N=1 in the paper). + self.num_generations = 1 + self.num_iterations = args.num_iterations + self.temperature = args.temperature + self.shuffle_dataset = args.shuffle_dataset + self.filter_empty = args.filter_empty + self.use_vllm = args.use_vllm + self.chat_template_kwargs = args.chat_template_kwargs or {} + self._step = 0 + self._buffered_inputs = None + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + + generation_kwargs = { + "max_new_tokens": self.max_completion_length, + "do_sample": True, + "pad_token_id": self._tokenizer.pad_token_id, + "bos_token_id": self._tokenizer.bos_token_id, + "eos_token_id": self._tokenizer.eos_token_id, + "temperature": args.temperature, + "top_p": args.top_p, + "top_k": args.top_k, + "min_p": args.min_p, + "repetition_penalty": args.repetition_penalty, + "cache_implementation": args.cache_implementation, + } + if args.generation_kwargs is not None: + generation_kwargs.update(args.generation_kwargs) + self.generation_config = GenerationConfig(**generation_kwargs, disable_compile=True) + + if hasattr(model, "warnings_issued"): + model.warnings_issued["estimate_tokens"] = True + + super().__init__( + model=model, + args=args, + data_collator=identity, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + callbacks=callbacks, + optimizers=optimizers, + compute_loss_func="non-None value to disable scaling", + ) + + if args.disable_dropout: + disable_dropout_in_model(self.model) + + self.model.add_model_tags(self._tag_names) + + self.model_accepts_loss_kwargs = False + + if self.use_vllm: + from ...generation.vllm_generation import VLLMGeneration + + self.vllm_generation = VLLMGeneration( + model=self.model, + accelerator=self.accelerator, + processing_class=self.processing_class, + mode=args.vllm_mode, + server_base_url=args.vllm_server_base_url, + server_host=args.vllm_server_host, + server_port=args.vllm_server_port, + group_port=args.vllm_group_port, + server_timeout=args.vllm_server_timeout, + tensor_parallel_size=args.vllm_tensor_parallel_size, + gpu_memory_utilization=args.vllm_gpu_memory_utilization, + max_model_length=args.vllm_max_model_length, + max_num_seqs=args.per_device_train_batch_size + * args.vllm_tensor_parallel_size + * args.steps_per_generation, + enable_sleep_mode=args.vllm_enable_sleep_mode, + model_impl=args.vllm_model_impl, + repetition_penalty=args.repetition_penalty, + temperature=self.temperature, + top_p=args.top_p, + top_k=args.top_k, + min_p=args.min_p, + max_completion_length=self.max_completion_length, + logprobs=None, + generation_kwargs=args.generation_kwargs, + ) + self._last_loaded_step = -1 + + def _set_signature_columns_if_needed(self): + if self._signature_columns is None: + self._signature_columns = ["prompt"] + + def _apply_prompt_template(self, prompts): + return [ + maybe_apply_chat_template({"prompt": prompt}, self.processing_class, **self.chat_template_kwargs)["prompt"] + for prompt in prompts + ] + + # ------------------------------------------------------------------ + # DataLoader + # ------------------------------------------------------------------ + + def get_train_dataloader(self): + if self.train_dataset is None: + raise ValueError("Trainer: training requires a train_dataset.") + + train_dataset = self.train_dataset + data_collator = self.data_collator + if is_datasets_available() and isinstance(train_dataset, datasets.Dataset): + train_dataset = self._remove_unused_columns(train_dataset, description="training") + else: + data_collator = self._get_collator_with_removed_columns(data_collator, description="training") + + dataloader_params = { + "batch_size": self._train_batch_size * self.args.steps_per_generation, + "collate_fn": data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "persistent_workers": self.args.dataloader_persistent_workers, + } + if not isinstance(train_dataset, torch.utils.data.IterableDataset): + dataloader_params["sampler"] = self._get_train_sampler() + dataloader_params["drop_last"] = self.args.dataloader_drop_last + dataloader_params["worker_init_fn"] = partial( + seed_worker, num_workers=self.args.dataloader_num_workers, rank=self.args.process_index + ) + dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor + return self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params)) + + def _get_train_sampler(self, dataset=None) -> Sampler: + if dataset is None: + dataset = self.train_dataset + return RepeatSampler( + data_source=dataset, + mini_repeat_count=self.num_generations, + batch_size=self.args.generation_batch_size // self.num_generations, + repeat_count=self.num_iterations * self.args.steps_per_generation, + shuffle=self.shuffle_dataset, + seed=self.args.seed, + ) + + def _get_eval_sampler(self, eval_dataset) -> Sampler: + return RepeatSampler( + data_source=eval_dataset, + mini_repeat_count=self.num_generations, + seed=self.args.seed, + ) + + # ------------------------------------------------------------------ + # Training step management + # ------------------------------------------------------------------ + + def training_step(self, model, inputs, num_items_in_batch): + output = super().training_step(model, inputs, num_items_in_batch) + self._step += 1 + return output + + def _prepare_inputs(self, generation_batch): + mode = "train" if self.model.training else "eval" + if mode == "train": + generate_every = self.args.steps_per_generation * self.num_iterations + if self._step % generate_every == 0 or self._buffered_inputs is None: + generation_batch = self._build_buffered_batch(generation_batch) + self._buffered_inputs = split_tensor_dict(generation_batch, self.args.steps_per_generation) + return self._buffered_inputs[self._step % self.args.steps_per_generation] + return self._build_buffered_batch(generation_batch) + + # ------------------------------------------------------------------ + # Generation + # ------------------------------------------------------------------ + + def _generate_completion_ids(self, prompts: list[Any]) -> tuple[torch.Tensor, torch.Tensor]: + """Generate completions from the model at the configured training-time temperature and truncation.""" + if self.use_vllm: + return self._generate_completion_ids_vllm(prompts) + return self._generate_completion_ids_transformers(prompts) + + def _generate_completion_ids_vllm(self, prompts: list[Any]) -> tuple[torch.Tensor, torch.Tensor]: + """Generate completions using vLLM.""" + if self.state.global_step != self._last_loaded_step: + self.vllm_generation.sync_weights() + self._last_loaded_step = self.state.global_step + + prompts_text = self._apply_prompt_template(prompts) + tokenized = self.processing_class( + text=prompts_text, + return_tensors=None, + padding=False, + max_length=self.max_prompt_length, + truncation=True, + add_special_tokens=False, + ) + prompt_ids = tokenized["input_ids"] + + _, completion_ids_list, _, _ = self.vllm_generation.generate( + prompts=prompt_ids, + images=None, + num_generations=self.num_generations, + ) + + device = self.accelerator.device + completion_ids = [torch.tensor(ids, device=device) for ids in completion_ids_list] + completion_mask = [torch.ones(len(ids), dtype=torch.long, device=device) for ids in completion_ids_list] + return ( + pad(completion_ids, padding_value=self._tokenizer.pad_token_id, padding_side="right"), + pad(completion_mask, padding_value=0, padding_side="right"), + ) + + def _generate_completion_ids_transformers(self, prompts: list[Any]) -> tuple[torch.Tensor, torch.Tensor]: + """Generate completions using the training model with transformers.""" + generate_inputs = self.processing_class( + text=self._apply_prompt_template(prompts), + return_tensors="pt", + padding=True, + padding_side="left", + max_length=self.max_prompt_length, + truncation=True, + add_special_tokens=False, + ) + # Use the base Trainer tensor preparation instead of re-entering the buffered outer training hook. + generate_inputs = _BaseTrainer._prepare_inputs(self, generate_inputs) + + with ( + unwrap_model_for_generation( + self.model_wrapped, + self.accelerator, + gather_deepspeed3_params=self.args.ds3_gather_for_generation, + ) as unwrapped_model, + torch.no_grad(), + ): + prompt_completion_ids = unwrapped_model.generate( + **generate_inputs, generation_config=self.generation_config + ) + + prompt_length = generate_inputs["input_ids"].size(1) + completion_ids = prompt_completion_ids[:, prompt_length:] + is_eos = completion_ids == self._tokenizer.eos_token_id + eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=completion_ids.device) + eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)] + seq_idx = torch.arange(is_eos.size(1), device=completion_ids.device).expand(is_eos.size(0), -1) + completion_mask = (seq_idx <= eos_idx.unsqueeze(1)).long() + + completion_ids_list = [c[m].tolist() for c, m in zip(completion_ids, completion_mask.bool(), strict=True)] + completion_ids = [torch.tensor(ids, device=self.accelerator.device) for ids in completion_ids_list] + completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids] + return ( + pad(completion_ids, padding_value=self._tokenizer.pad_token_id, padding_side="right"), + pad(completion_mask, padding_value=0, padding_side="right"), + ) + + # ------------------------------------------------------------------ + # Batch construction + # ------------------------------------------------------------------ + + def _build_buffered_batch(self, inputs: list[dict[str, Any]]) -> dict[str, torch.Tensor | Any]: + """Generate completions and build the training batch.""" + prompts = [example["prompt"] for example in inputs] + completion_ids, completion_mask = self._generate_completion_ids(prompts) + + # Optionally filter empty or single-line stub completions (the paper applies minimal syntactic filtering) + if self.filter_empty: + completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + keep = torch.ones(len(completions_text), dtype=torch.bool, device=completion_ids.device) + for i, text in enumerate(completions_text): + stripped = text.strip() + if len(stripped) == 0 or stripped.count("\n") == 0 and len(stripped) < 10: + keep[i] = False + completion_mask = completion_mask * keep.unsqueeze(1).long() + + # Tokenize prompts for the training forward pass + prompt_text = self._apply_prompt_template(prompts) + prompt_inputs = self.processing_class( + text=prompt_text, + return_tensors="pt", + padding=True, + padding_side="left", + max_length=self.max_prompt_length, + truncation=True, + add_special_tokens=False, + ) + prompt_inputs = _BaseTrainer._prepare_inputs(self, prompt_inputs) + prompt_ids = prompt_inputs["input_ids"] + prompt_mask = prompt_inputs["attention_mask"] + + # Log completion statistics + mode = "train" if self.model.training else "eval" + completion_lengths = completion_mask.sum(dim=1).float() + agg_lengths = self.accelerator.gather(completion_lengths) + self._metrics[mode]["completions/mean_length"].append(agg_lengths.mean().item()) + self._metrics[mode]["completions/min_length"].append(agg_lengths.min().item()) + self._metrics[mode]["completions/max_length"].append(agg_lengths.max().item()) + active_ratio = (completion_mask.sum(dim=1) > 0).float().mean() + self._metrics[mode]["ssd/active_sample_ratio"].append(self.accelerator.gather(active_ratio).mean().item()) + + return { + "prompt_ids": prompt_ids, + "prompt_mask": prompt_mask, + "completion_ids": completion_ids, + "completion_mask": completion_mask, + } + + # ------------------------------------------------------------------ + # Loss computation + # ------------------------------------------------------------------ + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + if return_outputs: + raise ValueError("The SSDTrainer does not support returning outputs") + + prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"] + completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"] + input_ids = torch.cat([prompt_ids, completion_ids], dim=1) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) + + # Forward pass + model_inputs = {"input_ids": input_ids, "attention_mask": attention_mask, "use_cache": False} + if "logits_to_keep" in self.model_kwarg_keys: + model_inputs["logits_to_keep"] = logits_to_keep + 1 + logits = model(**model_inputs).logits + logits = logits[:, :-1, :] + logits = logits[:, -logits_to_keep:, :] + + # Standard cross-entropy loss: -log p(y_t | x, y None: + mode = "train" if self.model.training else "eval" + metrics = {} + for key, val in self._metrics[mode].items(): + valid = [v for v in val if not math.isnan(v)] + metrics[key] = sum(valid) / len(valid) if valid else None + + # When called in evaluation, the keys in `logs` start with "eval_". We need to add the prefix "eval_" to the + # keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/tpo/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/tpo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e07ec04eb1b9f4d8a0cfeef4b64460f3c991c1fc --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/tpo/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .tpo_config import TPOConfig +from .tpo_trainer import TPOTrainer + + +__all__ = ["TPOConfig", "TPOTrainer"] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/tpo/tpo_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/tpo/tpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..2e05a73b39c683326c4a3a2e6cbb44dfc0ebded7 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/tpo/tpo_config.py @@ -0,0 +1,174 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class TPOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`experimental.tpo.TPOTrainer`]. + + This class includes only the parameters that are specific to TPO training. For a full list of training arguments, + please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may + differ from those in [`~transformers.TrainingArguments`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + > Parameters that control the model + + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model` + argument of the [`experimental.tpo.TPOTrainer`] is provided as a string. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to + [`~transformers.AutoModelForCausalLM.from_pretrained`] and + [`~transformers.AutoProcessor.from_pretrained`]. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. + + > Parameters that control the data preprocessing + + dataset_num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + max_length (`int` or `None`, *optional*, defaults to `1024`): + Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from the left or + right depending on the `truncation_mode`. If `None`, no truncation is applied. + truncation_mode (`str`, *optional*, defaults to `"keep_start"`): + Truncation mode to use when the sequence exceeds `max_length`. Possible values are `"keep_start"` and + `"keep_end"`. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + + > Parameters that control the training + + loss_type (`str`, *optional*, defaults to `"sigmoid"`): + Type of loss to use. Possible values are: + + - `"sigmoid"`: sigmoid loss from the original [TPO](https://huggingface.co/papers/2405.16681) paper. + - `"hinge"`: hinge loss on the normalized likelihood from the + [SLiC](https://huggingface.co/papers/2305.10425) paper. + - `"ipo"`: IPO loss from the [IPO](https://huggingface.co/papers/2310.12036) paper. + - `"tpo-l"`: length-normalized TPO variant from the + [TPO](https://huggingface.co/papers/2405.16681) paper, which adds a target reward margin + `tpo_l_gamma` to the Bradley-Terry objective. + + beta (`float`, *optional*, defaults to `0.01`): + Parameter controlling the temperature of the TPO loss. For the IPO loss (`loss_type="ipo"`), β is the + regularization parameter denoted by τ in the [paper](https://huggingface.co/papers/2310.12036). + label_smoothing (`float`, *optional*, defaults to `0.0`): + Label smoothing factor. + tpo_alpha (`float`, *optional*, defaults to `1.0`): + Weight of the supervised negative log-likelihood term computed on the gold (`reference`) response in TPO + training. Setting `tpo_alpha=0.0` disables the NLL term and skips the corresponding forward pass. + tpo_l_gamma (`float`, *optional*, defaults to `0.5`): + Target reward margin γ for the TPO-L loss, used only when `loss_type="tpo-l"`. + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `5e-7` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=5e-7, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + # Parameters that control the model + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of " + "the `TPOTrainer` is provided as a string." + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. " + "Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoProcessor.from_pretrained`." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the model."}, + ) + + # Parameters that control the data preprocessing + dataset_num_proc: int | None = field( + default=None, + metadata={"help": "Number of processes to use for processing the dataset."}, + ) + max_length: int | None = field( + default=1024, + metadata={ + "help": "Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from " + "the left or right depending on the `truncation_mode`. If `None`, no truncation is applied." + }, + ) + truncation_mode: str = field( + default="keep_start", + metadata={ + "help": "Truncation mode to use when the sequence exceeds `max_length`.", + "choices": ["keep_end", "keep_start"], + }, + ) + pad_to_multiple_of: int | None = field( + default=None, + metadata={"help": "If set, the sequences will be padded to a multiple of this value."}, + ) + + # Parameters that control the training + loss_type: str = field( + default="sigmoid", + metadata={ + "help": "Type of loss to use.", + "choices": ["sigmoid", "hinge", "ipo", "tpo-l"], + }, + ) + beta: float = field( + default=0.01, + metadata={ + "help": "Parameter controlling the temperature of the TPO loss. For the IPO loss (`loss_type='ipo'`), this " + "value is the regularization parameter denoted by τ in the IPO paper." + }, + ) + label_smoothing: float = field( + default=0.0, + metadata={"help": "Label smoothing factor."}, + ) + tpo_alpha: float = field( + default=1.0, + metadata={ + "help": "Weight of the supervised NLL term computed on the gold (`reference`) response in TPO training. " + "Setting `tpo_alpha=0.0` disables the NLL term and skips the corresponding forward pass." + }, + ) + tpo_l_gamma: float = field( + default=0.5, + metadata={"help": "Target reward margin γ for the TPO-L loss, used only when `loss_type='tpo-l'`."}, + ) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/tpo/tpo_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/tpo/tpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..0ea3a6f86f6346376969c263790a1b12e7e8fc80 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/tpo/tpo_trainer.py @@ -0,0 +1,790 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import textwrap +from collections import defaultdict +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import torch +import torch.nn.functional as F +import transformers +from accelerate import PartialState +from accelerate.logging import get_logger +from accelerate.utils import is_peft_model +from datasets import Dataset, IterableDataset +from packaging.version import Version +from transformers import ( + AutoProcessor, + DataCollator, + PreTrainedModel, + PreTrainedTokenizerBase, +) +from transformers.data.data_collator import DataCollatorMixin +from transformers.trainer_callback import TrainerCallback +from transformers.trainer_utils import EvalPrediction +from transformers.utils import is_peft_available + +from ...data_utils import extract_prompt, is_conversational +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import ( + create_model_from_path, + disable_dropout_in_model, + entropy_from_logits, + get_config_model_id, + pad, + selective_log_softmax, +) +from .tpo_config import TPOConfig + + +if is_peft_available(): + from peft import PeftConfig, PeftModel, get_peft_model + + +logger = get_logger(__name__) + + +def _extract_triple_prompt(example: dict) -> dict: + """Extract the shared prompt from `chosen`/`rejected` and also strip it from `reference`. + + Wraps [`~trl.data_utils.extract_prompt`] — which only rewrites `chosen` and `rejected` — and additionally strips + the extracted prompt prefix from the `reference` (gold) completion. This is specific to TPO and assumes that the + `reference` completion shares the same implicit prompt prefix as `chosen` and `rejected`. If it does not, a + `ValueError` is raised asking the caller to provide an explicit `prompt` column. + """ + extracted = extract_prompt(example) + prompt = extracted["prompt"] + reference = example["reference"] + if reference[: len(prompt)] != prompt: + raise ValueError( + "The `reference` completion does not start with the implicit prompt extracted from `chosen`/`rejected`. " + "Either provide an explicit `prompt` column, or make sure the `reference` completion shares the same " + "prompt prefix as the `chosen` and `rejected` completions." + ) + extracted["reference"] = reference[len(prompt) :] + return extracted + + +@dataclass +class DataCollatorForTriplePreference(DataCollatorMixin): + """ + Data collator used for triple-preference data. Inputs are dynamically padded to the maximum length of a batch. + + This collator expects each example in the input list to be a dictionary containing the keys `"prompt_ids"`, + `"chosen_ids"` and `"rejected_ids"`. When `include_reference=True` (the default) each example must additionally + contain `"reference_ids"`. The collator returns a dictionary containing the following keys: + - `"input_ids"`: Tensor of input IDs, padded to the maximum length of the batch. When + `include_reference=True`, the first third of the batch corresponds to the `"chosen_ids"`, the second third to + the `"rejected_ids"` and the last third to the `"reference_ids"`. When `include_reference=False`, the first + half corresponds to the `"chosen_ids"` and the second half to the `"rejected_ids"` (matching the layout of + [`~trl.trainer.dpo_trainer.DataCollatorForPreference`]). + - `"attention_mask"`: Tensor of attention mask, padded to the maximum length of the batch. + - `"completion_mask"`: Tensor indicating the positions of the completion tokens, padded to the maximum length of + the batch. + + Args: + pad_token_id (`int`): + Token ID to use for padding. + max_length (`int`, *optional*): + Maximum length of the sequences after concatenation. Sequences longer than `max_length` are truncated + before padding, which avoids allocating oversized tensors for batches containing very long sequences. + truncation_mode (`str`, *optional*, defaults to `"keep_start"`): + Truncation mode when a concatenated sequence exceeds `max_length`. Possible values are `"keep_end"` and + `"keep_start"`. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + return_tensors (`str`, *optional*, defaults to `"pt"`): + Type of Tensor to return. Only `"pt"` is currently supported. + include_reference (`bool`, *optional*, defaults to `True`): + Whether to include the `"reference_ids"` branch in the collated batch. When `False`, the collator emits + only the chosen/rejected halves and skips the gold-response sequences entirely, which matches the behavior + expected when `tpo_alpha=0.0` (no NLL term). + + Examples: + ```python + >>> from trl.experimental.tpo.tpo_trainer import DataCollatorForTriplePreference + + >>> collator = DataCollatorForTriplePreference(pad_token_id=0) + >>> examples = [ + ... {"prompt_ids": [1, 2, 3], "chosen_ids": [4, 5], "rejected_ids": [6], "reference_ids": [7, 8]}, + ... {"prompt_ids": [9, 10], "chosen_ids": [11], "rejected_ids": [12, 13], "reference_ids": [14]}, + ... ] + >>> collator(examples) + {'input_ids': tensor([[ 1, 2, 3, 4, 5], + [ 9, 10, 11, 0, 0], + [ 1, 2, 3, 6, 0], + [ 9, 10, 12, 13, 0], + [ 1, 2, 3, 7, 8], + [ 9, 10, 14, 0, 0]]), + 'attention_mask': tensor([[1, 1, 1, 1, 1], + [1, 1, 1, 0, 0], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 1], + [1, 1, 1, 0, 0]]), + 'completion_mask': tensor([[0, 0, 0, 1, 1], + [0, 0, 1, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 1, 1, 0], + [0, 0, 0, 1, 1], + [0, 0, 1, 0, 0]])} + ``` + """ + + pad_token_id: int + max_length: int | None = None + truncation_mode: str = "keep_start" + pad_to_multiple_of: int | None = None + return_tensors: str = "pt" + include_reference: bool = True + + def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + prompt_chosen_ids = [example["prompt_ids"] + example["chosen_ids"] for example in examples] + prompt_rejected_ids = [example["prompt_ids"] + example["rejected_ids"] for example in examples] + chosen_mask = [[0] * len(example["prompt_ids"]) + [1] * len(example["chosen_ids"]) for example in examples] + rejected_mask = [[0] * len(example["prompt_ids"]) + [1] * len(example["rejected_ids"]) for example in examples] + if self.include_reference: + prompt_reference_ids = [example["prompt_ids"] + example["reference_ids"] for example in examples] + reference_mask = [ + [0] * len(example["prompt_ids"]) + [1] * len(example["reference_ids"]) for example in examples + ] + + if self.max_length is not None: + if self.truncation_mode == "keep_start": + sl = slice(None, self.max_length) + elif self.truncation_mode == "keep_end": + sl = slice(-self.max_length, None) + else: + raise ValueError( + f"Unsupported truncation mode: {self.truncation_mode}, expected 'keep_start' or 'keep_end'" + ) + prompt_chosen_ids = [ids[sl] for ids in prompt_chosen_ids] + prompt_rejected_ids = [ids[sl] for ids in prompt_rejected_ids] + chosen_mask = [m[sl] for m in chosen_mask] + rejected_mask = [m[sl] for m in rejected_mask] + if self.include_reference: + prompt_reference_ids = [ids[sl] for ids in prompt_reference_ids] + reference_mask = [m[sl] for m in reference_mask] + + chosen_attention_mask = [[1] * len(ids) for ids in prompt_chosen_ids] + rejected_attention_mask = [[1] * len(ids) for ids in prompt_rejected_ids] + input_ids = prompt_chosen_ids + prompt_rejected_ids + attention_mask = chosen_attention_mask + rejected_attention_mask + completion_mask = chosen_mask + rejected_mask + if self.include_reference: + reference_attention_mask = [[1] * len(ids) for ids in prompt_reference_ids] + input_ids = input_ids + prompt_reference_ids + attention_mask = attention_mask + reference_attention_mask + completion_mask = completion_mask + reference_mask + + # Convert to tensor + input_ids = [torch.tensor(ids) for ids in input_ids] + attention_mask = [torch.tensor(m, dtype=torch.long) for m in attention_mask] + completion_mask = [torch.tensor(m, dtype=torch.long) for m in completion_mask] + + # Pad + output = {} + output["input_ids"] = pad( + input_ids, + padding_value=self.pad_token_id, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + output["attention_mask"] = pad( + attention_mask, + padding_value=0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + output["completion_mask"] = pad( + completion_mask, + padding_value=0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + return output + + +class TPOTrainer(_BaseTrainer): + """ + Trainer for Triple Preference Optimization (TPO) method. This algorithm was initially proposed in the paper [Triple + Preference Optimization: Achieving Better Alignment using a Single Step + Optimization](https://huggingface.co/papers/2405.16681). This class is a wrapper around the + [`~transformers.Trainer`] class and inherits all of its attributes and methods. + + Args: + model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]): + Model to be trained. Can be either: + + - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using `.from_pretrained` (where `` is derived from the model + config) with the keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported. + - A [`~peft.PeftModel`] object. Only causal language models are supported. + args ([`experimental.tpo.TPOConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + data_collator ([`~transformers.DataCollator`], *optional*): + Function to use to form a batch from a list of elements of the processed `train_dataset` or `eval_dataset`. + Will default to [`~trl.experimental.tpo.tpo_trainer.DataCollatorForTriplePreference`]. Custom collators + must truncate sequences before padding; the trainer does not apply post-collation truncation. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + Dataset to use for training. TPO requires a *triple-preference* dataset: each sample must contain a + `"chosen"`, a `"rejected"` and a `"reference"` (gold) completion. The format of the samples can be either: + + - [Standard](dataset_formats#standard): Each sample contains plain text. + - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role + and content). + eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`): + Dataset to use for evaluation. It must meet the same requirements as `train_dataset`. + processing_class ([`~transformers.PreTrainedTokenizerBase`], *optional*): + Processing class used to process the data. If `None`, the processing class is loaded from the model's name + with [`~transformers.AutoProcessor.from_pretrained`]. A padding token, `tokenizer.pad_token`, must be set. + If the processing class has not set a padding token, `tokenizer.eos_token` will be used as the default. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function that will be used to compute metrics at evaluation. Must take a + [`~transformers.EvalPrediction`] and return a dictionary string to metric values. + callbacks (list of [`~transformers.TrainerCallback`], *optional*): + List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed + in [here](https://huggingface.co/docs/transformers/main_classes/callback). + + If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`] + method. + optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`): + A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your + model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration used to wrap the model. If `None`, the model is not wrapped. + """ + + _tag_names = ["trl", "tpo"] + _name = "TPO" + _paper = { + "title": "Triple Preference Optimization: Achieving Better Alignment using a Single Step Optimization", + "id": "2405.16681", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @misc{saeidi2025triplepreferenceoptimizationachieving, + title = {{Triple Preference Optimization: Achieving Better Alignment using a Single Step Optimization}}, + author = {Amir Saeidi and Shivanshu Verma and Aswin RRV and Kashif Rasul and Chitta Baral}, + year = 2025, + eprint = {2405.16681}, + archivePrefix= {arXiv}, + primaryClass = {cs.CL}, + url = {https://arxiv.org/abs/2405.16681}, + }"""), + } + + def __init__( + self, + model: "str | PreTrainedModel | PeftModel", + args: TPOConfig | None = None, + data_collator: DataCollator | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | None = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + peft_config: "PeftConfig | None" = None, + ): + # Args + if args is None: + model_name = model if isinstance(model, str) else get_config_model_id(model.config) + model_name = model_name.split("/")[-1] + args = TPOConfig(f"{model_name}-TPO") + + if train_dataset is None: + raise ValueError("`train_dataset` is required") + elif isinstance(train_dataset, IterableDataset): + # IterableDataset requires dispatch_batches=False because Accelerate's dispatch mode may try to concatenate + # batches from multiple processes, leading to mismatch errors. + if args.accelerator_config.dispatch_batches is True: + logger.warning( + "You are using an `IterableDataset` for training with `dispatch_batches=True`. `dispatch_batches` " + "is forced to `False` when using an `IterableDataset`. To remove this warning, unset " + "`dispatch_batches` in `TPOConfig` or set it to `False`." + ) + args.accelerator_config.dispatch_batches = False + + # Model + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + model = create_model_from_path(model, **model_init_kwargs) + else: + if args.model_init_kwargs is not None: + logger.warning( + "You passed `model_init_kwargs` to the `TPOConfig`, but your model is already instantiated. " + "The `model_init_kwargs` will be ignored." + ) + + # Processing class + if processing_class is None: + processing_class = AutoProcessor.from_pretrained( + get_config_model_id(model.config), trust_remote_code=args.trust_remote_code + ) + if not isinstance(processing_class, PreTrainedTokenizerBase): + raise TypeError( + "The `processing_class` must be a `PreTrainedTokenizerBase`. `TPOTrainer` does not currently " + "support vision-language models." + ) + self._tokenizer = processing_class + + if self._tokenizer.pad_token is None: + self._tokenizer.pad_token = self._tokenizer.eos_token + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge " + "and unload the existing adapter, save the resulting base model, and then pass that base model along " + "with the new `peft_config` to the trainer." + ) + # Create PEFT model + model = get_peft_model(model, peft_config) + + # When using gradient checkpointing with PEFT, we need to enable input gradients. transformers.Trainer normally + # handles this, but a bug currently prevents it; see https://github.com/huggingface/transformers/issues/42489 + if is_peft_model(model) and args.gradient_checkpointing: + model.enable_input_require_grads() + + # Data collator. When `tpo_alpha=0.0`, the NLL term on the gold response is disabled, so we can drop the + # reference branch from the batch entirely — this spares the model from computing logits for a third of + # each step. + if data_collator is None: + data_collator = DataCollatorForTriplePreference( + pad_token_id=self._tokenizer.pad_token_id, + max_length=args.max_length, + truncation_mode=args.truncation_mode, + pad_to_multiple_of=args.pad_to_multiple_of, + include_reference=args.tpo_alpha != 0.0, + ) + + # Training arguments + self.beta = args.beta + self.loss_type = args.loss_type + self.label_smoothing = args.label_smoothing + self.tpo_alpha = args.tpo_alpha + self.tpo_l_gamma = args.tpo_l_gamma + if self.loss_type in ["hinge", "ipo"] and self.label_smoothing > 0: + logger.warning( + f"You are using the {self.loss_type} loss type that does not support label smoothing. The " + "`label_smoothing` parameter will be ignored. Set `label_smoothing` to `0.0` to remove this warning." + ) + + # Dataset + train_dataset = self._prepare_dataset(train_dataset, processing_class, args, "train") + if eval_dataset is not None: + if isinstance(eval_dataset, dict): + eval_dataset = { + key: self._prepare_dataset(dataset, processing_class, args, key) + for key, dataset in eval_dataset.items() + } + else: + eval_dataset = self._prepare_dataset(eval_dataset, processing_class, args, "eval") + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + ) + + # Disable dropout in the model + if args.disable_dropout: + disable_dropout_in_model(model) + + # Initialize the metrics + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + self._total_train_tokens = 0 + + # Add tags to the model + self.model.add_model_tags(self._tag_names) + + def _tokenize( + self, + processing_class: PreTrainedTokenizerBase, + input: str | list, + **kwargs, + ) -> dict[str, list]: + """Tokenize a single example for dataset preprocessing. + + Dispatches to `apply_chat_template` for conversational input (list of message dicts) and to `__call__` for + non-conversational input (str). + + Args: + processing_class ([`~transformers.PreTrainedTokenizerBase`]): + The tokenizer to use. + input (`str` or `list`): + A string for non-conversational input, or a list of message dicts for conversational input. + **kwargs: + Forwarded to `apply_chat_template` (e.g. `add_generation_prompt`). + + Returns: + `dict` with at least an `"input_ids"` key mapping to a flat `list[int]`. + """ + if isinstance(input, list): # conversational: list of message dicts + return processing_class.apply_chat_template(input, tokenize=True, return_dict=True, **kwargs) + # non-conversational: plain text string + return processing_class(text=input) + + def _prepare_dataset( + self, + dataset: Dataset | IterableDataset, + processing_class: PreTrainedTokenizerBase, + args: TPOConfig, + dataset_name: str, + ) -> Dataset | IterableDataset: + # Validate that the triple-preference columns are present + first_example = next(iter(dataset)) + if "chosen" not in first_example or "rejected" not in first_example: + raise ValueError( + "TPO requires a triple-preference dataset with `chosen`, `rejected` and `reference` columns, but the " + f"dataset is missing `chosen` or `rejected`. Got columns: {list(first_example.keys())}." + ) + if "reference" not in first_example: + raise ValueError( + "TPO requires a triple-preference dataset with `chosen`, `rejected` and `reference` columns, but the " + f"dataset is missing the `reference` (gold) column. Got columns: {list(first_example.keys())}." + ) + + # Build the kwargs for the `map` function + map_kwargs = {} + if isinstance(dataset, Dataset): # IterableDataset does not support num_proc + map_kwargs["num_proc"] = args.dataset_num_proc + + with PartialState().main_process_first(): + # Extract the prompt if needed. Unlike DPO, we must also strip the extracted prompt from the reference + # column (see `_extract_triple_prompt`), which assumes the reference shares the same implicit prompt. + first_example = next(iter(dataset)) + if "prompt" not in first_example: + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Extracting prompt from {dataset_name} dataset" + dataset = dataset.map(_extract_triple_prompt, **map_kwargs) + + # Add EOS to completions for non-conversational data + first_example = next(iter(dataset)) + if not is_conversational(first_example): + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Adding EOS to {dataset_name} dataset" + + def add_eos(example, eos_token): + if not example["chosen"].endswith(eos_token): + example["chosen"] = example["chosen"] + eos_token + if not example["rejected"].endswith(eos_token): + example["rejected"] = example["rejected"] + eos_token + if not example["reference"].endswith(eos_token): + example["reference"] = example["reference"] + eos_token + return example + + dataset = dataset.map(add_eos, fn_kwargs={"eos_token": processing_class.eos_token}, **map_kwargs) + + # Tokenize the dataset + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Tokenizing {dataset_name} dataset" + + def tokenize_fn(example, processing_class): + tools = example.get("tools") + tools = json.loads(tools) if isinstance(tools, str) else tools + output = {} + if is_conversational(example): + prompt_ids = self._tokenize( + processing_class, + example["prompt"], + tools=tools, + add_generation_prompt=True, + **example.get("chat_template_kwargs", {}), + )["input_ids"] + prompt_chosen_ids = self._tokenize( + processing_class, + example["prompt"] + example["chosen"], + tools=tools, + **example.get("chat_template_kwargs", {}), + )["input_ids"] + prompt_rejected_ids = self._tokenize( + processing_class, + example["prompt"] + example["rejected"], + tools=tools, + **example.get("chat_template_kwargs", {}), + )["input_ids"] + prompt_reference_ids = self._tokenize( + processing_class, + example["prompt"] + example["reference"], + tools=tools, + **example.get("chat_template_kwargs", {}), + )["input_ids"] + else: + prompt_ids = self._tokenize(processing_class, example["prompt"])["input_ids"] + prompt_chosen_ids = self._tokenize(processing_class, example["prompt"] + example["chosen"])[ + "input_ids" + ] + prompt_rejected_ids = self._tokenize(processing_class, example["prompt"] + example["rejected"])[ + "input_ids" + ] + prompt_reference_ids = self._tokenize(processing_class, example["prompt"] + example["reference"])[ + "input_ids" + ] + + # Check if the tokenized prompt starts with the tokenized prompt+completion + if not prompt_chosen_ids[: len(prompt_ids)] == prompt_ids: + logger.warning( + "Mismatch between tokenized prompt and the start of tokenized prompt+chosen. " + "This may be due to unexpected tokenizer behavior, whitespace issues, or special " + "token handling. Verify that the tokenizer is processing text consistently." + ) + if not prompt_rejected_ids[: len(prompt_ids)] == prompt_ids: + logger.warning( + "Mismatch between tokenized prompt and the start of tokenized prompt+rejected. " + "This may be due to unexpected tokenizer behavior, whitespace issues, or special " + "token handling. Verify that the tokenizer is processing text consistently." + ) + if not prompt_reference_ids[: len(prompt_ids)] == prompt_ids: + logger.warning( + "Mismatch between tokenized prompt and the start of tokenized prompt+reference. " + "This may be due to unexpected tokenizer behavior, whitespace issues, or special " + "token handling. Verify that the tokenizer is processing text consistently." + ) + + output["prompt_ids"] = prompt_ids + output["chosen_ids"] = prompt_chosen_ids[len(prompt_ids) :] + output["rejected_ids"] = prompt_rejected_ids[len(prompt_ids) :] + output["reference_ids"] = prompt_reference_ids[len(prompt_ids) :] + return output + + dataset = dataset.map(tokenize_fn, fn_kwargs={"processing_class": processing_class}, **map_kwargs) + + return dataset + + def _set_signature_columns_if_needed(self): + # If `self.args.remove_unused_columns` is True, non-signature columns are removed. + # By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids" + # and "attention_mask"). + if self._signature_columns is None: + self._signature_columns = ["prompt_ids", "chosen_ids", "rejected_ids", "reference_ids"] + + def _compute_loss(self, model, inputs, return_outputs): + mode = "train" if self.model.training else "eval" + + # When `tpo_alpha=0.0` the NLL term is disabled and the collator drops the reference branch, so the batch + # is laid out as `[chosen, rejected]` (n_branches=2). Otherwise it is `[chosen, rejected, reference]` + # (n_branches=3). + n_branches = 3 if self.tpo_alpha != 0.0 else 2 + + _non_model_keys = {"completion_mask"} + model_kwargs = {k: v for k, v in inputs.items() if k not in _non_model_keys} + model_kwargs["use_cache"] = False + outputs = model(**model_kwargs) + + input_ids = inputs["input_ids"] + completion_mask = inputs["completion_mask"] + shift_logits = outputs.logits[..., :-1, :] + shift_labels = input_ids[..., 1:] + shift_completion_mask = completion_mask[..., 1:] + per_token_logps = selective_log_softmax(shift_logits, shift_labels) + per_token_logps[shift_completion_mask == 0] = 0.0 # mask out non-completion tokens + + # Length-normalized for IPO and TPO-L (matches the SimPO-style implicit reward used by the TPO paper); + # summed otherwise. + if self.loss_type in ("ipo", "tpo-l"): + completion_lengths = shift_completion_mask.sum(dim=1).clamp(min=1) + logps = per_token_logps.sum(dim=1) / completion_lengths + else: + logps = per_token_logps.sum(dim=1) + logps_chunks = logps.chunk(n_branches, dim=0) + chosen_logps, rejected_logps = logps_chunks[0], logps_chunks[1] + + # Contrastive loss between chosen and rejected. Unlike DPO, TPO does not subtract reference-model log-probs: + # the "reference" in TPO is a gold response used in the NLL term below, not a separate reference policy. + delta_score = chosen_logps - rejected_logps + + if self.loss_type == "sigmoid": + per_sequence_loss = ( + -F.logsigmoid(self.beta * delta_score) * (1 - self.label_smoothing) + - F.logsigmoid(-self.beta * delta_score) * self.label_smoothing + ) + + elif self.loss_type == "hinge": + per_sequence_loss = torch.relu(1 - self.beta * delta_score) + + elif self.loss_type == "ipo": + # (Eq. 17) of the IPO paper where beta is the regularization parameter for the IPO loss, denoted by τ. + per_sequence_loss = (delta_score - 1 / (2 * self.beta)) ** 2 + + elif self.loss_type == "tpo-l": + # Length-normalized TPO-L variant: subtract a target reward margin γ/β before the sigmoid. + gamma_logratios = self.tpo_l_gamma / self.beta + shifted_delta = delta_score - gamma_logratios + per_sequence_loss = ( + -F.logsigmoid(self.beta * shifted_delta) * (1 - self.label_smoothing) + - F.logsigmoid(-self.beta * shifted_delta) * self.label_smoothing + ) + + else: + raise ValueError( + f"Unknown loss type: {self.loss_type}. Should be one of ['sigmoid', 'hinge', 'ipo', 'tpo-l']" + ) + + loss = per_sequence_loss.mean() + + # NLL loss on the gold (`reference`) response. Mirrors the `"sft"` loss branch of `DPOTrainer._compute_loss`: + # we restrict the cross-entropy to the completion tokens of the reference sequence and let `F.cross_entropy` + # average over them. The NLL contribution is folded into the main `loss` (matching DPO/SFT convention: the + # individual NLL term is not logged separately). + if n_branches == 3: + _, _, ref_logits = shift_logits.chunk(3, dim=0) + _, _, ref_labels = shift_labels.chunk(3, dim=0) + _, _, ref_mask = shift_completion_mask.chunk(3, dim=0) + ref_mask = ref_mask.bool() + nll_loss = F.cross_entropy(ref_logits[ref_mask], ref_labels[ref_mask]) + loss = loss + self.tpo_alpha * nll_loss + + # Log the metrics + # Entropy + per_token_entropy = entropy_from_logits(shift_logits.detach()) + entropy = per_token_entropy[shift_completion_mask.bool()].mean() + entropy = self.accelerator.gather_for_metrics(entropy).mean().item() + self._metrics[mode]["entropy"].append(entropy) + + # Number of tokens + if mode == "train": + num_tokens_in_batch = self.accelerator.gather_for_metrics(inputs["attention_mask"].sum()).sum().item() + self._total_train_tokens += num_tokens_in_batch + self._metrics[mode]["num_tokens"] = [self._total_train_tokens] + + # Average logits for chosen and rejected completions + logits_chunks = shift_logits.detach().chunk(n_branches, dim=0) + mask_chunks = shift_completion_mask.chunk(n_branches, dim=0) + labels_chunks = shift_labels.chunk(n_branches, dim=0) + chosen_logits, rejected_logits = logits_chunks[0], logits_chunks[1] + chosen_mask, rejected_mask = mask_chunks[0], mask_chunks[1] + chosen_labels = labels_chunks[0] + total_chosen_logits = chosen_logits[chosen_mask.bool()].mean(-1).sum() + total_chosen_tokens = chosen_mask.sum() + total_rejected_logits = rejected_logits[rejected_mask.bool()].mean(-1).sum() + total_rejected_tokens = rejected_mask.sum() + total_chosen_logits = self.accelerator.gather_for_metrics(total_chosen_logits).sum().item() + total_chosen_tokens = self.accelerator.gather_for_metrics(total_chosen_tokens).sum().item() + total_rejected_logits = self.accelerator.gather_for_metrics(total_rejected_logits).sum().item() + total_rejected_tokens = self.accelerator.gather_for_metrics(total_rejected_tokens).sum().item() + avg_chosen_logits = total_chosen_logits / total_chosen_tokens if total_chosen_tokens > 0 else 0.0 + avg_rejected_logits = total_rejected_logits / total_rejected_tokens if total_rejected_tokens > 0 else 0.0 + self._metrics[mode]["logits/chosen"].append(avg_chosen_logits) + self._metrics[mode]["logits/rejected"].append(avg_rejected_logits) + + # Token accuracy for the chosen completions + predictions = chosen_logits.argmax(dim=-1) + chosen_bool_mask = chosen_mask.bool() + correct_predictions = (predictions == chosen_labels) & chosen_bool_mask + total_tokens = chosen_bool_mask.sum() + correct_tokens = correct_predictions.sum() + correct_tokens = self.accelerator.gather_for_metrics(correct_tokens) + total_tokens = self.accelerator.gather_for_metrics(total_tokens) + total_sum = total_tokens.sum() + accuracy = (correct_tokens.sum() / total_sum).item() if total_sum > 0 else 0.0 + self._metrics[mode]["mean_token_accuracy"].append(accuracy) + + # Rewards for chosen and rejected completions (β · log π_θ as in the SimPO/TPO implicit reward) + chosen_rewards = self.beta * chosen_logps.detach() + rejected_rewards = self.beta * rejected_logps.detach() + agg_chosen_rewards = self.accelerator.gather(chosen_rewards) + agg_rejected_rewards = self.accelerator.gather(rejected_rewards) + self._metrics[mode]["rewards/chosen"].append(agg_chosen_rewards.mean().item()) + self._metrics[mode]["rewards/rejected"].append(agg_rejected_rewards.mean().item()) + + # Reward accuracy + reward_accuracies = (chosen_rewards > rejected_rewards).float() + agg_reward_accuracies = self.accelerator.gather(reward_accuracies) + self._metrics[mode]["rewards/accuracies"].append(agg_reward_accuracies.mean().item()) + + # Reward margins + margins = chosen_rewards - rejected_rewards + agg_margins = self.accelerator.gather(margins) + self._metrics[mode]["rewards/margins"].append(agg_margins.mean().item()) + + # Average log probabilities for chosen and rejected completions + self._metrics[mode]["logps/chosen"].append(self.accelerator.gather(chosen_logps).mean().item()) + self._metrics[mode]["logps/rejected"].append(self.accelerator.gather(rejected_logps).mean().item()) + + return (loss, outputs) if return_outputs else loss + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + return self._compute_loss(model, inputs, return_outputs) + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} # average the metrics + + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + # During eval, Trainer calls prediction_step. If no labels are present in the inputs, it only runs forward and + # returns logits. We override prediction_step to force compute_loss, because this trainer doesn't involve labels. + def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys: list[str] | None = None): + inputs = self._prepare_inputs(inputs) + with torch.no_grad(), self.compute_loss_context_manager(): + if prediction_loss_only: + loss = self.compute_loss(model, inputs, return_outputs=False) + logits, labels = None, None + else: + loss, outputs = self.compute_loss(model, inputs, return_outputs=True) + logits, labels = outputs.logits, inputs["input_ids"] + return loss, logits, labels + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/utils.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..db784a7f4894897e2d3ea249362c1419c45d127b --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/utils.py @@ -0,0 +1,858 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This file contains utility classes and functions that are used across more than one experimental trainer or feature. + +import inspect +import logging +from copy import deepcopy +from dataclasses import dataclass +from typing import Any + +import pyarrow as pa +import pyarrow.types +import torch +from accelerate.utils import is_peft_model +from packaging.version import Version +from pyarrow import compute as pc +from torch import nn +from torch.nn.utils.rnn import pad_sequence +from transformers import PreTrainedModel, PreTrainedTokenizerBase, TrainingArguments +from transformers.integrations.deepspeed import is_deepspeed_zero3_enabled +from transformers.utils import ( + is_peft_available, + is_torch_mlu_available, + is_torch_mps_available, + is_torch_npu_available, + is_torch_xpu_available, +) + +from ..data_utils import DatasetType, _get_dataset_format +from ..trainer.utils import pad + + +if is_peft_available(): + import peft + from peft import PeftConfig, PeftModel, get_peft_model + + +@dataclass +class DPODataCollatorWithPadding: + r""" + DPO DataCollator class that pads the tokenized inputs to the maximum length of the batch. + + Args: + pad_token_id (`int` defaults to 0): + The tokenizer's pad_token_id. + is_encoder_decoder (`bool` or `None`, `optional`, defaults to `None`): + Whether you model has an encoder_decoder architecture. + """ + + pad_token_id: int = 0 + is_encoder_decoder: bool | None = False + + def __call__(self, features: list[dict[str, Any]]) -> dict[str, Any]: + # first, pad everything to the same length + padded_batch = {} + for k in features[0].keys(): + if k.endswith(("_input_ids", "_attention_mask", "_labels", "_pixel_values")): + if self.is_encoder_decoder: + to_pad = [torch.LongTensor(ex[k]) for ex in features] + + if (k.startswith("prompt")) and (k.endswith("input_ids")): + if self.pad_token_id is None: + raise ValueError( + "Padding is enabled, but the tokenizer is not configured with a padding token." + " Explicitly set `tokenizer.pad_token` (e.g. `tokenizer.pad_token = tokenizer.eos_token`)" + " before calling the trainer." + ) + padding_value = self.pad_token_id + elif k.endswith("_attention_mask"): + padding_value = 0 + elif k.startswith(("chosen", "rejected", "completion")) or ("decoder" in k): + padding_value = -100 + else: + raise ValueError(f"Unexpected key in batch '{k}'") + padded_batch[k] = pad_sequence(to_pad, batch_first=True, padding_value=padding_value) + else: + # Set padding value based on the key + if k.endswith("_input_ids"): + if self.pad_token_id is None: + raise ValueError( + "Padding is enabled, but the tokenizer is not configured with a padding token." + " Explicitly set `tokenizer.pad_token` (e.g. `tokenizer.pad_token = tokenizer.eos_token`)" + " before calling the trainer." + ) + padding_value = self.pad_token_id + elif k.endswith("_labels"): + padding_value = -100 + elif k.endswith("_attention_mask"): + padding_value = 0 + elif k.endswith("_pixel_values"): + padding_value = 0 # TODO: check if this is correct + else: + raise ValueError(f"Unexpected key in batch '{k}'") + + # Set padding side based on the key + if k in ["prompt_input_ids", "prompt_attention_mask"]: + padding_side = "left" + else: + padding_side = "right" + + # Set the dtype + if k.endswith("_pixel_values"): + dtype = torch.float32 # will be downcasted if necessary by the Trainer + else: + dtype = torch.int64 + + # Convert to tensor and pad + to_pad = [torch.tensor(ex[k], dtype=dtype) for ex in features] + padded_batch[k] = pad(to_pad, padding_value=padding_value, padding_side=padding_side) + elif k.endswith("_logps"): + # the cached reference model logprobs + padded_batch[k] = torch.tensor([ex[k] for ex in features]) + else: + padded_batch[k] = [ex[k] for ex in features] + + return padded_batch + + +def pad_byte_offsets(offsets: list[tuple[int, int]], target_length: int, padding_side: str) -> torch.Tensor: + """Build a ``[target_length, 2]`` long tensor from ``(start, end)`` byte-offset tuples, + padding with ``(0, 0)`` on the requested side.""" + offs = torch.tensor(offsets, dtype=torch.long).reshape(-1, 2) + pad_len = target_length - offs.size(0) + if pad_len <= 0: + return offs + pad_block = torch.zeros(pad_len, 2, dtype=torch.long) + return torch.cat([pad_block, offs], dim=0) if padding_side == "left" else torch.cat([offs, pad_block], dim=0) + + +def is_byte_level_tokenizer(backend) -> bool: + """Whether ``backend`` is a ByteLevel BPE tokenizer (Llama-3 family, SmolLM, Qwen, \u2026) \u2014 its pieces are in + byte\u2192unicode space, one char per source byte. Detected via the pre-tokenizer / decoder repr.""" + return "ByteLevel" in repr(backend.pre_tokenizer) or "ByteLevel" in repr(backend.decoder) + + +def piece_byte_len(piece: str) -> int: + """UTF-8 byte length of a ByteLevel BPE token piece \u2014 each char maps 1:1 to one source byte. + + Cross-tokenizer ULD targets ByteLevel BPE pairs (Llama-3, Qwen, SmolLM, Phi, Mistral v0.3+, \u2026); SentencePiece + students are out of scope here and would need the loss-level projection from X-Token to align.""" + return len(piece) + + +def _bytes_to_unicode() -> dict[int, str]: + bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("\u00a1"), ord("\u00ac") + 1)) + bs += list(range(ord("\u00ae"), ord("\u00ff") + 1)) + cs = bs[:] + n = 0 + for b in range(256): + if b not in bs: + bs.append(b) + cs.append(256 + n) + n += 1 + return dict(zip(bs, [chr(n) for n in cs], strict=True)) + + +_BYTE_LEVEL_DECODER = {ch: b for b, ch in _bytes_to_unicode().items()} + + +def _byte_level_piece_len(piece: str, text_bytes: bytes, start: int) -> int | None: + piece_bytes = [] + for ch in piece: + if ch not in _BYTE_LEVEL_DECODER: + return None + piece_bytes.append(_BYTE_LEVEL_DECODER[ch]) + if piece_bytes and piece_bytes[0] == ord(" ") and text_bytes[start : start + 1] != b" ": + piece_bytes = piece_bytes[1:] + return len(piece_bytes) + + +def _split_repeated_byte_offsets(byte_offsets: list[tuple[int, int]], tokens: list[str]) -> list[tuple[int, int]]: + """Split repeated char-derived spans for byte-fallback or byte-level tokens.""" + normalized = list(byte_offsets) + i = 0 + while i < len(byte_offsets): + j = i + 1 + while j < len(byte_offsets) and byte_offsets[j] == byte_offsets[i]: + j += 1 + + if j - i > 1: + start, end = byte_offsets[i] + piece_lengths = [piece_byte_len(token) for token in tokens[i:j]] + if sum(piece_lengths) == end - start: + cursor = start + for offset_idx, length in enumerate(piece_lengths, start=i): + normalized[offset_idx] = (cursor, cursor + length) + cursor += length + + i = j + return normalized + + +def _normalize_byte_offsets( + byte_offsets: list[tuple[int, int]], tokens: list[str], text_bytes: bytes +) -> list[tuple[int, int]]: + byte_offsets = _split_repeated_byte_offsets(byte_offsets, tokens) + normalized = [] + cursor = 0 + + for idx, (start, end) in enumerate(byte_offsets): + if start == end: + normalized.append((cursor, cursor)) + continue + + piece_len = _byte_level_piece_len(tokens[idx], text_bytes, start) + next_start = byte_offsets[idx + 1][0] if idx + 1 < len(byte_offsets) else None + has_overlap = start < cursor or (next_start is not None and next_start < end) + + if piece_len is not None and (has_overlap or piece_len == end - start): + candidate_start = max(start, cursor) + candidate_end = candidate_start + piece_len + if candidate_end <= end: + start = candidate_start + end = candidate_end + + if start < cursor or end < start: + raise ValueError( + "Tokenizer produced overlapping byte offsets that could not be normalized. " + "Cross-tokenizer ULD requires monotonic byte offsets." + ) + + normalized.append((start, end)) + cursor = end + + return normalized + + +def encode_with_byte_offsets(backend, texts: list[str], add_special_tokens: bool = False): + """Encode ``texts`` and return per-text ``(ids, byte_offsets)`` pairs. + + Byte offsets are derived from the fast tokenizer's character offsets via an O(N) char-to-byte cumulative table. + Overlapping spans from byte-level and byte-fallback tokens are split across their byte pieces.""" + if not is_byte_level_tokenizer(backend): + raise NotImplementedError( + "Cross-tokenizer ULD currently supports only ByteLevel BPE tokenizers " + "(Llama-3, Qwen, SmolLM, Phi, Mistral v0.3+, …). The given tokenizer is not ByteLevel." + ) + encs = backend.encode_batch(texts, add_special_tokens=add_special_tokens) + out = [] + for text, enc in zip(texts, encs, strict=True): + char_to_byte = [0] + for ch in text: + char_to_byte.append(char_to_byte[-1] + len(ch.encode("utf-8"))) + byte_offsets = [(char_to_byte[s], char_to_byte[e]) for s, e in enc.offsets] + byte_offsets = _normalize_byte_offsets(byte_offsets, enc.tokens, text.encode("utf-8")) + out.append((list(enc.ids), byte_offsets)) + return out + + +@dataclass +class DataCollatorForChatML: + """ + Data collator for ChatML format datasets. + """ + + tokenizer: PreTrainedTokenizerBase + ignore_index: int = -100 + max_length: int = None + prompt_key: str = "prompt" + messages_key: str = "messages" + + def __post_init__(self): + if self.tokenizer.pad_token_id is None: + raise ValueError("The tokenizer does not have a pad token. Please set `pad_token_id` in the tokenizer.") + if self.max_length is None: + # set a sensible default + self.max_length = min(self.tokenizer.model_max_length, 1024) + + def __call__(self, examples: list[dict[str, Any]]) -> dict[str, torch.Tensor]: + input_ids = [] + attention_mask = [] + prompts_input_ids = [] + prompt_attention_mask = [] + labels = [] + byte_offsets: list[list[tuple[int, int]]] = [] + + for example in examples: + formatted_prompt = example.get(self.prompt_key, example.get("original_prompt_text", None)) + if formatted_prompt is None: + prompt = example[self.messages_key][:-1] + formatted_prompt = self.tokenizer.apply_chat_template( + prompt, add_generation_prompt=True, tokenize=False + ) + + if "input_ids" not in example: + message = example[self.messages_key] + formatted_message = self.tokenizer.apply_chat_template( + message, add_generation_prompt=False, tokenize=False + ) + if is_byte_level_tokenizer(self.tokenizer.backend_tokenizer): + [(message_input_ids_full, full_offs)] = encode_with_byte_offsets( + self.tokenizer.backend_tokenizer, [formatted_message], add_special_tokens=False + ) + prompt_byte_len = len(formatted_prompt.encode("utf-8")) + completion_start_idx_full = next( + (idx for idx, (start, _) in enumerate(full_offs) if start >= prompt_byte_len), + len(message_input_ids_full), + ) + else: + # Non-ByteLevel tokenizer: byte offsets are unnecessary (cross-tokenizer ULD requires ByteLevel + # anyway). Fall back to plain tokenization so GKD / non-ULD trainers with SentencePiece or + # Unigram tokenizers still work through this collator. + message_input_ids_full = self.tokenizer( + formatted_message, add_special_tokens=False, return_tensors=None + )["input_ids"] + completion_start_idx_full = len( + self.tokenizer(formatted_prompt, add_special_tokens=False, return_tensors=None)["input_ids"] + ) + full_offs = [(0, 0)] * len(message_input_ids_full) + prompt_byte_len = 0 + + # Keep the last max_length tokens — drops oldest prompt context first, + # never drops from the END (the model's recent context). + if self.max_length is not None and len(message_input_ids_full) > self.max_length: + sample_ids = message_input_ids_full[-self.max_length :] + sample_offs = full_offs[-self.max_length :] + current_prompt_len = max( + 0, completion_start_idx_full - (len(message_input_ids_full) - self.max_length) + ) + else: + sample_ids = message_input_ids_full + sample_offs = full_offs + current_prompt_len = completion_start_idx_full + + # Make completion-relative: prompt positions zeroed, completion offsets shifted. If truncation + # ate into the completion (no prompt tokens kept and the first kept token is mid-completion), + # rebase to byte 0 of the kept completion so teacher/student share the same coordinate system. + kept_completion_offs = sample_offs[current_prompt_len:] + base = ( + kept_completion_offs[0][0] if kept_completion_offs and current_prompt_len == 0 else prompt_byte_len + ) + completion_offs = [(s - base, e - base) for s, e in kept_completion_offs] + sample_offs = [(0, 0)] * current_prompt_len + completion_offs + + input_ids.append(sample_ids) + attention_mask.append([1] * len(sample_ids)) + current_prompt_ids = sample_ids[:current_prompt_len] + byte_offsets.append(sample_offs) + else: + sample_ids = example["input_ids"] + input_ids.append(sample_ids) + attention_mask.append(example.get("attention_mask", [1] * len(sample_ids))) + completion_mask = example.get("completion_mask") + if completion_mask is not None: + # Use the tracked boundary directly: no re-tokenization, survives truncation. + prompt_len = completion_mask.index(1) if 1 in completion_mask else len(sample_ids) + current_prompt_ids = sample_ids[:prompt_len] + else: + # No tracked boundary: tokenize the prompt and cap with a slice (avoid `truncation=True`, + # which would persist on the shared backend used by `encode_with_byte_offsets`). + tokenized_prompt = self.tokenizer( + formatted_prompt, + padding=False, + return_tensors=None, + add_special_tokens=False, + ) + current_prompt_ids = tokenized_prompt["input_ids"][: len(sample_ids)] + byte_offsets.append(example.get("byte_offsets", [(0, 0)] * len(sample_ids))) + + prompts_input_ids.append(current_prompt_ids) + prompt_attention_mask.append([1] * len(current_prompt_ids)) + + label = [self.ignore_index] * len(sample_ids) + label[len(current_prompt_ids) :] = sample_ids[len(current_prompt_ids) :] + labels.append(label) + + input_ids = pad( + [torch.tensor(x, dtype=torch.long) for x in input_ids], + padding_side="left", + padding_value=self.tokenizer.pad_token_id, + ) + attention_mask = pad( + [torch.tensor(x, dtype=torch.long) for x in attention_mask], padding_side="left", padding_value=0 + ) + labels = pad( + [torch.tensor(x, dtype=torch.long) for x in labels], padding_side="left", padding_value=self.ignore_index + ) + prompts_input_ids = pad( + [torch.tensor(x, dtype=torch.long) for x in prompts_input_ids], + padding_side="left", + padding_value=self.tokenizer.pad_token_id, + ) + prompt_attention_mask = pad( + [torch.tensor(x, dtype=torch.long) for x in prompt_attention_mask], padding_side="left", padding_value=0 + ) + + target_len = input_ids.size(1) + byte_offsets_tensor = torch.stack( + [pad_byte_offsets(offs, target_len, padding_side="left") for offs in byte_offsets], dim=0 + ) + + out = { + "input_ids": input_ids, + "attention_mask": attention_mask, + "labels": labels, + "prompts": prompts_input_ids, + "prompt_attention_mask": prompt_attention_mask, + "byte_offsets": byte_offsets_tensor, + } + # Forward source text for cross-tokenizer ULD, when the dataset has it. + if "original_prompt_text" in examples[0] and "original_completion_text" in examples[0]: + out["original_prompt_text"] = [ex["original_prompt_text"] for ex in examples] + out["original_completion_text"] = [ex["original_completion_text"] for ex in examples] + return out + + +def truncate_right( + input_ids: torch.Tensor, stop_token_id: int, pad_token_id: int +) -> tuple[torch.Tensor, torch.Tensor]: + """ + Truncates the input tensor from the right side after the first occurrence of the stop token. + + Args: + input_ids (`torch.Tensor`): + The tensor containing the responses to be truncated + stop_token_id (`int`): + The token ID representing the stop token where truncation occurs + pad_token_id (`int`): + The token ID representing the pad token used to fill the truncated responses + + Returns: + tuple: + - `output_ids` (`torch.Tensor`): + The truncated responses tensor with pad tokens filled after the stop token + - `mask` (`torch.Tensor`): + The mask tensor to indicate the padding tokens + """ + trunc_idxs = first_true_indices(input_ids == stop_token_id).unsqueeze(-1) + new_size = [1] * (len(input_ids.size()) - 1) + [input_ids.shape[1]] + idxs = torch.arange(input_ids.shape[1], device=input_ids.device).view(*new_size) + output_ids = torch.masked_fill(input_ids, idxs > trunc_idxs, pad_token_id) + mask = torch.masked_fill(torch.ones_like(input_ids), idxs > trunc_idxs, 0) + return output_ids, mask + + +def add_bos_token_if_needed( + bos_token_id: int | None, + prompt_len_input_ids: int, + prompt_tokens: dict[str, list[int]], + chosen_prompt_len_input_ids: int, + chosen_tokens: dict[str, list[int]], + rejected_prompt_len_input_ids: int, + rejected_tokens: dict[str, list[int]], +): + if bos_token_id is not None: + if prompt_len_input_ids == 0 or bos_token_id != prompt_tokens["prompt_input_ids"][0]: + prompt_tokens["prompt_input_ids"] = [bos_token_id] + prompt_tokens["prompt_input_ids"] + prompt_tokens["prompt_attention_mask"] = [1] + prompt_tokens["prompt_attention_mask"] + if chosen_prompt_len_input_ids == 0 or bos_token_id != chosen_tokens["prompt_input_ids"][0]: + chosen_tokens["prompt_input_ids"] = [bos_token_id] + chosen_tokens["prompt_input_ids"] + chosen_tokens["prompt_attention_mask"] = [1] + chosen_tokens["prompt_attention_mask"] + if rejected_prompt_len_input_ids == 0 or bos_token_id != rejected_tokens["prompt_input_ids"][0]: + rejected_tokens["prompt_input_ids"] = [bos_token_id] + rejected_tokens["prompt_input_ids"] + rejected_tokens["prompt_attention_mask"] = [1] + rejected_tokens["prompt_attention_mask"] + return prompt_tokens, chosen_tokens, rejected_tokens + + +def add_eos_token_if_needed( + eos_token_id: int, chosen_tokens: dict[str, list[int]], rejected_tokens: dict[str, list[int]] +): + if len(chosen_tokens["input_ids"]) == 0 or eos_token_id != chosen_tokens["input_ids"][-1]: + chosen_tokens["input_ids"].append(eos_token_id) + chosen_tokens["attention_mask"].append(1) + if len(rejected_tokens["input_ids"]) == 0 or eos_token_id != rejected_tokens["input_ids"][-1]: + rejected_tokens["input_ids"].append(eos_token_id) + rejected_tokens["attention_mask"].append(1) + return chosen_tokens, rejected_tokens + + +def first_true_indices(bools: torch.Tensor, dtype=torch.long) -> torch.Tensor: + """ + Takes an N-dimensional bool tensor and returns an (N-1)-dimensional tensor of integers giving the position of the + first True in each "row". + + Returns the length of the rows (bools.size(-1)) if no element is True in a given row. + + Args: + bools (`torch.Tensor`): + An N-dimensional boolean tensor. + dtype (`torch.dtype`, *optional*): + The desired data type of the output tensor. Defaults to `torch.long`. + + Returns: + `torch.Tensor`: + An (N-1)-dimensional tensor of integers indicating the position of the first True in each row. If no True + value is found in a row, returns the length of the row. + """ + row_len = bools.size(-1) + zero_or_index = row_len * (~bools).type(dtype) + torch.arange(row_len, dtype=dtype, device=bools.device) + return torch.min(zero_or_index, dim=-1).values + + +def get_reward( + model: torch.nn.Module, query_responses: torch.Tensor, pad_token_id: int, context_length: int +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Computes the reward logits and the rewards for a given model and query responses. + + Args: + model (`torch.nn.Module`): + The model used to compute the reward logits. + query_responses (`torch.Tensor`): + The tensor containing the query responses. + pad_token_id (`int`): + The token ID representing the pad token. + context_length (`int`): + The length of the context in the query responses. + + Returns: + tuple: + - `reward_logits` (`torch.Tensor`): + The logits for the reward model. + - `final_rewards` (`torch.Tensor`): + The final rewards for each query response. + - `sequence_lengths` (`torch.Tensor`): + The lengths of the sequences in the query responses. + """ + attention_mask = query_responses != pad_token_id + position_ids = attention_mask.cumsum(1) - attention_mask.long() # exclusive cumsum + lm_backbone = getattr(model, model.base_model_prefix) + input_ids = torch.masked_fill(query_responses, ~attention_mask, 0) + output = lm_backbone( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + return_dict=True, + output_hidden_states=True, + use_cache=False, # otherwise mistral-based RM would error out + ) + reward_logits = model.score(output.hidden_states[-1]) + sequence_lengths = first_true_indices(query_responses[:, context_length:] == pad_token_id) - 1 + context_length + # https://github.com/huggingface/transformers/blob/dc68a39c8111217683bf49a4912d0c9018bab33d/src/transformers/models/gpt2/modeling_gpt2.py#L1454 + return ( + reward_logits, + reward_logits[ + torch.arange(reward_logits.size(0), device=reward_logits.device), + sequence_lengths, + ].squeeze(-1), + sequence_lengths, + ) + + +def prepare_model_for_kbit_training(model, use_gradient_checkpointing=True, gradient_checkpointing_kwargs=None): + r""" + Prepare a k-bit quantized transformers model for training (PEFT/QLoRA). + """ + loaded_in_kbit = getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False) + quant_methods = ["gptq", "aqlm", "eetq", "torchao", "hqq"] + is_quantized = getattr(model, "quantization_method", None) in quant_methods or getattr( + model, "hqq_quantized", False + ) + + if gradient_checkpointing_kwargs is None: + gradient_checkpointing_kwargs = {} + + for _, param in model.named_parameters(): + # freeze all parameters + param.requires_grad = False + + # Enable gradient checkpointing if needed + if (loaded_in_kbit or is_quantized) and use_gradient_checkpointing: + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + # backward-compatible hook + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + supports_gc_kwargs = "gradient_checkpointing_kwargs" in list( + inspect.signature(model.gradient_checkpointing_enable).parameters + ) + gc_kwargs = {"gradient_checkpointing_kwargs": gradient_checkpointing_kwargs} if supports_gc_kwargs else {} + model.gradient_checkpointing_enable(**gc_kwargs) + + return model + + +def enable_gradient_checkpointing( + model: PreTrainedModel, gradient_checkpointing_kwargs: dict | None +) -> PreTrainedModel: + """Enables gradient checkpointing for the model.""" + # Enable gradient checkpointing on the base model for PEFT + if is_peft_model(model): + model.base_model.gradient_checkpointing_enable() + # Enable gradient checkpointing for non-PEFT models + else: + model.gradient_checkpointing_enable() + + gradient_checkpointing_kwargs = gradient_checkpointing_kwargs or {} + use_reentrant = ( + "use_reentrant" not in gradient_checkpointing_kwargs or gradient_checkpointing_kwargs["use_reentrant"] + ) + + if use_reentrant: + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + return model + + +def prepare_peft_model( + model: PreTrainedModel, peft_config: "PeftConfig | None", args: TrainingArguments +) -> PreTrainedModel: + """Prepares a model for PEFT training.""" + if not is_peft_available(): + raise ImportError("PEFT is required to use a peft model. Run `pip install peft`.") + + if isinstance(model, PeftModel) and peft_config is not None: + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge and " + "unload the existing adapter, save the resulting base model, and then pass that base model along with the " + "new `peft_config` to the trainer." + ) + + # Handle quantized models (QLoRA) + is_qlora = getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False) + + is_sharded_qlora = False + if getattr(model, "is_loaded_in_4bit", False): + # Check if model is sharded (FSDP/DS-Zero3) + for _, param in model.named_parameters(): + if param.__class__.__name__ == "Params4bit": + is_sharded_qlora = param.data.device.type in {"cpu", "meta"} + break + + # Prepare model for kbit training if needed + if is_qlora and not is_sharded_qlora and not isinstance(model, PeftModel): + model = prepare_model_for_kbit_training( + model, + use_gradient_checkpointing=args.gradient_checkpointing, + gradient_checkpointing_kwargs=args.gradient_checkpointing_kwargs or {}, + ) + # Disable gradient checkpointing as it's handled by prepare_model_for_kbit_training + args.gradient_checkpointing = False + elif args.gradient_checkpointing: + model = enable_gradient_checkpointing(model, args.gradient_checkpointing_kwargs) + + # Create PEFT model + if peft_config is not None: + if ( + Version(peft.__version__) >= Version("0.12") # autocast_adapter_dtype introduced in 0.12 + and getattr(model, "is_loaded_in_4bit", False) + and is_sharded_qlora + ): + model = get_peft_model(model, peft_config, autocast_adapter_dtype=False) + else: + model = get_peft_model(model, peft_config) + + # Handle bf16 casting for 4-bit models + if args.bf16 and getattr(model, "is_loaded_in_4bit", False) and not is_sharded_qlora: + peft_module_casting_to_bf16(model) + + return model + + +def pad_to_length(tensor: torch.Tensor, length: int, pad_value: int | float, dim: int = -1) -> torch.Tensor: + if tensor.size(dim) >= length: + return tensor + else: + pad_size = list(tensor.shape) + pad_size[dim] = length - tensor.size(dim) + return torch.cat( + [ + tensor, + pad_value * torch.ones(*pad_size, dtype=tensor.dtype, device=tensor.device), + ], + dim=dim, + ) + + +def empty_cache() -> None: + """Empties the cache of the available torch device. + + This function checks for the availability of different torch devices (CUDA, MLU, MPS, NPU, XPU) and empties the + cache of the first available device it finds. + + If none of the specific devices are available, it defaults to emptying the CUDA cache. + """ + if is_torch_mlu_available(): + torch.mlu.empty_cache() + elif is_torch_mps_available(): + torch.mps.empty_cache() + elif is_torch_npu_available(): + torch.npu.empty_cache() + elif is_torch_xpu_available(): + torch.xpu.empty_cache() + else: + torch.cuda.empty_cache() + + +def peft_module_casting_to_bf16(model): + for name, module in model.named_modules(): + if isinstance(module, torch.nn.LayerNorm) or "norm" in name: + module = module.to(torch.float32) + elif any(x in name for x in ["lm_head", "embed_tokens", "wte", "wpe"]): + if hasattr(module, "weight"): + if module.weight.dtype == torch.float32: + module = module.to(torch.bfloat16) + + +LAYER_PATTERNS = [ + "transformer.h.{layer}", + "model.decoder.layers.{layer}", + "gpt_neox.layers.{layer}", + "model.layers.{layer}", +] + + +def create_reference_model( + model: nn.Module, num_shared_layers: int | None = None, pattern: str | None = None +) -> nn.Module: + """ + Creates a static reference copy of a model. Note that model will be in `.eval()` mode. + + Args: + model ([`nn.Module`]): The model to be copied. + num_shared_layers (`int`, *optional*): + The number of initial layers that are shared between both models and kept frozen. Shared layers reference + the same storage as the source model, so they are not duplicated in memory. + pattern (`str`, *optional*): The shared layers are selected with a string pattern + (e.g. "transformer.h.{layer}" for GPT2) and if a custom pattern is necessary it can be passed here. + + Returns: + [`nn.Module`] + """ + if is_deepspeed_zero3_enabled(): + raise ValueError( + "DeepSpeed ZeRO-3 is enabled and is not compatible with `create_reference_model()`. Please instantiate your reference model directly with `AutoModelForCausalLM.from_pretrained()`." + ) + + parameter_names = [n for n, _ in model.named_parameters()] + ref_model = deepcopy(model) + + # if no layers are shared, return copy of model + if num_shared_layers is None: + for param_name in parameter_names: + param = ref_model.get_parameter(param_name) + param.requires_grad = False + return ref_model.eval() + + # identify layer name pattern + if pattern is not None: + pattern = pattern.format(layer=num_shared_layers) + else: + for pattern_candidate in LAYER_PATTERNS: + pattern_candidate = pattern_candidate.format(layer=num_shared_layers) + if any(pattern_candidate in name for name in parameter_names): + pattern = pattern_candidate + break + + if pattern is None: + raise ValueError("Layer pattern could not be matched.") + + # divide parameters in shared and unshared parameter lists + shared_param_list = [] + unshared_param_list = [] + + shared_parameter = True + for name, _param in model.named_parameters(): + if pattern in name: + shared_parameter = False + if shared_parameter: + shared_param_list.append(name) + else: + unshared_param_list.append(name) + + # Freeze the shared layers in the source model, then point the reference parameter at the same + # storage instead of keeping the `deepcopy` duplicate. The shared (frozen) layers are thus held in + # memory only once; because they are frozen in the model, the reference stays static during training. + for param_name in shared_param_list: + param = model.get_parameter(param_name) + param.requires_grad = False + + ref_param = ref_model.get_parameter(param_name) + ref_param.data = param.data + ref_param.requires_grad = False + + # for all other parameters just make sure they don't use gradients + for param_name in unshared_param_list: + param = ref_model.get_parameter(param_name) + param.requires_grad = False + + if pattern is not None and len(unshared_param_list) == 0: + logging.warning("Pattern passed or found, but no layers matched in the model. Check for a typo.") + + return ref_model.eval() + + +def truncate_dataset( + dataset: DatasetType, + max_length: int, + map_kwargs: dict[str, Any] | None = None, +) -> DatasetType: + r""" + Truncate sequences in a dataset to a specified `max_length`. + + Args: + dataset ([`~datasets.Dataset`] or [`~datasets.DatasetDict`]): + Dataset to truncate. + max_length (`int`): + Maximum sequence length to truncate to. + map_kwargs (`dict`, *optional*): + Additional keyword arguments to pass to the dataset's map method when truncating examples. + + Returns: + [`~datasets.Dataset`] or [`~datasets.DatasetDict`]: The dataset with truncated sequences. + + Example: + ```python + >>> from datasets import Dataset + + >>> examples = { + ... "input_ids": [[1, 2, 3], [4, 5, 6, 7], [8]], + ... "attention_mask": [[0, 1, 1], [0, 0, 1, 1], [1]], + ... } + >>> dataset = Dataset.from_dict(examples) + >>> truncated_dataset = truncate_dataset(dataset, max_length=2) + >>> truncated_dataset[:] + {'input_ids': [[1, 2], [4, 5], [8]], + 'attention_mask': [[0, 1], [0, 0], [1]]} + ``` + """ + if map_kwargs is None: + map_kwargs = {} + + def truncate(examples): + truncated_columns = [] + for column in examples.columns: + if pyarrow.types.is_list(column.type) or pyarrow.types.is_large_list(column.type): + column = pc.list_slice(column, 0, max_length) + truncated_columns.append(column) + return pa.Table.from_arrays(truncated_columns, names=examples.column_names) + + format = _get_dataset_format(dataset) + dataset = dataset.with_format("arrow") + dataset = dataset.map(truncate, batched=True, **map_kwargs) + dataset = dataset.with_format(**format) + return dataset diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/xpo/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/xpo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2fc35384cd4246001ac14d1bd126430cce00b122 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/xpo/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .xpo_config import XPOConfig +from .xpo_trainer import XPOTrainer + + +__all__ = ["XPOConfig", "XPOTrainer"] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/xpo/xpo_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/xpo/xpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..243545084617bdc8f384289cb76883d22fcfaf54 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/xpo/xpo_config.py @@ -0,0 +1,44 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field + +from ..online_dpo import OnlineDPOConfig + + +@dataclass +class XPOConfig(OnlineDPOConfig): + r""" + Configuration class for the [`experimental.xpo.XPOTrainer`]. + + Subclass of [`experimental.online_dpo.OnlineDPOConfig`] we can use all its arguments and add the following: + + Parameters: + alpha (`float` or `list[float]`, *optional*, defaults to `1e-5`): + Weight of the XPO loss term. If a list of floats is provided then the alpha is selected for each new epoch + and the last alpha is used for the rest of the epochs. + """ + + alpha: list[float] = field( + default_factory=lambda: [1e-5], + metadata={ + "help": "Weight of the XPO loss term. If a list of floats is provided then the alpha is selected for each " + "new epoch and the last alpha is used for the rest of the epochs." + }, + ) + + def __post_init__(self): + super().__post_init__() + if hasattr(self.alpha, "__len__") and len(self.alpha) == 1: + self.alpha = self.alpha[0] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/xpo/xpo_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/xpo/xpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..5edbbc3dc2022802816fba8ea8b52f486745d3a1 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/experimental/xpo/xpo_trainer.py @@ -0,0 +1,506 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import textwrap +from collections.abc import Callable +from typing import Any + +import torch +import torch.nn as nn +import torch.nn.functional as F +from datasets import Dataset, IterableDataset +from transformers import ( + BaseImageProcessor, + FeatureExtractionMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, +) +from transformers.trainer_utils import EvalPrediction +from transformers.training_args import OptimizerNames +from transformers.utils import is_peft_available + +from ...data_utils import maybe_apply_chat_template +from ...models.utils import unwrap_model_for_generation +from ...trainer.utils import selective_log_softmax +from ..online_dpo import OnlineDPOTrainer +from ..utils import empty_cache, get_reward, truncate_right +from .xpo_config import XPOConfig + + +if is_peft_available(): + from peft import PeftConfig, PeftModel + + +class XPOTrainer(OnlineDPOTrainer): + """ + Trainer for Exploratory Preference Optimization (XPO). + + It is implemented as a subclass of [`experimental.online_dpo.OnlineDPOTrainer`]. + + Args: + model ([`~transformers.PreTrainedModel`]): + The model to train, preferably an `AutoModelForCausalLM`. + ref_model ([`~transformers.PreTrainedModel`]): + Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation + and loss. If no reference model is provided, the trainer will create a reference model with the same + architecture as the model to be optimized. + reward_funcs ([`~transformers.PreTrainedModel`]): + The reward model to score completions with, preferably an + [`~transformers.AutoModelForSequenceClassification`]. + args ([`experimental.xpo.XPOConfig`]): + The XPO config arguments to use for training. + data_collator ([`~transformers.DataCollator`]): + The data collator to use for training. If None is specified, the default data collator + ([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the + maximum length of the sequences in the batch, given a dataset of paired sequences. + train_dataset ([`~datasets.Dataset`]): + The dataset to use for training. + eval_dataset ([`~datasets.Dataset`]): + The dataset to use for evaluation. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*): + Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either: + + - A single processing class: Used when `reward_funcs` contains only one reward function. + - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`. + + If set to `None`, the tokenizer for each model-based reward function is automatically loaded using + [`~transformers.AutoTokenizer.from_pretrained`]. + peft_config ([`~peft.PeftConfig`], *optional*): + The peft config to use for training. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to + metric values. + callbacks (`list[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + """ + + _tag_names = ["trl", "xpo"] + _name = "XPO" + _paper = { + "title": "Exploratory Preference Optimization: Harnessing Implicit Q*-Approximation for Sample-Efficient RLHF", + "id": "2405.21046", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{jung2024binary, + title = {{Exploratory Preference Optimization: Harnessing Implicit Q*-Approximation for Sample-Efficient RLHF}}, + author = {Tengyang Xie and Dylan J. Foster and Akshay Krishnamurthy and Corby Rosset and Ahmed Awadallah and Alexander Rakhlin}, + year = 2024, + eprint = {arXiv:2405.21046} + }"""), + } + + def __init__( + self, + model: PreTrainedModel | nn.Module = None, + ref_model: PreTrainedModel | nn.Module = None, + reward_funcs: nn.Module | None = None, + args: XPOConfig | None = None, + data_collator: Callable | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + processing_class: PreTrainedTokenizerBase + | BaseImageProcessor + | FeatureExtractionMixin + | ProcessorMixin + | None = None, + reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None, + peft_config: "PeftConfig | None" = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + ) -> None: + super().__init__( + model=model, + ref_model=ref_model, + reward_funcs=reward_funcs, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + reward_processing_classes=reward_processing_classes, + peft_config=peft_config, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + self._alpha = self.args.alpha + + # Overwrite the stats dictionary to include XPO specific statistics + self.stats = { + # Remove "non_score_reward", "rlhf_reward", "scores" + # Add "loss/dpo", "loss/xpo" + "loss/dpo": [], + "loss/xpo": [], + "objective/kl": [], + "objective/entropy": [], + "rewards/chosen": [], + "rewards/rejected": [], + "rewards/accuracies": [], + "rewards/margins": [], + "logps/chosen": [], + "logps/rejected": [], + # Replace "contain_eos_token" by "model_contain_eos_token" and "ref_contain_eos_token" + "val/model_contain_eos_token": [], + "val/ref_contain_eos_token": [], + "objective/model_scores": [], + "objective/ref_scores": [], + "objective/scores_margin": [], + "alpha": [], + "beta": [], + } + if len(self.reward_funcs) != 1: + raise ValueError("XPOTrainer only supports one reward function/model.") + self.reward_funcs = self.reward_funcs[0] + + @property + def alpha(self): + if isinstance(self._alpha, list): + epoch = self.state.epoch + return self._alpha[epoch] if epoch < len(self._alpha) else self._alpha[-1] + else: + return self._alpha + + def _generate_completions(self, prompts, model): + with ( + unwrap_model_for_generation( + model, + self.accelerator, + generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762 + ) as unwrapped_policy_model_for_gen, + ): + model_output = unwrapped_policy_model_for_gen.generate( + input_ids=prompts["input_ids"], + attention_mask=prompts["attention_mask"], + generation_config=self.generation_config, + ) + + actual_model_for_ref_generation: torch.nn.Module + if self.ref_model is None: + unwrapped_main_model_for_ref_logic = self.accelerator.unwrap_model(model) + + if is_peft_available() and isinstance(unwrapped_main_model_for_ref_logic, PeftModel): + actual_model_for_ref_generation = unwrapped_main_model_for_ref_logic.get_base_model() + else: + actual_model_for_ref_generation = unwrapped_main_model_for_ref_logic + else: + actual_model_for_ref_generation = self.accelerator.unwrap_model(self.ref_model) + + with ( + unwrap_model_for_generation( + actual_model_for_ref_generation, + self.accelerator, + generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762 + ) as final_ref_model_for_gen, + ): + ref_output = final_ref_model_for_gen.generate( + input_ids=prompts["input_ids"], + attention_mask=prompts["attention_mask"], + generation_config=self.generation_config, + ) + + return model_output, ref_output + + def _process_completions(self, model_output, ref_output, prompts): + context_length = prompts["input_ids"].shape[1] + + # Process model completions + model_completion_ids = model_output[:, context_length:] + model_completion_ids, model_completion_mask = truncate_right( + model_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id + ) + model_data = { + "input_ids": torch.cat((prompts["input_ids"], model_completion_ids), dim=1), + "attention_mask": torch.cat((prompts["attention_mask"], model_completion_mask), dim=1), + "raw": prompts["raw"], + } + + # Process reference model completions + ref_completion_ids = ref_output[:, context_length:] + ref_completion_ids, ref_completion_mask = truncate_right( + ref_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id + ) + ref_data = { + "input_ids": torch.cat((prompts["input_ids"], ref_completion_ids), dim=1), + "attention_mask": torch.cat((prompts["attention_mask"], ref_completion_mask), dim=1), + "raw": prompts["raw"], + } + + return model_data, ref_data + + def _compute_rewards(self, model_data, ref_data, context_length): + with torch.no_grad(): + _, model_scores, _ = get_reward( + self.reward_funcs, model_data["input_ids"], self.processing_class.pad_token_id, context_length + ) + _, ref_scores, _ = get_reward( + self.reward_funcs, ref_data["input_ids"], self.processing_class.pad_token_id, context_length + ) + + # Apply EOS penalty if needed + if self.args.missing_eos_penalty is not None: + model_contain_eos = torch.any(model_data["input_ids"] == self.processing_class.eos_token_id, dim=-1) + ref_contain_eos = torch.any(ref_data["input_ids"] == self.processing_class.eos_token_id, dim=-1) + model_scores[~model_contain_eos] -= self.args.missing_eos_penalty + ref_scores[~ref_contain_eos] -= self.args.missing_eos_penalty + + return model_scores, ref_scores + + def _compute_logprobs(self, model, model_data, ref_data, context_length): + def compute_logprobs_for_data(m, data): + output = m(data["input_ids"], attention_mask=data["attention_mask"]) + logits = output.logits[:, context_length - 1 : -1] + token_logprobs = selective_log_softmax(logits, data["input_ids"][:, context_length:]) + return token_logprobs + + # Compute logprobs for model completions + model_logprobs_model_data = compute_logprobs_for_data(model, model_data) + # Compute logprobs for model on reference completions (for XPO loss) + model_logprobs_ref_data = compute_logprobs_for_data(model, ref_data) + + # Compute logprobs for reference model completions + with torch.no_grad(): + if self.ref_model is None: + with model.disable_adapter(): + ref_logprobs_model_data = compute_logprobs_for_data(model, model_data) + ref_logprobs_ref_data = compute_logprobs_for_data(model, ref_data) + else: + ref_logprobs_model_data = compute_logprobs_for_data(self.ref_model, model_data) + ref_logprobs_ref_data = compute_logprobs_for_data(self.ref_model, ref_data) + + # Mask padding tokens + model_padding_mask = model_data["attention_mask"][:, context_length:] == 0 + ref_padding_mask = ref_data["attention_mask"][:, context_length:] == 0 + model_logprobs_model_data = model_logprobs_model_data.masked_fill(model_padding_mask, 0.0) + model_logprobs_ref_data = model_logprobs_ref_data.masked_fill(ref_padding_mask, 0.0) + ref_logprobs_ref_data = ref_logprobs_ref_data.masked_fill(ref_padding_mask, 0.0) + ref_logprobs_model_data = ref_logprobs_model_data.masked_fill(model_padding_mask, 0.0) + + return model_logprobs_model_data, model_logprobs_ref_data, ref_logprobs_ref_data, ref_logprobs_model_data + + def _compute_losses( + self, + model_logprobs_model_data, + model_logprobs_ref_data, + ref_logprobs_ref_data, + ref_logprobs_model_data, + chosen_mask, + ): + # Compute log probs + model_logprobs_model_data_sum = model_logprobs_model_data.sum(1) + model_logprobs_ref_data_sum = model_logprobs_ref_data.sum(1) + ref_logprobs_ref_data_sum = ref_logprobs_ref_data.sum(1) + ref_logprobs_model_data_sum = ref_logprobs_model_data.sum(1) + + chosen_model_logprobs = torch.where(chosen_mask, model_logprobs_model_data_sum, model_logprobs_ref_data_sum) + chosen_ref_logprobs = torch.where(chosen_mask, ref_logprobs_model_data_sum, ref_logprobs_ref_data_sum) + chosen_log_ratios = chosen_model_logprobs - chosen_ref_logprobs + + rejected_model_logprobs = torch.where(~chosen_mask, model_logprobs_model_data_sum, model_logprobs_ref_data_sum) + rejected_ref_logprobs = torch.where(~chosen_mask, ref_logprobs_model_data_sum, ref_logprobs_ref_data_sum) + rejected_log_ratios = rejected_model_logprobs - rejected_ref_logprobs + + # Compute logits as the difference between chosen and rejected log ratios + logits = chosen_log_ratios - rejected_log_ratios + + if self.args.loss_type == "sigmoid": + dpo_losses = -F.logsigmoid(self.beta * logits) + elif self.args.loss_type == "ipo": + dpo_losses = (logits - 1 / (2 * self.beta)) ** 2 + else: + raise NotImplementedError(f"invalid loss type {self.args.loss_type}") + + # Compute XPO specific loss + xpo_losses = self.alpha * model_logprobs_ref_data_sum + + # Total loss + loss = (dpo_losses + xpo_losses).mean() + + return loss, dpo_losses, xpo_losses + + def _log_statistics( + self, + model_data, + ref_data, + model_logprobs_model_data, + model_logprobs_ref_data, + ref_logprobs_ref_data, + ref_logprobs_model_data, + chosen_mask, + dpo_losses, + xpo_losses, + context_length, + model_scores, + ref_scores, + ): + # Helper function to gather and compute mean + def gather_mean(tensor): + return self.accelerator.gather_for_metrics(tensor).mean().item() + + # Log losses + self.stats["loss/dpo"].append(gather_mean(dpo_losses)) + self.stats["loss/xpo"].append(gather_mean(xpo_losses)) + + # Log scores + self.stats["objective/model_scores"].append(gather_mean(model_scores)) + self.stats["objective/ref_scores"].append(gather_mean(ref_scores)) + self.stats["objective/scores_margin"].append(gather_mean(model_scores - ref_scores)) + + # Log logprobs + model_logprobs_model_data_sum = model_logprobs_model_data.sum(1) + model_logprobs_ref_data_sum = model_logprobs_ref_data.sum(1) + ref_logprobs_ref_data_sum = ref_logprobs_ref_data.sum(1) + ref_logprobs_model_data_sum = ref_logprobs_model_data.sum(1) + + chosen_model_logprobs = torch.where(chosen_mask, model_logprobs_model_data_sum, model_logprobs_ref_data_sum) + chosen_ref_logprobs = torch.where(chosen_mask, ref_logprobs_model_data_sum, ref_logprobs_ref_data_sum) + chosen_log_ratios = chosen_model_logprobs - chosen_ref_logprobs + + rejected_model_logprobs = torch.where(~chosen_mask, model_logprobs_model_data_sum, model_logprobs_ref_data_sum) + rejected_ref_logprobs = torch.where(~chosen_mask, ref_logprobs_model_data_sum, ref_logprobs_ref_data_sum) + rejected_log_ratios = rejected_model_logprobs - rejected_ref_logprobs + + self.stats["logps/chosen"].append(gather_mean(chosen_model_logprobs.mean() + chosen_ref_logprobs.mean())) + self.stats["logps/rejected"].append(gather_mean(rejected_model_logprobs.mean() + rejected_ref_logprobs.mean())) + + # Log rewards + # Compute various statistics + chosen_rewards = chosen_log_ratios * self.beta + rejected_rewards = rejected_log_ratios * self.beta + self.stats["rewards/chosen"].append(gather_mean(chosen_rewards.mean())) + self.stats["rewards/rejected"].append(gather_mean(rejected_rewards.mean())) + + # Calculate KL divergence for model and ref data + kl_model_data = model_logprobs_model_data - ref_logprobs_model_data + kl_ref_data = model_logprobs_ref_data - ref_logprobs_ref_data + mean_kl = (kl_model_data.sum(1) + kl_ref_data.sum(1)).mean() / 2 + self.stats["objective/kl"].append(gather_mean(mean_kl)) + + # Calculate entropy for model and ref data + entropy_model_data = -model_logprobs_model_data.sum(1) + entropy_ref_data = -model_logprobs_ref_data.sum(1) + mean_entropy = (entropy_model_data.mean() + entropy_ref_data.mean()) / 2 + self.stats["objective/entropy"].append(gather_mean(mean_entropy)) + + # Calculate margins + margin = chosen_rewards - rejected_rewards + self.stats["rewards/margins"].append(gather_mean(margin.mean())) + + # Calculate accuracy + accuracy = (margin > 0).float() + self.stats["rewards/accuracies"].append(gather_mean(accuracy.mean())) + + # Log EOS token statistics + model_eos = (model_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1) + ref_eos = (ref_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1) + self.stats["val/model_contain_eos_token"].append(gather_mean(model_eos.float())) + self.stats["val/ref_contain_eos_token"].append(gather_mean(ref_eos.float())) + + # Log alpha and beta + self.stats["alpha"].append(self.alpha) + self.stats["beta"].append(self.beta) + + def training_step( + self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None + ) -> torch.Tensor: + model.train() + + # Apply chat template and tokenize the input + batch_size = len(next(iter(inputs.values()))) + prompts = inputs["prompt"] + inputs = [{k: v[i] for k, v in inputs.items()} for i in range(batch_size)] + inputs = [maybe_apply_chat_template(x, self.processing_class) for x in inputs] + inputs = [self.tokenize_row(x, self.model.config.is_encoder_decoder, self.processing_class) for x in inputs] + inputs = self.data_collator(inputs) + + # need the prompt_ only + inputs = self._prepare_inputs(inputs) + context_length = inputs["prompt_input_ids"].shape[1] + prompts = { + "input_ids": inputs["prompt_input_ids"], + "attention_mask": inputs["prompt_attention_mask"], + "raw": prompts, + } + del inputs + + # Sample completions from both the model and the reference model + model_output, ref_output = self._generate_completions(prompts, model) + + # Process model completions + model_data, ref_data = self._process_completions(model_output, ref_output, prompts) + + # Compute rewards + model_scores, ref_scores = self._compute_rewards(model_data, ref_data, context_length) + chosen_mask = model_scores >= ref_scores + + # Compute logprobs + model_logprobs_model_data, model_logprobs_ref_data, ref_logprobs_ref_data, ref_logprobs_model_data = ( + self._compute_logprobs(model, model_data, ref_data, context_length) + ) + + # Compute loss + loss, dpo_losses, xpo_losses = self._compute_losses( + model_logprobs_model_data, + model_logprobs_ref_data, + ref_logprobs_ref_data, + ref_logprobs_model_data, + chosen_mask, + ) + + # Log everything + self._log_statistics( + model_data, + ref_data, + model_logprobs_model_data.detach(), + model_logprobs_ref_data.detach(), + ref_logprobs_ref_data, + ref_logprobs_model_data, + chosen_mask, + dpo_losses.detach(), + xpo_losses.detach(), + context_length, + model_scores, + ref_scores, + ) + + if ( + self.args.torch_empty_cache_steps is not None + and self.state.global_step % self.args.torch_empty_cache_steps == 0 + ): + empty_cache() + + kwargs = {} + # For LOMO optimizers you need to explicitly use the learning rate + if self.args.optim in [OptimizerNames.LOMO, OptimizerNames.ADALOMO]: + kwargs["learning_rate"] = self._get_learning_rate() + + if self.args.n_gpu > 1: + loss = loss.mean() # mean() to average on multi-gpu parallel training + + self.accelerator.backward(loss, **kwargs) + + return loss.detach() / self.args.gradient_accumulation_steps diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/extras/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/extras/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d2777dd0eb21a0ea67dce8775337a27ea8499da2 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/extras/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/extras/dataset_formatting.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/extras/dataset_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..6dd89493a33263bda1506f67f661947ac69a3690 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/extras/dataset_formatting.py @@ -0,0 +1,32 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import datasets +from datasets import Value +from packaging.version import Version + + +if Version(datasets.__version__) >= Version("4.0.0"): + from datasets import List + + FORMAT_MAPPING = { + "chatml": List({"content": Value(dtype="string", id=None), "role": Value(dtype="string", id=None)}), + "instruction": {"completion": Value(dtype="string", id=None), "prompt": Value(dtype="string", id=None)}, + } +else: + FORMAT_MAPPING = { + "chatml": [{"content": Value(dtype="string", id=None), "role": Value(dtype="string", id=None)}], + "instruction": {"completion": Value(dtype="string", id=None), "prompt": Value(dtype="string", id=None)}, + } diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/extras/profiling.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/extras/profiling.py new file mode 100644 index 0000000000000000000000000000000000000000..8c8adab026bf78a105a0ff65afb36fa81be91ecc --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/extras/profiling.py @@ -0,0 +1,224 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import functools +import time +from collections.abc import Callable + +from transformers import Trainer +from transformers.integrations import is_mlflow_available, is_trackio_available, is_wandb_available + + +if is_wandb_available(): + import wandb + +if is_mlflow_available(): + import mlflow + +if is_trackio_available(): + import trackio + + +class ProfilingContext: + """ + Context manager for profiling code blocks with configurable logging. + + This class handles timing of code execution and logging metrics to various backends (Weights & Biases, MLflow, + Trackio) without being coupled to the Trainer class. + + Args: + name (`str`): + Name of the profiling context. Used in the metric name. + report_to (`list` of `str`): + List of integrations to report metrics to (e.g., ["wandb", "mlflow", "trackio"]). + is_main_process (`bool`, *optional*, defaults to `True`): + Whether this is the main process in distributed training. Metrics are only logged from the main process. + step (`int` or `None`, *optional*): + Training step to associate with the logged metrics. + metric_prefix (`str`, *optional*, defaults to `"profiling/Time taken"`): + Prefix for the metric name in logs. + + Example: + ```python + # Direct usage + from trl.extras.profiling import ProfilingContext + + with ProfilingContext( + name="MyClass.expensive_operation", + report_to=["wandb"], + is_main_process=True, + step=100, + ): + # Code to profile + result = expensive_computation() + + # With Trainer (backwards compatible via profiling_context function) + from transformers import Trainer + from trl.extras.profiling import profiling_context + + + class MyTrainer(Trainer): + def some_method(self): + with profiling_context(self, "matrix_multiplication"): + result = matrix_multiply() + ``` + """ + + def __init__( + self, + name: str, + report_to: list[str], + is_main_process: bool = True, + step: int | None = None, + metric_prefix: str = "profiling/Time taken", + ): + self.name = name + self.report_to = report_to + self.is_main_process = is_main_process + self.step = step + self.metric_prefix = metric_prefix + self._start_time = None + + def __enter__(self): + """Start timing when entering the context.""" + self._start_time = time.perf_counter() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + """Stop timing and log metrics when exiting the context.""" + if self._start_time is not None: + duration = time.perf_counter() - self._start_time + self._log_metrics(duration) + return False + + def _log_metrics(self, duration: float) -> None: + """ + Log profiling metrics to configured backends. + + Args: + duration (`float`): + Execution time in seconds. + """ + if not self.is_main_process: + return + + metric_name = f"{self.metric_prefix}: {self.name}" + metrics = {metric_name: duration} + + # Log to Weights & Biases if configured + if "wandb" in self.report_to and is_wandb_available() and wandb.run is not None: + wandb.log(metrics) + + # Log to MLflow if configured + if "mlflow" in self.report_to and is_mlflow_available() and mlflow.active_run() is not None: + mlflow.log_metrics(metrics, step=self.step) + + # Log to Trackio if configured + if "trackio" in self.report_to and is_trackio_available(): + trackio.log(metrics, step=self.step) + + +def profiling_context(trainer: Trainer, name: str) -> ProfilingContext: + """ + Factory function to create a ProfilingContext from a Trainer instance. + + This function maintains backwards compatibility with existing code while using the decoupled ProfilingContext class + internally. + + Args: + trainer (`~transformers.Trainer`): + Trainer object containing configuration for logging. + name (`str`): + Name of the block to be profiled. Will be prefixed with the trainer class name. + + Returns: + `ProfilingContext`: A configured profiling context manager. + + Example: + ```python + >>> from transformers import Trainer + >>> from trl.extras.profiling import profiling_context + + + >>> class MyTrainer(Trainer): + ... def some_method(self): + ... A = np.random.rand(1000, 1000) + ... B = np.random.rand(1000, 1000) + ... with profiling_context(self, "matrix_multiplication"): + ... # Code to profile: simulate a computationally expensive operation + ... result = A @ B # Matrix multiplication + ``` + """ + context_name = f"{trainer.__class__.__name__}.{name}" + step = trainer.state.global_step + + return ProfilingContext( + name=context_name, + report_to=trainer.args.report_to, + is_main_process=trainer.accelerator.is_main_process, + step=step, + ) + + +def profiling_decorator(func: Callable) -> Callable: + """ + Decorator to profile a function and log execution time using [`extras.profiling.profiling_context`]. + + This decorator works with methods that have access to a trainer instance (typically as `self`). For non-Trainer + objects that have an `accelerator` attribute, it will use that for logging configuration. + + Args: + func (`Callable`): + Function to be profiled. + + Returns: + `Callable`: Wrapped function that profiles execution time. + + Example: + ```python + >>> from transformers import Trainer + >>> from trl.extras.profiling import profiling_decorator + + + >>> class MyTrainer(Trainer): + ... @profiling_decorator + ... def some_method(self): + ... A = np.random.rand(1000, 1000) + ... B = np.random.rand(1000, 1000) + ... # Code to profile: simulate a computationally expensive operation + ... result = A @ B + ``` + """ + + @functools.wraps(func) + def wrapper(self, *args, **kwargs): + # Check if self is a Trainer-like object with required attributes + if hasattr(self, "state") and hasattr(self, "args"): + with profiling_context(self, func.__name__): + return func(self, *args, **kwargs) + # For non-Trainer objects (e.g., VLLMGeneration), use ProfilingContext directly + elif hasattr(self, "accelerator"): + context_name = f"{self.__class__.__name__}.{func.__name__}" + with ProfilingContext( + name=context_name, + report_to=[], # No reporting for non-Trainer objects without args + is_main_process=self.accelerator.is_main_process, + step=None, + ): + return func(self, *args, **kwargs) + else: + # No profiling available, just run the function + return func(self, *args, **kwargs) + + return wrapper diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/generation/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/generation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..22e7cf6d88463c5b6774725e2b66ee1496bddd22 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/generation/__init__.py @@ -0,0 +1,25 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Generation backends for TRL trainers.""" + +from ..import_utils import is_vllm_available + + +__all__ = [] + +if is_vllm_available(): + from .vllm_generation import VLLMGeneration + + __all__.append("VLLMGeneration") diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/generation/vllm_client.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/generation/vllm_client.py new file mode 100644 index 0000000000000000000000000000000000000000..73f08f451dab972412de3118f8d545b8d01a6c04 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/generation/vllm_client.py @@ -0,0 +1,764 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import atexit +import base64 +import copy +import logging +import socket +import time +from io import BytesIO +from urllib.parse import urlparse + +import torch +import torch.distributed.distributed_c10d as c10d +from requests.adapters import HTTPAdapter +from torch import nn +from transformers import is_torch_xpu_available +from transformers.utils import get_json_schema +from urllib3.util.retry import Retry + +from ..import_utils import is_requests_available, is_vllm_ascend_available, is_vllm_available + + +if is_requests_available(): + import requests + from requests import ConnectionError + + +if is_vllm_available(): + from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator + from vllm.distributed.utils import StatelessProcessGroup + + if is_vllm_ascend_available(): + from vllm_ascend.distributed.device_communicators.pyhccl import PyHcclCommunicator as PyNcclCommunicator + + +logger = logging.getLogger(__name__) + + +def pil_to_base64(image): + buffer = BytesIO() + image.save(buffer, format="PNG") + img_bytes = buffer.getvalue() + return base64.b64encode(img_bytes).decode("utf-8") + + +class VLLMClient: + """ + A client class to interact with a vLLM server. + + This class provides methods to generate completions, initialize and manage weight update groups, and update model + weights in a distributed setting. Before using it, start the vLLM server with `trl vllm-serve`. + + Args: + base_url (`str`, *optional*): + Base URL for the vLLM server (e.g., `"http://localhost:8000"`). If provided, `host` and `server_port` are + ignored. + host (`str`, *optional*, defaults to `"0.0.0.0"`): + IP address of the vLLM server. Ignored if `base_url` is provided. + server_port (`int`, *optional*, defaults to `8000`): + Port number of the vLLM server. Ignored if `base_url` is provided. + group_port (`int`, *optional*, defaults to `51216`): + Port number for the weight update group. + connection_timeout (`float`, *optional*, defaults to `0.0`): + Total timeout duration in seconds to wait for the server to be up. If the server is not up after the + timeout, a `ConnectionError` is raised. + + Examples: + Run the vLLM server with the model `Qwen/Qwen2.5-7B`: + + ``` + $ trl vllm-serve --model Qwen/Qwen2.5-7B + ... + INFO: Application startup complete. + INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) + ``` + + Use the client to generate completions and update model weights: + + ```python + >>> from trl.generation.vllm_client import VLLMClient + + >>> client = VLLMClient() + >>> client.generate(["Hello, AI!", "Tell me a joke"]) + {'prompt_ids': [[9707, 11, 15235, 0], + [40451, 752, 264, 21646]], + 'completion_ids': [[2980, 498, 1492, 752, 448, 264, 13027, 8645, 30, 358, 2776, 4460, 311, 3270, 264, 2025], + [911, 98072, 2142, 624, 45, 51426, 2142, 374, 279, 16396, 429, 4302, 702, 36988, 7290, 476]], + 'logprobs': [[[-1.6612], [-0.0081], [-1.5189], [-0.0123], [-1.2045], [-0.6227], [-2.9791], [-2.8387], [-0.1267], [-0.0366], [-2.6528], [-0.3197], [-0.0001], [-1.8174], [-0.0251], [-1.473]], + [[-0.018], [-10.7331], [-0.1605], [-0.891], [-3.7945], [-0.0127], [-0.3073], [-1.1648], [-1.8025], [-0.409], [-0.0256], [-1.6127], [-2.2935], [-4.1785], [-0.6531], [-0.2629]]], + 'logprob_token_ids': [[[2980], [498], [1492], [752], [448], [264], [13027], [8645], [30], [358], [2776], [4460], [311], [3270], [264], [2025]], + [[911], [98072], [2142], [624], [45], [51426], [2142], [374], [279], [16396], [429], [4302], [702], [36988], [7290], [476]]]} + + >>> from transformers import AutoModelForCausalLM + + >>> model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-7B", device_map="cuda") + >>> client.init_communicator(device="cuda") + >>> client.update_model_params(model) + ``` + + There are several ways to initialize the client: + + ```python + >>> VLLMClient(base_url="http://localhost:8000") + >>> VLLMClient(base_url="http://192.168.1.100:8000") + >>> VLLMClient(host="localhost", server_port=8000) + >>> VLLMClient(host="192.168.1.100", server_port=8000) + ``` + """ + + def __init__( + self, + base_url: str | None = None, + host: str = "0.0.0.0", + server_port: int = 8000, + group_port: int = 51216, + connection_timeout: float = 0.0, + ): + if not is_requests_available(): + raise ImportError("requests is not installed. Please install it with `pip install requests`.") + if not is_vllm_available(): + raise ImportError("vLLM is not installed. Please install it with `pip install trl[vllm]`.") + + self.session = requests.Session() + + # Configure retries for HTTP requests made through this session. + # This is not strictly required for correctness, but it helps make training more robust to rare, transient + # failures (network hiccups, temporary 5xx errors, overloaded servers). Without this, such failures could cause + # an otherwise healthy training run to fail. + retry_strategy = Retry( + total=5, # global cap on the total number of retries across all failure types + connect=5, # retry connection-level failures (DNS issues, refused connections, etc) + read=5, # retry failures while reading the response after the connection was successfully established + status=3, # retry a limited number of times when we receive certain HTTP error responses from the server + status_forcelist=[500, 502, 503], # only retry on server-side errors that are usually temporary + backoff_factor=2, # exponential backoff between retries (2s, 4s, 8s, ...) + allowed_methods=["POST", "GET"], # allow POST as well, even though we're not sure it's safe here + ) + + adapter = HTTPAdapter(max_retries=retry_strategy) + self.session.mount("http://", adapter) + self.session.mount("https://", adapter) + + if base_url is not None: + # Parse the base_url to extract host and port + parsed_url = urlparse(base_url) + self.host = socket.gethostbyname(parsed_url.hostname) + scheme = parsed_url.scheme or "http" + self.base_url = f"{scheme}://{parsed_url.netloc}{parsed_url.path}" + else: + self.host = host + self.server_port = server_port + self.base_url = f"http://{self.host}:{self.server_port}" + self.group_port = group_port + self.check_server(connection_timeout) # check server and fail after timeout + + def check_server(self, total_timeout: float = 0.0, retry_interval: float = 2.0): + """ + Check server availability with retries on failure, within a total timeout duration. If the server is not up + after the total timeout duration, raise a `ConnectionError`. + + Args: + retry_interval (`float`, *optional*, defaults to `2.0`): + Interval in seconds between retries. + total_timeout (`float`, *optional*, defaults to `0.0`): + Total timeout duration in seconds. + """ + url = f"{self.base_url}/health/" + start_time = time.time() # Record the start time + + while True: + try: + response = requests.get(url) + except requests.exceptions.RequestException as exc: + # Check if the total timeout duration has passed + elapsed_time = time.time() - start_time + if elapsed_time >= total_timeout: + raise ConnectionError( + f"The vLLM server can't be reached at {self.base_url} after {total_timeout} seconds. Make " + "sure the server is running by running `trl vllm-serve`." + ) from exc + else: + if response.status_code == 200: + if "X-Forwarded-For" in response.headers: + self.host = response.headers["X-Forwarded-For"] + logger.info("Server is up!") + return None + + # Retry logic: wait before trying again + logger.info(f"Server is not up yet. Retrying in {retry_interval} seconds...") + time.sleep(retry_interval) + + def generate( + self, + prompts: list[str] | list[list[int]], + images: list | None = None, + n: int = 1, + repetition_penalty: float = 1.0, + temperature: float = 1.0, + top_p: float = 1.0, + top_k: int = 0, + min_p: float = 0.0, + max_tokens: int = 16, + logprobs: int | None = 0, + structured_outputs_regex: str | None = None, + generation_kwargs: dict | None = None, + ) -> dict[str, list[list[int]]]: + """ + Generates model completions for the provided prompts. + + Args: + prompts (`list[str]` or `list[list[int]]`): + List of text prompts or list of token ID lists for which the model will generate completions. + images (`list[list[PIL.Image] | None]`, *optional*): + List of image lists for VLM support. Each element is a list of PIL images for the corresponding prompt, + or `None` if no images for that prompt. + n (`int`, *optional*, defaults to `1`): + Number of completions to generate for each prompt. + repetition_penalty (`float`, *optional*, defaults to `1.0`): + Parameter for repetition penalty. 1.0 means no penalty. + temperature (`float`, *optional*, defaults to `1.0`): + Temperature parameter for sampling. Higher values increase diversity. + top_p (`float`, *optional*, defaults to `1.0`): + Top-p sampling parameter.`1.0` means no truncation. + top_k (`int`, *optional*, defaults to `0`): + Top-k sampling parameter. `0` means no truncation. + min_p (`float`, *optional*, defaults to `0.0`): + Minimum probability for sampling. + max_tokens (`int`, *optional*, defaults to `16`): + Maximum number of tokens to generate for each prompt. + logprobs (`int` or `None`, *optional*, defaults to `0`): + Number of top logprobs to return per token. When 0, only the sampled token's logprob is returned. When + N>0, returns up to N+1 logprobs sorted by descending probability, because vLLM always includes the + sampled token's logprob (which may fall outside the top-N). + structured_outputs_regex (`str`, *optional*): + Regular expression to guide the decoding process. + generation_kwargs (`dict`, *optional*): + Additional generation parameters to pass to the vLLM `SamplingParams`. This can include parameters like + `seed`, `frequency_penalty`, etc. If it contains keys that conflict with the other parameters, they + will override them. + + Returns: + `dict` with keys: + - `prompt_ids` (`list[list[int]]`): + List of lists of token IDs representing the tokenized input prompts. + - `completion_ids` (`list[list[int]]`): + List of lists of token IDs representing the model-generated completions for each prompt. + - `logprobs` (`list[list[list[float]]]`): + Per-token logprobs of shape (num_sequences, seq_len, num_logprobs), sorted by descending + probability. + - `logprob_token_ids` (`list[list[list[int]]]`): + Token IDs corresponding to each logprob, same shape as `logprobs`. + """ + url = f"{self.base_url}/generate/" + + # Convert PIL images to base64 strings. Each element is a list of images for the corresponding prompt, + # or None if no images for that prompt. + if images: + images = [ + [pil_to_base64(img) for img in img_list] if img_list is not None else None for img_list in images + ] + + response = self.session.post( + url, + json={ + "prompts": prompts, + "images": images, + "n": n, + "repetition_penalty": repetition_penalty, + "temperature": temperature, + "top_p": top_p, + "top_k": top_k, + "min_p": min_p, + "max_tokens": max_tokens, + "logprobs": logprobs, + "structured_outputs_regex": structured_outputs_regex, + "generation_kwargs": generation_kwargs or {}, + }, + ) + if response.status_code == 200: + json_response = response.json() + return { + "prompt_ids": json_response["prompt_ids"], + "completion_ids": json_response["completion_ids"], + "logprobs": json_response["logprobs"], + "logprob_token_ids": json_response["logprob_token_ids"], + } + else: + raise Exception(f"Request failed: {response.status_code}, {response.text}") + + def chat( + self, + messages: list[list[dict]], + n: int = 1, + repetition_penalty: float = 1.0, + temperature: float = 1.0, + top_p: float = 1.0, + top_k: int = 0, + min_p: float = 0.0, + max_tokens: int = 16, + logprobs: int | None = 0, + structured_outputs_regex: str | None = None, + generation_kwargs: dict | None = None, + chat_template_kwargs: dict | None = None, + tools: list | None = None, + chat_template: str | None = None, + ) -> dict[str, list[list[int]]]: + """ + Generates model completions for the provided chat messages. + + Args: + messages (`list[list[dict]]`): + List of message lists for which the model will generate completions. Each message is a dictionary with + keys like "role" and "content". + n (`int`, *optional*, defaults to `1`): + Number of completions to generate for each message list. + repetition_penalty (`float`, *optional*, defaults to `1.0`): + Parameter for repetition penalty. 1.0 means no penalty. + temperature (`float`, *optional*, defaults to `1.0`): + Temperature parameter for sampling. Higher values increase diversity. + top_p (`float`, *optional*, defaults to `1.0`): + Top-p sampling parameter.`1.0` means no truncation. + top_k (`int`, *optional*, defaults to `0`): + Top-k sampling parameter. `0` means no truncation. + min_p (`float`, *optional*, defaults to `0.0`): + Minimum probability for sampling. + max_tokens (`int`, *optional*, defaults to `16`): + Maximum number of tokens to generate for each message list. + logprobs (`int` or `None`, *optional*, defaults to `0`): + Number of top logprobs to return per token. When 0, only the sampled token's logprob is returned. When + N>0, returns up to N+1 logprobs sorted by descending probability, because vLLM always includes the + sampled token's logprob (which may fall outside the top-N). + structured_outputs_regex (`str`, *optional*): + Regular expression to guide the decoding process. + generation_kwargs (`dict`, *optional*): + Additional generation parameters to pass to the vLLM `SamplingParams`. This can include parameters like + `seed`, `frequency_penalty`, etc. If it contains keys that conflict with the other parameters, they + will override them. + chat_template_kwargs (`dict`, *optional*): + Additional keyword arguments to customize the chat template used by the model. + tools (`list[dict | Callable]`, *optional*): + List of tool functions available for tool calling during chat generation. + chat_template (`str`, *optional*): + Template to use for structuring the chat. If not provided, the model's default chat template will be + used. + + Returns: + `dict` with keys: + - `prompt_ids` (`list[list[int]]`): + List of lists of token IDs representing the tokenized input messages. + - `completion_ids` (`list[list[int]]`): + List of lists of token IDs representing the model-generated completions for each message list. + - `logprobs` (`list[list[list[float]]]`): + Per-token logprobs of shape (num_sequences, seq_len, num_logprobs), sorted by descending + probability. + - `logprob_token_ids` (`list[list[list[int]]]`): + Token IDs corresponding to each logprob, same shape as `logprobs`. + """ + if chat_template is not None: + raise NotImplementedError("Custom chat templates are not yet implemented in VLLMClient.chat().") + + url = f"{self.base_url}/chat/" + + # Convert PIL images to base64 strings + messages = copy.deepcopy(messages) # avoid modifying the original messages + for message_list in messages: + for message in message_list: + if isinstance(message["content"], list): + for part in message["content"]: + if part["type"] == "image_pil": + part["image_pil"] = pil_to_base64(part["image_pil"]) + + if isinstance(tools, list) and len(tools) > 0: + tools = [get_json_schema(tool) if callable(tool) else tool for tool in tools] + + response = self.session.post( + url, + json={ + "messages": messages, + "n": n, + "repetition_penalty": repetition_penalty, + "temperature": temperature, + "top_p": top_p, + "top_k": top_k, + "min_p": min_p, + "max_tokens": max_tokens, + "logprobs": logprobs, + "structured_outputs_regex": structured_outputs_regex, + "generation_kwargs": generation_kwargs or {}, + "chat_template_kwargs": chat_template_kwargs or {}, + "tools": tools, + }, + ) + if response.status_code == 200: + json_response = response.json() + return { + "prompt_ids": json_response["prompt_ids"], + "completion_ids": json_response["completion_ids"], + "logprobs": json_response["logprobs"], + "logprob_token_ids": json_response["logprob_token_ids"], + } + else: + raise Exception(f"Request failed: {response.status_code}, {response.text}") + + def init_communicator(self, device: torch.device | str | int = 0): + """ + Initializes the weight update group in a distributed setup for model synchronization. + + Args: + device (`torch.device`, `str`, or `int`, *optional*, defaults to `0`): + Device of trainer main process. It's the device that will be used for the weights synchronization. Can + be a `torch.device` object, a string like `'cuda:0'`, or an integer device index. + """ + # Get the world size from the server + url = f"{self.base_url}/get_world_size/" + response = requests.get(url) + if response.status_code == 200: + vllm_world_size = response.json()["world_size"] + else: + raise Exception(f"Request failed: {response.status_code}, {response.text}") + + world_size = vllm_world_size + 1 # add the client to the world + self.rank = vllm_world_size # the client's rank is the last process + + # Initialize weight update group + url = f"{self.base_url}/init_communicator/" + # Will simplify it after torch xpu 2.9 support get uuid. + if is_torch_xpu_available(): + if hasattr(torch.xpu.get_device_properties(device), "uuid"): + client_device_uuid = str(torch.xpu.get_device_properties(device).uuid) + else: + client_device_uuid = "42" + else: + client_device_uuid = str(torch.cuda.get_device_properties(device).uuid) + + # Set the weight update group's host to "0.0.0.0" so that + # clients from different IPs can send updated weights + response = self.session.post( + url, + json={ + "host": "0.0.0.0", + "port": self.group_port, + "world_size": world_size, + "client_device_uuid": client_device_uuid, + }, + ) + if response.status_code != 200: + raise Exception(f"Request failed: {response.status_code}, {response.text}") + + # Brief delay to allow server initialization. While not strictly required (client socket will retry on + # connection failure), this prevents log warnings like: + # [W416 23:24:57.460001114 socket.cpp:204] [c10d] The hostname of the client socket cannot be retrieved. err=-3 + time.sleep(0.1) + + # Set up the communication group for weight broadcasting + if is_torch_xpu_available(): + store = torch.distributed.TCPStore( + host_name=self.host, port=self.group_port, world_size=world_size, is_master=(self.rank == 0) + ) + prefixed_store = c10d.PrefixStore("client2server", store) + xccl_options = c10d.ProcessGroupXCCL.Options() + pg = c10d.ProcessGroupXCCL( + store=prefixed_store, + rank=self.rank, + size=world_size, + options=xccl_options, + ) + self.communicator = pg + else: + pg = StatelessProcessGroup.create( + host=self.host, port=self.group_port, rank=self.rank, world_size=world_size + ) + self.communicator = PyNcclCommunicator(pg, device=device) + + # When the client object is deleted, close the weight update group + atexit.register(self.close_communicator) + + def update_named_param(self, name: str, weights: torch.Tensor): + """ + Updates a specific named parameter in the model and broadcasts it to other processes. + + Args: + name (`str`): + Name of the layer whose weights are being updated. + weights (`torch.Tensor`): + Tensor containing the updated weights. + """ + dtype, shape = str(weights.dtype), tuple(weights.shape) + url = f"{self.base_url}/update_named_param/" + response = self.session.post(url, json={"name": name, "dtype": dtype, "shape": shape}) + if response.status_code != 200: + raise Exception(f"Request failed: {response.status_code}, {response.text}") + + if is_torch_xpu_available(): + # Use XCCL to broadcast the updated weights from the client (src) to all workers. + self.communicator.broadcast(weights, root=self.rank) + self.communicator.barrier() + else: + # Use NCCL to broadcast the updated weights from the client (src) to all workers. + self.communicator.broadcast(weights, src=self.rank) + self.communicator.group.barrier() + + def update_model_params(self, model: nn.Module): + """ + Updates all parameters of the given model by calling `update_named_param` for each parameter in the model. + + Args: + model (`nn.Module`): + Model whose parameters (weights/biases) are to be updated. + """ + for name, param in model.named_parameters(): + # Update each parameter individually + self.update_named_param(name, param.data) + + def get_sequence_logprobs( + self, + sequences: list[list[int]], + prompt_lengths: list[int], + top_logprobs: int = 100, + temperature: float = 1.0, + use_binary: bool = True, + chunk_size: int = 0, + max_concurrent_requests: int = 4, + ) -> dict[str, list]: + """ + Computes teacher logprobs for existing token sequences without generating new tokens. + + Sends full sequences (prompt + completion) to the vLLM server and retrieves per-token top-k logprobs for the + completion region only. This is used for knowledge distillation where the teacher model evaluates existing + sequences rather than generating new ones. + + When `chunk_size > 0`, splits the batch into chunks and dispatches them concurrently via a thread pool, keeping + the server's data-parallel workers busy. + + When `use_binary=True`, uses base64-encoded numpy arrays for fast serialization instead of nested JSON lists. + + Args: + sequences (`list[list[int]]`): + List of full token ID sequences (prompt + completion). + prompt_lengths (`list[int]`): + Number of prompt tokens in each sequence. Logprobs are returned starting from this position. + top_logprobs (`int`, *optional*, defaults to `100`): + Number of top logprobs to return per token position. + temperature (`float`, *optional*, defaults to `1.0`): + Temperature used when scoring the teacher distribution. + use_binary (`bool`, *optional*, defaults to `True`): + Use binary (base64 numpy) response format for faster serialization. + chunk_size (`int`, *optional*, defaults to `0`): + If > 0, split batch into chunks of this size and dispatch concurrently. If 0, send the entire batch in + a single request. + max_concurrent_requests (`int`, *optional*, defaults to `4`): + Maximum number of concurrent requests when using chunked dispatch. + + Returns: + `dict` with keys: + - `logprobs` (`list[list[list[float]]]`): + Per-token logprobs of shape (batch, completion_len, top_logprobs), sorted by descending + probability. + - `logprob_token_ids` (`list[list[list[int]]]`): + Token IDs corresponding to each logprob, same shape as `logprobs`. + """ + from concurrent.futures import ThreadPoolExecutor, as_completed + + if temperature <= 0: + raise ValueError(f"temperature must be positive, got {temperature}") + + url = f"{self.base_url}/get_sequence_logprobs/" + response_format = "binary" if use_binary else "json" + + if chunk_size > 0 and len(sequences) > chunk_size: + # Chunked concurrent dispatch + n = len(sequences) + chunks = [] + for i in range(0, n, chunk_size): + chunks.append((sequences[i : i + chunk_size], prompt_lengths[i : i + chunk_size])) + + responses = [None] * len(chunks) + + def _send_chunk(idx, seqs, plens): + resp = self.session.post( + url, + json={ + "sequences": seqs, + "prompt_lengths": plens, + "top_logprobs": top_logprobs, + "temperature": temperature, + "response_format": response_format, + }, + ) + if resp.status_code != 200: + raise Exception(f"Request failed: {resp.status_code}, {resp.text}") + return idx, resp.json() + + with ThreadPoolExecutor(max_workers=min(max_concurrent_requests, len(chunks))) as executor: + futures = { + executor.submit(_send_chunk, idx, seqs, plens): idx for idx, (seqs, plens) in enumerate(chunks) + } + for future in as_completed(futures): + idx, result = future.result() + responses[idx] = result + + # Merge results + if use_binary: + return self._merge_binary_responses(responses, top_logprobs) + else: + all_logprobs = [] + all_token_ids = [] + for resp in responses: + all_logprobs.extend(resp["logprobs"]) + all_token_ids.extend(resp["logprob_token_ids"]) + return {"logprobs": all_logprobs, "logprob_token_ids": all_token_ids} + else: + # Single request + response = self.session.post( + url, + json={ + "sequences": sequences, + "prompt_lengths": prompt_lengths, + "top_logprobs": top_logprobs, + "temperature": temperature, + "response_format": response_format, + }, + ) + if response.status_code != 200: + raise Exception(f"Request failed: {response.status_code}, {response.text}") + + json_response = response.json() + if use_binary: + return self._decode_binary_logprobs(json_response) + else: + return { + "logprobs": json_response["logprobs"], + "logprob_token_ids": json_response["logprob_token_ids"], + } + + @staticmethod + def _decode_binary_logprobs(response: dict) -> dict[str, list]: + """Decode base64-encoded numpy arrays back to nested lists. + + Returns a dict with: + ``logprobs`` / ``logprob_token_ids`` — teacher's sorted top-k logprobs and + token IDs (shape per sequence: ``(comp_len, top_k)``). Used for the forward KL term. + ``actual_logprobs`` / ``actual_token_ids`` — teacher logprob for the actual + token at each position (shape per sequence: ``(comp_len, 1)``). Used for the reverse KL term. + """ + import numpy as np + + shape = response["shape"] # [batch, max_comp_len, top_k] + comp_lengths = response["completion_lengths"] + + logprobs_arr = np.frombuffer(base64.b64decode(response["logprobs_b64"]), dtype=np.float32).reshape(shape) + token_ids_arr = np.frombuffer(base64.b64decode(response["token_ids_b64"]), dtype=np.int32).reshape(shape) + + # Convert back to nested lists, trimming padding + all_logprobs = [] + all_token_ids = [] + for i, comp_len in enumerate(comp_lengths): + all_logprobs.append(logprobs_arr[i, :comp_len, :].tolist()) + all_token_ids.append(token_ids_arr[i, :comp_len, :].tolist()) + + result = {"logprobs": all_logprobs, "logprob_token_ids": all_token_ids} + + # Decode actual-token logprobs (for reverse KL) + if "actual_logprobs_b64" in response: + actual_shape = [shape[0], shape[1], 1] + actual_lp = np.frombuffer(base64.b64decode(response["actual_logprobs_b64"]), dtype=np.float32).reshape( + actual_shape + ) + actual_ids = np.frombuffer(base64.b64decode(response["actual_token_ids_b64"]), dtype=np.int32).reshape( + actual_shape + ) + all_actual_lps = [] + all_actual_ids = [] + for i, comp_len in enumerate(comp_lengths): + all_actual_lps.append(actual_lp[i, :comp_len, :].tolist()) + all_actual_ids.append(actual_ids[i, :comp_len, :].tolist()) + result["actual_logprobs"] = all_actual_lps + result["actual_token_ids"] = all_actual_ids + + return result + + @staticmethod + def _merge_binary_responses(responses: list[dict], top_logprobs: int) -> dict[str, list]: + """Merge binary responses from multiple chunks into a single result.""" + + all_logprobs = [] + all_token_ids = [] + all_actual_lps = [] + all_actual_ids = [] + for resp in responses: + decoded = VLLMClient._decode_binary_logprobs(resp) + all_logprobs.extend(decoded["logprobs"]) + all_token_ids.extend(decoded["logprob_token_ids"]) + if "actual_logprobs" in decoded: + all_actual_lps.extend(decoded["actual_logprobs"]) + all_actual_ids.extend(decoded["actual_token_ids"]) + + result = {"logprobs": all_logprobs, "logprob_token_ids": all_token_ids} + if all_actual_lps: + if len(all_actual_lps) != len(all_logprobs): + raise ValueError( + f"Inconsistent chunks: {len(all_actual_lps)} actual_logprobs entries " + f"but {len(all_logprobs)} logprobs entries." + ) + result["actual_logprobs"] = all_actual_lps + result["actual_token_ids"] = all_actual_ids + return result + + def reset_prefix_cache(self): + """ + Resets the prefix cache for the model. + """ + url = f"{self.base_url}/reset_prefix_cache/" + response = self.session.post(url) + if response.status_code != 200: + raise Exception(f"Request failed: {response.status_code}, {response.text}") + + def close_communicator(self): + """ + Closes the weight update group and cleans up the communication group. + """ + url = f"{self.base_url}/close_communicator/" + + try: + response = self.session.post(url) + except ConnectionError: + # The server might be already down, so we don't need to close the communicator + pass + else: + if response.status_code != 200: + raise Exception(f"Request failed: {response.status_code}, {response.text}") + + if self.communicator is not None: + self.communicator = None + + +# Example usage +if __name__ == "__main__": + from vllm import SamplingParams + + device = "xpu" if is_torch_xpu_available() else "cuda" + client = VLLMClient() + client.init_communicator(device=device) + + # Generate completions + responses = client.generate(["Hello, AI!", "Tell me a joke"], n=4, max_tokens=32, sampling_params=SamplingParams()) + print("Responses:", responses) # noqa + + # Update model weights + from transformers import AutoModelForCausalLM + + model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-7B").to(device) + client.update_model_params(model) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/generation/vllm_generation.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/generation/vllm_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..0c9cea9b586449e4a39471b3f766bc9bc2069b3f --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/generation/vllm_generation.py @@ -0,0 +1,689 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""vLLM-based generation backend for TRL trainers.""" + +import logging +import math +import os +from contextlib import nullcontext +from typing import TYPE_CHECKING + +import torch +from accelerate.utils import broadcast_object_list, gather_object, is_peft_model +from torch import nn +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from transformers import PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin, is_bitsandbytes_available +from transformers.utils import ( + is_torch_mlu_available, + is_torch_mps_available, + is_torch_npu_available, + is_torch_xpu_available, +) + +from ..distributed import DistributedBackend +from ..extras.profiling import ProfilingContext +from ..import_utils import is_vllm_available +from ..trainer.utils import ensure_master_addr_port +from .vllm_client import VLLMClient + + +if is_vllm_available(): + from vllm import LLM, RequestOutput, SamplingParams + from vllm.sampling_params import StructuredOutputsParams + + +logger = logging.getLogger(__name__) + + +def empty_cache() -> None: + """Empties the cache of the available torch device. + + This function checks for the availability of different torch devices (CUDA, MLU, MPS, NPU, XPU) and empties the + cache of the first available device it finds. + + If none of the specific devices are available, it defaults to emptying the CUDA cache. + """ + if is_torch_mlu_available(): + torch.mlu.empty_cache() + elif is_torch_mps_available(): + torch.mps.empty_cache() + elif is_torch_npu_available(): + torch.npu.empty_cache() + elif is_torch_xpu_available(): + torch.xpu.empty_cache() + else: + torch.cuda.empty_cache() + + +def extract_logprobs(all_outputs: list["RequestOutput"]): + """ + Extract logprobs and token IDs from vLLM generation outputs. + + Returns logprobs and token IDs sorted by rank (most probable first). Each returned list has shape (num_sequences, + seq_len, num_logprobs), where num_logprobs is determined by the `logprobs` parameter passed to vLLM (1 when + `logprobs=0`, up to N+1 when `logprobs=N`). NaN logprob values are replaced with `None`. + + Args: + all_outputs (list of `RequestOutput`): + List of vLLM `RequestOutput` objects from generation. + + Returns: + Tuple of (logprobs, logprob_token_ids), each of shape (num_sequences, seq_len, num_logprobs). + """ + all_logprobs = [] + all_token_ids = [] + for outputs in all_outputs: + for output in outputs.outputs: + if output.logprobs is None: + return None, None + seq_logprobs = [] + seq_token_ids = [] + for lp in output.logprobs: + sorted_items = sorted(lp.items(), key=lambda x: x[1].rank) + seq_token_ids.append([token_id for token_id, _ in sorted_items]) + seq_logprobs.append([None if math.isnan(item.logprob) else item.logprob for _, item in sorted_items]) + all_logprobs.append(seq_logprobs) + all_token_ids.append(seq_token_ids) + return all_logprobs, all_token_ids + + +if TYPE_CHECKING: + from accelerate import Accelerator + from peft import PeftModel + + +if is_bitsandbytes_available(): + import bitsandbytes as bnb + + +class VLLMGeneration: + """Handles vLLM-based generation for trainers. + + Extracts all vLLM-specific logic (initialization, generation, weight sync) from trainers into a separate, testable + class. + + Args: + model ([`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]): + Model to use for generation. + accelerator ([`~accelerate.Accelerator`]): + Accelerator for distributed training. + processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`]): + Tokenizer or processor for the model. + + > Parameters for vLLM: + + mode (`str`, *optional*, defaults to `"colocate"`): + vLLM mode. Must be one of `"colocate"` or `"server"`. + + - `"colocate"`: vLLM will run in the same process and share the training GPUs. This avoids the need for a + separate server but may cause resource contention with training. + - `"server"`: The trainer will send generation requests to a separate vLLM server. Make sure a TRL vLLM + server is running (start with `trl vllm-serve`). + + structured_outputs_regex (`str`, *optional*): + Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled. + + > Parameters for "server" vLLM mode: + + server_base_url (`str`, *optional*): + Base URL for the vLLM server (e.g., `"http://localhost:8000"`). If provided, `server_host` and + `server_port` are ignored. + server_host (`str`, *optional*, defaults to `"0.0.0.0"`): + Host of the vLLM server to connect to. Ignored if `server_base_url` is provided. + server_port (`int`, *optional*, defaults to `8000`): + Port of the vLLM server to connect to. Ignored if `server_base_url` is provided. + server_timeout (`float`, *optional*, defaults to `240.0`): + Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up after the + timeout, a `ConnectionError` is raised. + group_port (`int`, *optional*, defaults to `51216`): + Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port + is occupied, there is no need to change it. + + > Parameters for "colocate" vLLM mode: + + tensor_parallel_size (`int`, *optional*, defaults to `1`): + The number of GPUs to use for distributed execution with tensor parallelism. This setting only applies when + `mode` is set to `"colocate"`. If you are using `mode="server"`, this parameter must be passed separately + when launching the vLLM server via the `--vllm_tensor_parallel_size` flag. + gpu_memory_utilization (`float`, *optional*, defaults to `0.9`): + Ratio (between 0 and 1) of GPU memory to reserve for the model weights, activations, and KV cache. Higher + values will increase the KV cache size and thus improve the model's throughput. However, if the value is + too high, it may cause out-of- memory (OOM) errors. This setting only applies when `mode` is set to + `"colocate"`. If you are using `mode="server"`, this parameter must be passed separately when launching the + vLLM server via the `--vllm_gpu_memory_utilization` flag. + max_model_length (`int`, *optional*): + Model context length (prompt and completion). Set it to at least the maximum prompt length in the dataset + plus `max_completion_length`; if omitted, it is inferred from the model config. + max_num_seqs (`int`, *optional*): + Maximum number of sequences to process in parallel, effectively capping the batch size. + enable_sleep_mode (`bool`, *optional*, defaults to `False`): + Whether to enable sleep mode for the engine to offload weights/cache during the optimizer step. Keeps GPU + memory usage low, but waking the engine adds host–device transfer latency. + model_impl (`str`, *optional*, defaults to `"auto"`): + Model implementation to use for vLLM. + - "auto" will try to use the vLLM implementation, if it exists, and fall back to the Transformers + implementation if no vLLM implementation is available. + - "vllm" will use the vLLM model implementation. + - "transformers" will use the Transformers model implementation. + - "terratorch" will use the TerraTorch model implementation. + + > Parameters for generation: + + repetition_penalty (`float`, *optional*, defaults to `1.0`): + Parameter for repetition penalty. It penalizes new tokens based on whether they appear in the prompt and + the generated text so far. Values > 1 encourage the model to use new tokens, while values < 1 encourage the + model to repeat tokens. Default `1.0` means no penalty. + temperature (`float`, *optional*, defaults to `1.0`): + Sampling temperature. It controls the randomness of the sampling. Lower values make the model more + deterministic, while higher values make the model more random and increase diversity. + top_p (`float`, *optional*, defaults to `1.0`): + Top-p sampling parameter. It controls the cumulative probability of the top tokens to consider. Defaults to + `1.0` to consider all tokens. + top_k (`int`, *optional*, defaults to `0`): + Top-k sampling parameter. It controls the number of top tokens to consider. Defaults to `0` to consider all + tokens. + min_p (`float`, *optional*, defaults to `0.0`): + Min-p sampling parameter. It represents the minimum probability for a token to be considered, relative to + the probability of the most likely token. Default `0.0` means min-p is disabled. + max_completion_length (`int`, *optional*, defaults to `16`): + Maximum number of tokens to generate for each prompt. + logprobs (`int` or `None`, *optional*, defaults to `0`): + Number of top logprobs to return per token. When 0 (default), only the sampled token's logprob is returned + (inner dimension = 1). When N>0, returns up to N+1 logprobs sorted by descending probability, because vLLM + always includes the sampled token's logprob alongside the top-N (the sampled token may or may not already + be in the top-N). + generation_kwargs (`dict`, *optional*): + Additional generation parameters to pass to the vLLM `SamplingParams`. This can include parameters like + `seed`, `frequency_penalty`, etc. If it contains keys that conflict with the other parameters, they will + override them. + + > Parameters for chat/tools: + + chat_template (`str`, *optional*): + Template to use for structuring the chat. If not provided, the model's default chat template will be used. + chat_template_kwargs (`dict`, *optional*): + Additional keyword arguments to customize the chat template used by the model. + tools (`list`, *optional*): + Tools available for tool calling during chat generation. + """ + + def __init__( + self, + model: "PreTrainedModel | PeftModel", + accelerator: "Accelerator", + processing_class: PreTrainedTokenizerBase | ProcessorMixin, + # vLLM configuration + mode: str = "colocate", + structured_outputs_regex: str | None = None, + # Server mode configuration + server_base_url: str | None = None, + server_host: str = "0.0.0.0", + server_port: int = 8000, + server_timeout: float = 240.0, + group_port: int = 51216, + # Colocate mode configuration + tensor_parallel_size: int = 1, + gpu_memory_utilization: float = 0.9, + max_model_length: int | None = None, + max_num_seqs: int | None = None, + enable_sleep_mode: bool = False, + model_impl: str = "auto", + # Generation configuration + repetition_penalty: float = 1.0, + temperature: float = 1.0, + top_p: float = 1.0, + top_k: int = 0, + min_p: float = 0.0, + max_completion_length: int = 16, + logprobs: int | None = 0, + generation_kwargs: dict | None = None, + ): + self.model = model + self.accelerator = accelerator + self._dist = DistributedBackend(accelerator) + self.processing_class = processing_class + + # vLLM configuration + self.mode = mode + self.structured_outputs_regex = structured_outputs_regex + + # Server mode configuration + self.server_base_url = server_base_url + self.server_host = server_host + self.server_port = server_port + self.group_port = group_port + self.server_timeout = server_timeout + + # Colocate mode configuration + self.tensor_parallel_size = tensor_parallel_size + self.gpu_memory_utilization = gpu_memory_utilization + self.max_model_length = max_model_length + self.max_num_seqs = max_num_seqs + self.enable_sleep_mode = enable_sleep_mode + self.model_impl = model_impl + + # Generation configuration + self.repetition_penalty = repetition_penalty + self.temperature = temperature + self.top_p = top_p + self.top_k = top_k + self.min_p = min_p + self.max_completion_length = max_completion_length + self.logprobs = logprobs + self.generation_kwargs = generation_kwargs or {} + + self._init_vllm() + + def _init_vllm(self): + """Initialize vLLM in server or colocate mode.""" + model = self.model + accelerator = self.accelerator + + if not is_vllm_available(): + raise ImportError( + "vLLM is not available and `use_vllm` is set to True. Please install vLLM with " + "`pip install trl[vllm]` to use it." + ) + + if self.mode == "server": + if accelerator.is_main_process: + if self.server_base_url is not None: + base_url = self.server_base_url + else: + base_url = f"http://{self.server_host}:{self.server_port}" + self.vllm_client = VLLMClient( + base_url=base_url, group_port=self.group_port, connection_timeout=self.server_timeout + ) + self.vllm_client.init_communicator(device=torch.cuda.current_device()) + + elif self.mode == "colocate": + # Make sure tensor_parallel_size group size evenly divides the world size - each group should have + # the same number of ranks + if not accelerator.num_processes % self.tensor_parallel_size == 0: + raise ValueError( + f"tensor_parallel_size ({self.tensor_parallel_size}) must divide world size " + f"({accelerator.num_processes}) evenly." + ) + + if self.tensor_parallel_size > 1: + # Create subgroups of ranks for TP, each group with `tensor_parallel_size` ranks. + # For example, if world_size=8 and tensor_parallel_size=2 → groups: [0,1], [2,3], [4,5], [6,7] + self.tp_group, _ = torch.distributed.new_subgroups_by_enumeration( + [ + list(range(i * self.tensor_parallel_size, (i + 1) * self.tensor_parallel_size)) + for i in range(accelerator.num_processes // self.tensor_parallel_size) + ] + ) + + # vLLM requires the environment variables to be set for distributed training. + os.environ["RANK"] = str(accelerator.process_index) + os.environ["LOCAL_RANK"] = str(accelerator.local_process_index) + os.environ["WORLD_SIZE"] = str(accelerator.num_processes) + # Ensure distributed rendezvous variables are set without colliding across concurrent runs + ensure_master_addr_port() + + quantization = None + if is_bitsandbytes_available(): + for _, module in model.named_modules(): + if isinstance(module, bnb.nn.Linear4bit): + quantization = "bitsandbytes" + break + elif isinstance(module, bnb.nn.Linear8bitLt): + raise ValueError("vLLM does not support in-flight 8-bit quantization.") + + # Build LLM initialization kwargs + self.llm = LLM( + model=model.name_or_path, + tensor_parallel_size=self.tensor_parallel_size, + gpu_memory_utilization=self.gpu_memory_utilization, + max_model_len=self.max_model_length, + max_num_seqs=self.max_num_seqs, + enable_sleep_mode=self.enable_sleep_mode, + model_impl=self.model_impl, + distributed_executor_backend="external_launcher", + # Feed identical seed for tp groups to ensure sampling results are the same across workers + seed=accelerator.process_index // self.tensor_parallel_size, + # Latest vLLM v1 memory profiler is misled by the high default value (i.e., 32768) - thinking there's not enough memory + max_num_batched_tokens=4096, + # Important so temperature scaling/logit tweaking affects the TIS log probs + logprobs_mode="processed_logprobs", + quantization=quantization, + ) + if self.enable_sleep_mode: + self.llm.sleep(level=2) + else: + raise ValueError(f"vllm_mode must be either 'server' or 'colocate', got '{self.mode}'.") + + # When using vLLM, the main process is responsible for loading the model weights. This can cause process + # desynchronization and seems to lead to DeepSpeed hanging during initialization. To prevent this, we + # synchronize all processes after vLLM has been fully initialized. + accelerator.wait_for_everyone() + + def _fix_param_name_to_vllm(self, name: str, extra_prefixes: list[str] | None = None) -> str: + """Fix parameter name for vLLM compatibility.""" + extra_prefixes = extra_prefixes or [] + prefixes = ["_checkpoint_wrapped_module."] + extra_prefixes + for prefix in prefixes: + name = name.replace(prefix, "") + return name + + def _push_param_to_vllm(self, name: str, param) -> None: + """Push a single parameter tensor to the vLLM engine (server or colocate mode).""" + if self.mode == "server" and self.accelerator.is_main_process: + self.vllm_client.update_named_param(name, param) + elif self.mode == "colocate": + self.llm.llm_engine.model_executor.driver_worker.model_runner.model.load_weights([(name, param)]) + + def _sync_fsdp1_params_to_vllm(self, module: nn.Module, prefix: str = "", visited: set[str] | None = None): + """Memory-efficient post-order traversal of FSDP modules to extract full parameters and sync with vLLM.""" + # For FSDP1, we need to recurse into children and also use summon_full_params + if visited is None: + visited = set() + for child_name, child_module in module.named_children(): + child_prefix = f"{prefix}.{child_name}" if prefix else child_name + self._sync_fsdp1_params_to_vllm( + child_module, prefix=child_prefix, visited=visited + ) # recurse into the child + + if isinstance(module, FSDP): + with FSDP.summon_full_params(module, recurse=False, writeback=False): + for param_name, param in module.named_parameters(): + full_name = f"{prefix}.{param_name}" if prefix else param_name + full_name = self._fix_param_name_to_vllm(full_name, extra_prefixes=["_fsdp_wrapped_module."]) + + if full_name in visited: + continue # skip FSDP subtrees already traversed + visited.add(full_name) + + self._push_param_to_vllm(full_name, param.data) + + def _sync_fsdp2_params_to_vllm(self, module: nn.Module): + """FSDP2-specific parameter synchronization.""" + # For FSDP2, module.state_dict() already covers all parameters, so no need for recursion + for name, param in module.state_dict().items(): + # When using PEFT, we need to recover the original parameter name + name = name.removeprefix("base_model.model.").replace(".base_layer", "") + # Skip PEFT layers: they don't exist in vLLM, and they are merged already. + if is_peft_model(module) and module.prefix in name: + continue + # When module to save, remove its prefix and discard the original module + if "original_module" in name: + continue + name = self._fix_param_name_to_vllm(name, extra_prefixes=["modules_to_save.default."]) + + if param.is_cpu: + param = param.to(torch.device("cuda")) + param = param.full_tensor() + + self._push_param_to_vllm(name, param) + + def _sync_fsdp_params_to_vllm(self, model: nn.Module): + """Dispatch FSDP weight sync to the version-appropriate method.""" + if self._dist.fsdp_version == 1: + self._sync_fsdp1_params_to_vllm(model) + elif self._dist.fsdp_version == 2: + self._sync_fsdp2_params_to_vllm(model) + + def sync_weights(self): + """Synchronize model weights to vLLM. + + Handles FSDP, DeepSpeed, PEFT weight synchronization. + """ + # Wake up vLLM weights before loading to ensure device memory is mapped. Without this, load_weights() writes to + # freed/unmapped memory when sleep mode is active, which crashes on backends with strict physical memory + # management (e.g., Ascend NPU). See https://github.com/huggingface/trl/issues/5142 + if self.mode == "colocate" and self.enable_sleep_mode: + empty_cache() # required to avoid OOM in some cases + self.llm.wake_up(tags=["weights"]) + + model = self.model + accelerator = self.accelerator + + if is_peft_model(model): + # With PEFT and FSDP/DeepSpeed ZeRO Stage 3, we must gather the full model at once before merging, as + # merging adapters in a sharded manner is not supported. + # TODO: does this work with FSDP? + with self._dist.gather_params(list(model.parameters())): + model.merge_adapter() + + # Update vLLM weights while parameters are gathered + if self._dist.is_fsdp: # note if using FSDP, gather_params is a no-op + # For PEFT with FSDP we need to use the memory efficient post-order traversal + self._sync_fsdp_params_to_vllm(model) + else: + # DeepSpeed ZeRO-3 with PEFT + for name, param in model.named_parameters(): + # When using PEFT, we need to recover the original parameter name + name = name.removeprefix("base_model.model.").replace(".base_layer", "") + # Skip PEFT layers: they don't exist in vLLM, and they are merged already. + if model.prefix in name: + continue + # When module to save, remove its prefix and discard the original module + if "original_module" in name: + continue + name = self._fix_param_name_to_vllm(name, extra_prefixes=["modules_to_save.default."]) + + self._push_param_to_vllm(name, param.data) + # Unmerge adapters while parameters are still gathered + model.unmerge_adapter() + # Parameters will automatically be repartitioned when exiting the context + else: + # For non-PEFT models, simply gather (if needed) and update each parameter individually. + if self._dist.is_fsdp: + self._sync_fsdp_params_to_vllm(model) + else: + for name, param in model.named_parameters(): + name = self._fix_param_name_to_vllm(name) + with self._dist.gather_params([param]): + self._push_param_to_vllm(name, param.data) + + # Reset cache on vLLM + if self.mode == "server" and accelerator.is_main_process: + self.vllm_client.reset_prefix_cache() + elif self.mode == "colocate": + self.llm.reset_prefix_cache() + + def generate( + self, + prompts: list[list[int]], + images: list[list | None] | None, + num_generations: int, + profiler: ProfilingContext | None = None, + ) -> tuple: + """Generate completions using vLLM. + + Args: + prompts: List of token ID lists, one per prompt (already tokenized). + images: Optional list of image lists for VLM support. Each element is a list of PIL images for the + corresponding prompt, or `None` if no images for that prompt. `None` if no images at all. + num_generations: Number of generations per prompt. + profiler: Optional profiler for performance tracking. + + Returns: + Tuple of (prompt_ids, completion_ids, logprobs, logprob_token_ids). + + - `prompt_ids`: `list[list[int]]` of shape `(batch_size, prompt_len)`. + - `completion_ids`: `list[list[int]]` of shape `(batch_size, completion_len)`. + - `logprobs`: `list[list[list[float | None]]]` of shape `(batch_size, completion_len, num_logprobs)`. + - `logprob_token_ids`: `list[list[list[int]]]` of shape `(batch_size, completion_len, num_logprobs)`. + + `num_logprobs` is 1 when `logprobs=0`, or up to N+1 when `logprobs=N` (the sampled token is always included + and may fall outside the top-N). + """ + profiler = profiler or nullcontext() + accelerator = self.accelerator + temperature = self.temperature + top_p = self.top_p + top_k = self.top_k + min_p = self.min_p + repetition_penalty = self.repetition_penalty + max_completion_length = self.max_completion_length + + # Wake up colocated vLLM weights if needed (idempotent if already awake from sync_weights) + if self.mode == "colocate" and self.enable_sleep_mode: + empty_cache() # required to avoid OOM in some cases + self.llm.wake_up(tags=["weights"]) + # Work around for https://github.com/vllm-project/vllm/issues/29341 + try: + self.llm.collective_rpc("reload_weights") + except NotImplementedError: + # Non-CUDA vLLM backends (e.g., vllm-ascend's NPUWorkerV1), don't implement reload_weights + pass + + # Generate completions using vLLM: gather all prompts and use them in a single call in the main process + if self.mode == "server": + all_prompts = gather_object(prompts) + # Always gather images (even when None) to avoid deadlock: images may be None on some ranks + # and non-None on others in mixed datasets, and gather_object is a collective operation. + all_images = gather_object(images if images is not None else [None] * len(prompts)) + if all(img is None for img in all_images): + all_images = None + + if accelerator.is_main_process: + # Since 'prompts' contains 'num_generations' duplicates, we first take unique prompts, and + # generate num_generations outputs for each one. This is faster than generating outputs for each + # duplicate prompt individually. + ordered_set_of_prompt_ids = all_prompts[::num_generations] + ordered_set_of_images = all_images[::num_generations] if all_images is not None else None + + sampling_params = { + "n": num_generations, + "repetition_penalty": repetition_penalty, + "temperature": temperature, + "top_p": top_p, + "top_k": top_k, + "min_p": 0.0 if min_p is None else min_p, + "max_tokens": max_completion_length, + "logprobs": self.logprobs, + "structured_outputs_regex": self.structured_outputs_regex, + "generation_kwargs": self.generation_kwargs, + } + with profiler: + output = self.vllm_client.generate( + prompts=ordered_set_of_prompt_ids, + images=ordered_set_of_images, + **sampling_params, + ) + payload = ( + output["prompt_ids"], + output["completion_ids"], + output["logprobs"], + output.get("logprob_token_ids"), + ) + else: + payload = None + + # Broadcast the completions from the main process to all processes, ensuring each process receives its corresponding slice. + obj_list = [payload] + broadcast_object_list(obj_list, from_process=0) + all_prompt_ids, all_completion_ids, all_logprobs, all_logprob_token_ids = obj_list[0] + + # vllm_client.generate(n=num_generations) returns num_generations completions per prompt. + # Duplicate prompt_ids to align with per-completion entries. + all_prompt_ids = [ids for ids in all_prompt_ids for _ in range(num_generations)] + + process_slice = slice( + accelerator.process_index * len(prompts), + (accelerator.process_index + 1) * len(prompts), + ) + prompt_ids = all_prompt_ids[process_slice] + completion_ids = all_completion_ids[process_slice] + logprobs = all_logprobs[process_slice] if all_logprobs is not None else None + logprob_token_ids = all_logprob_token_ids[process_slice] if all_logprob_token_ids is not None else None + + # Generate completions using colocated vLLM instances: each device holds vLLM copy and work on their own batch of prompts + elif self.mode == "colocate": + generation_kwargs = { + "n": 1, # vLLM on each GPU generates only 1 in colocate mode + "repetition_penalty": repetition_penalty, + "temperature": temperature, + "top_p": top_p, + "top_k": top_k, + "min_p": 0.0 if min_p is None else min_p, + "max_tokens": max_completion_length, + "logprobs": self.logprobs, + } + generation_kwargs.update(self.generation_kwargs) + + if self.structured_outputs_regex is not None: + if generation_kwargs.get("structured_outputs") is not None: + logger.warning( + "Both `structured_outputs_regex` and `generation_kwargs['structured_outputs']` are set; " + "`structured_outputs_regex` takes precedence." + ) + generation_kwargs["structured_outputs"] = StructuredOutputsParams(regex=self.structured_outputs_regex) + elif isinstance(structured_outputs_kwargs := generation_kwargs.get("structured_outputs"), dict): + generation_kwargs["structured_outputs"] = StructuredOutputsParams(**structured_outputs_kwargs) + sampling_params = SamplingParams(**generation_kwargs) + + if self.tensor_parallel_size > 1: + # Gather prompts from all ranks in the TP group and flatten. + # Each rank starts with its own prompts; after gathering, all ranks see the full group set. + orig_size = len(prompts) + gathered_prompts = [None for _ in range(self.tensor_parallel_size)] + torch.distributed.all_gather_object(gathered_prompts, prompts, group=self.tp_group) + all_prompts = [p for sublist in gathered_prompts for p in sublist] + # Always gather images (even when None) to avoid deadlock: images may be None on some + # ranks and non-None on others in mixed datasets, and all_gather_object is collective. + local_images = images if images is not None else [None] * len(prompts) + gathered_images = [None for _ in range(self.tensor_parallel_size)] + torch.distributed.all_gather_object(gathered_images, local_images, group=self.tp_group) + all_images = [img for sublist in gathered_images for img in sublist] + if all(img is None for img in all_images): + all_images = None + else: + all_prompts = prompts + all_images = images + + if self.enable_sleep_mode: + self.llm.wake_up(tags=["kv_cache"]) + + # Build vLLM-compatible prompt inputs with token IDs and optional multi-modal data + vllm_prompts = [] + if all_images is not None: + for ids, img_list in zip(all_prompts, all_images, strict=True): + row = {"prompt_token_ids": ids} + if img_list is not None: + row["multi_modal_data"] = {"image": img_list if len(img_list) > 1 else img_list[0]} + vllm_prompts.append(row) + else: + vllm_prompts = [{"prompt_token_ids": ids} for ids in all_prompts] + + with profiler: + all_outputs = self.llm.generate(vllm_prompts, sampling_params=sampling_params, use_tqdm=False) + + all_prompt_ids = [output.prompt_token_ids for output in all_outputs] + all_completion_ids = [output.token_ids for outputs in all_outputs for output in outputs.outputs] + all_logprobs, all_logprob_token_ids = extract_logprobs(all_outputs) + + if self.tensor_parallel_size > 1: + # Slice completions for this rank within its TP group. + # Each rank generates all outputs — we keep only our share. + local_rank_in_group = torch.distributed.get_rank(group=self.tp_group) + tp_slice = slice(local_rank_in_group * orig_size, (local_rank_in_group + 1) * orig_size) + prompt_ids = all_prompt_ids[tp_slice] + completion_ids = all_completion_ids[tp_slice] + logprobs = all_logprobs[tp_slice] if all_logprobs is not None else None + logprob_token_ids = all_logprob_token_ids[tp_slice] if all_logprob_token_ids is not None else None + else: + prompt_ids = all_prompt_ids + completion_ids = all_completion_ids + logprobs = all_logprobs + logprob_token_ids = all_logprob_token_ids + + if self.enable_sleep_mode: + self.llm.sleep(level=2) + + return prompt_ids, completion_ids, logprobs, logprob_token_ids diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/import_utils.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/import_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..716741843f354335dbeac2c0bdde4560a48b6869 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/import_utils.py @@ -0,0 +1,149 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import importlib +import importlib.metadata +import importlib.util +import warnings +from contextlib import contextmanager + +from packaging.version import Version + + +LIGER_KERNEL_MIN_VERSION = "0.8.0" +PACKAGE_DISTRIBUTION_MAPPING = importlib.metadata.packages_distributions() + + +# From transformers: https://github.com/huggingface/transformers/blob/556312cd45a5e619c41b0f8adf680eab0d334324/src/transformers/utils/import_utils.py#L48-L77 +def _is_package_available(pkg_name: str, return_version: bool = False) -> tuple[bool, str] | bool: + """Check if `pkg_name` exist, and optionally try to get its version""" + spec = importlib.util.find_spec(pkg_name) + package_exists = spec is not None + package_version = "N/A" + if package_exists and return_version: + try: + # importlib.metadata works with the distribution package, which may be different from the import + # name (e.g. `PIL` is the import name, but `pillow` is the distribution name) + distributions = PACKAGE_DISTRIBUTION_MAPPING[pkg_name] + # Per PEP 503, underscores and hyphens are equivalent in package names. + # Prefer the distribution that matches the (normalized) package name. + normalized_pkg_name = pkg_name.replace("_", "-") + if normalized_pkg_name in distributions: + distribution_name = normalized_pkg_name + elif pkg_name in distributions: + distribution_name = pkg_name + else: + distribution_name = distributions[0] + package_version = importlib.metadata.version(distribution_name) + except (importlib.metadata.PackageNotFoundError, KeyError): + # If we cannot find the metadata (because of editable install for example), try to import directly. + # Note that this branch will almost never be run, so we do not import packages for nothing here + package = importlib.import_module(pkg_name) + package_version = getattr(package, "__version__", "N/A") + if return_version: + return package_exists, package_version + else: + return package_exists + + +def is_deepspeed_available() -> bool: + return _is_package_available("deepspeed") + + +def is_fastapi_available() -> bool: + return _is_package_available("fastapi") + + +def is_harbor_available() -> bool: + return _is_package_available("harbor") + + +def is_jmespath_available() -> bool: + return _is_package_available("jmespath") + + +def is_joblib_available() -> bool: + return _is_package_available("joblib") + + +def is_liger_kernel_available(min_version: str = LIGER_KERNEL_MIN_VERSION) -> bool: + _liger_kernel_available, _liger_kernel_version = _is_package_available("liger_kernel", return_version=True) + return _liger_kernel_available and Version(_liger_kernel_version) >= Version(min_version) + + +def is_math_verify_available() -> bool: + return _is_package_available("math_verify") + + +def is_mergekit_available() -> bool: + return _is_package_available("mergekit") + + +def is_openreward_available() -> bool: + return _is_package_available("openreward") + + +def is_pydantic_available() -> bool: + return _is_package_available("pydantic") + + +def is_requests_available() -> bool: + return _is_package_available("requests") + + +def is_unsloth_available() -> bool: + return _is_package_available("unsloth") + + +def is_uvicorn_available() -> bool: + return _is_package_available("uvicorn") + + +def is_vllm_available(min_version: str | None = None) -> bool: + _vllm_available, _vllm_version = _is_package_available("vllm", return_version=True) + if _vllm_available: + if not (Version("0.14.0") <= Version(_vllm_version) <= Version("0.23.0")): + warnings.warn( + f"TRL currently supports vLLM versions from 0.14.0 to 0.23.0. You have version {_vllm_version} " + "installed. We recommend installing a supported version to avoid compatibility issues.", + stacklevel=2, + ) + if min_version is not None and Version(_vllm_version) < Version(min_version): + return False + return _vllm_available + + +def is_vllm_ascend_available() -> bool: + return _is_package_available("vllm_ascend") + + +def is_weave_available() -> bool: + return _is_package_available("weave") + + +class TRLExperimentalWarning(UserWarning): + """Warning for using the 'trl.experimental' submodule.""" + + pass + + +@contextmanager +def suppress_warning(category): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=category) + yield + + +def suppress_experimental_warning(): + return suppress_warning(TRLExperimentalWarning) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/models/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f84d989c2825020b0b69c4b31f0285fdcdf54b41 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/models/__init__.py @@ -0,0 +1,32 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import TYPE_CHECKING + +from .._lazy_module import _LazyModule + + +_import_structure = { + "activation_offloading": ["get_act_offloading_ctx_manager"], + "utils": ["create_reference_model", "prepare_deepspeed", "prepare_fsdp", "unwrap_model_for_generation"], +} + + +if TYPE_CHECKING: + from .activation_offloading import get_act_offloading_ctx_manager + from .utils import create_reference_model, prepare_deepspeed, prepare_fsdp, unwrap_model_for_generation +else: + import sys + + sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/models/activation_offloading.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/models/activation_offloading.py new file mode 100644 index 0000000000000000000000000000000000000000..0e3faecada84e17fb63935967dae333f81f367a8 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/models/activation_offloading.py @@ -0,0 +1,762 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of https://github.com/pytorch/torchtune. + + +import sys + +import psutil +import torch +from accelerate.logging import get_logger +from accelerate.utils.versions import is_torch_version +from torch import nn +from torch.autograd.graph import saved_tensors_hooks +from transformers import is_torch_npu_available + + +if is_torch_npu_available(): + import torch_npu # noqa: F401 + +# Import DTensor for FSDP v2 support with version-aware import path +DTensor = None +if torch.distributed.is_available(): + try: + if is_torch_version(">=", "2.5.0"): + from torch.distributed.tensor import DTensor + else: + # from torch 2.0.0 (oldest supported accelerate torch version), DTensor is in torch.distributed._tensor + from torch.distributed._tensor import DTensor + except (ImportError, AttributeError): + DTensor = None + +logger = get_logger(__name__) + + +def _get_unique_tensor_key(tensor: torch.Tensor) -> tuple: + """ + Get a unique key for a tensor based on its storage pointer and dtype. This allows deduplication of tensors that + share the same underlying storage. From: + https://github.com/volcengine/verl/blob/main/verl/utils/activation_offload.py + + Args: + tensor: The tensor to get the key for + + Returns: + A tuple of (storage_pointer, dtype) that uniquely identifies the tensor's storage + """ + # Handle special tensor types - primarily for FSDP v2 DTensor + actual_tensor = tensor + + # For DTensor (FSDP v2), extract the local tensor + if DTensor is not None and isinstance(tensor, DTensor) and hasattr(tensor, "_local_tensor"): + actual_tensor = tensor._local_tensor + + # Try to get storage pointer, but fall back to tensor id if not accessible + try: + storage_ptr = actual_tensor.untyped_storage().data_ptr() + actual_tensor.storage_offset() + except (RuntimeError, AttributeError): + # For tensors with invalid storage, use tensor id + # This won't enable deduplication for these tensors, but allows offloading to work + storage_ptr = id(actual_tensor) + + return (storage_ptr, actual_tensor.dtype) + + +class OffloadActivations(saved_tensors_hooks): + """ + Context manager under which activation tensors created in the forward pass will be offloaded. + + Enable the memory efficiency technique of activation offloading, where activations bigger than `min_offload_size` + bytes will be offloaded to CPU in the forward and brought back in the backward. This is in contrast to maintaining + the activation on GPU VRAM throughout the program. + + This manager contains the option of using one additional CUDA stream to handle the communication between CUDA and + CPU, which is intended to overlap with the default computation stream to improve runtime. We designed + synchronization with a few heuristics for optimizing the tradeoff between runtime vs memory usage. + + Args: + use_pin_memory (`bool`, *optional*, defaults to `True`): + Whether to offloaded Tensor will be placed in pinned memory on the CPU. Pinned memory allows the Tensor to + be moved back onto GPU more quickly but is a limited resource. + use_streams (`bool`, *optional*, defaults to `True`): + Whether to use streams for performance optimization where the communications get overlapped with the + computation. Requires a torch build after torch-2.5.0. + min_offload_size (`int`, *optional*, defaults to `1024`): + Minimum number of bytes a Tensor must be in order to qualify for offloading. If the tensor is too small, we + do not want to waste bandwidth and resources moving it to CPU and back. + max_fwd_stash_size (`int`, *optional*, defaults to `5`): + Maximum size of the forward stash, or the maximum number of consecutive activations to keep alive during + the forward pass. This number must be at least 1. Keeping alive more activations will potentially allow + more overlap between the communication and compute streams at the cost of increasing memory usage. Keeping + alive fewer activations will conserve memory, but may cause poor overlap between the streams, increasing + runtime. + + Raises: + ValueError: if `max_fwd_stash_size` is not at least `1`. + + Example: + ```python + >>> with OffloadActivations(): + ... outputs = model(inputs, labels=labels) + >>> loss = outputs.loss + >>> loss.backward() + ``` + """ + + def __init__( + self, + use_pin_memory: bool = True, + use_streams: bool = True, + min_offload_size: int = 1024, + max_fwd_stash_size: int = 5, + ) -> None: + self.use_streams = use_streams + + self.min_tensor_size_bytes = min_offload_size # we don't want to bother with small tensors + self.tracker = {} # tensor_id => (new_tensor, if_modified) ---> track what saved/offloaded tensors are where + self.tensor_id = 0 + self.is_first_forward_call = True + self.is_first_backward_call = True + self.is_first_forward_pass = True + + # Storage deduplication: maps storage key to tensor_id to avoid offloading same storage multiple times + self.storage_to_tensor_id = {} + + # Parameter filtering: track parameter storage pointers to skip them during offloading + self.param_storages = set() + + # Managing cpu memory + self.use_pin_memory = use_pin_memory + self.virtual_memory_safe_pct = 60 # we should not exceed this percentage of memory + + self.accelerator_type = ( + torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda" + ) + # NOTE: xpu doesn't have `default_stream` API, use `current_stream` instead + if self.accelerator_type == "xpu": # comp stream + self.s0 = torch.xpu.current_stream() + elif is_torch_npu_available() and self.accelerator_type == "npu": + self.s0 = torch.npu.current_stream() + else: + self.s0 = torch.cuda.default_stream() + + # For streaming + if self.use_streams: + if self.accelerator_type == "xpu": # comms stream + self.s1 = torch.xpu.Stream() + elif self.accelerator_type == "npu": + self.s1 = torch.npu.Stream() + else: + self.s1 = torch.cuda.Stream() + self.fwd_stash = {} # tensor_id => (activation, ev1) + if max_fwd_stash_size < 1: + raise ValueError(f"max_fwd_stash_size should be at least 1 but is {max_fwd_stash_size}") + self.max_fwd_stash_size = max_fwd_stash_size + self.bwd_tensor_stash = {} # tensor_id => activation + self.bwd_ev_stash = {} # tensor_id => ev0 + self.curr_graph_id = None + self.curr_autograd_node = None + + # -------- platform util functions -------- # + def verify_sufficient_virtual_memory(): + curr_pct = get_cpu_ram_pct() + if curr_pct > self.virtual_memory_safe_pct: + logger.warning(f"{curr_pct=}% > {self.virtual_memory_safe_pct=}% of virtual memory used") + + def get_cpu_ram_pct() -> float: + # get the percentage of memory used by the system + return psutil.virtual_memory().percent + + def get_tensor_id() -> int: + # create a unique id for each tensor we are managing + self.tensor_id += 1 + return self.tensor_id + + def get_num_bytes_tensor(x: torch.Tensor) -> int: + # get the number of bytes in a tensor, for memory management purposes + return x.element_size() * x.nelement() # x.element_size() * x._base_storage().nbytes() + + # -------- core pack / unpack work -------- # + def pack_tensor(activation: torch.Tensor) -> int: + # activations are passed in during forward pass - from here we take over and return a unique id + if self.is_first_forward_call: + if len(self.tracker) != 0: + raise ValueError("Backward pass should have cleared tracker of all tensors") + + # set training phase trackers + self.is_first_forward_call = False + self.is_first_backward_call = True + # Reset deduplication map for new forward pass + self.storage_to_tensor_id = {} + + # query for basic tensor info + num_bytes = get_num_bytes_tensor(activation) + tensor_id = get_tensor_id() + + # Check for tensor deduplication using storage pointer + # If this storage is already being tracked, we still create a new tensor_id + # but don't offload again (just keep the tensor in GPU) + storage_key = _get_unique_tensor_key(activation) + if storage_key in self.storage_to_tensor_id: + # Storage already offloaded - don't offload again, just track the reference + self.tracker[tensor_id] = (activation, False, None, None, None) # Keep on GPU, don't offload + return tensor_id + + # Check if tensor is on CPU (skip offloading) + if activation.device.type not in ["cuda", "xpu", "npu"]: + self.tracker[tensor_id] = (activation, False, None, None, None) + return tensor_id + + # Check if tensor is too small + if num_bytes < self.min_tensor_size_bytes: + self.tracker[tensor_id] = (activation, False, None, None, None) + return tensor_id + + # Check if tensor is a parameter or buffer + if isinstance(activation, torch.nn.Parameter) or ( + hasattr(torch.nn, "Buffer") and isinstance(activation, torch.nn.Buffer) + ): + self.tracker[tensor_id] = (activation, False, None, None, None) + return tensor_id + + # Check if tensor is an FP8 tensor (TorchAO) - skip offloading as they're already compressed + tensor_class_name = type(activation).__name__ + if tensor_class_name in ["Float8TrainingTensor", "ScaledMMConfig", "LinearMMConfig"]: + self.tracker[tensor_id] = (activation, False, None, None, None) + return tensor_id + + # Check if tensor storage is a model parameter (for FSDP compatibility) + try: + # Extract actual tensor for DTensor + check_tensor = activation + if DTensor is not None and isinstance(activation, DTensor) and hasattr(activation, "_local_tensor"): + check_tensor = activation._local_tensor + + if check_tensor.untyped_storage().data_ptr() in self.param_storages: + self.tracker[tensor_id] = (activation, False, None, None, None) + return tensor_id + except (RuntimeError, AttributeError): + # If we can't get data_ptr, skip this check + pass + + # Tensor qualifies for offloading + if self.use_streams: + # First, sync back and dereference previously offloaded tensors + # as the offloading should be done sufficiently long ago. + for id in list(self.fwd_stash.keys()): + if id <= tensor_id - self.max_fwd_stash_size: + _, ev = self.fwd_stash[id] + self.s0.wait_event(ev) + del self.fwd_stash[id] + else: + break + + # Sync in, offload, and add an event to sync back later + self.s1.wait_stream(self.s0) + + stream = self.s1 if self.use_streams else self.s0 + if self.accelerator_type == "xpu": + stream_ctx = torch.xpu.stream(stream) + elif self.accelerator_type == "npu": + stream_ctx = torch.npu.stream(stream) + else: + stream_ctx = torch.cuda.stream(stream) + with stream_ctx: + # Save original stride and shape information + original_stride = activation.stride() + original_storage_offset = activation.storage_offset() + original_shape = activation.size() + + # Check if tensor has broadcast dimensions (stride == 0) + # If so, copy the underlying storage directly instead of materializing the broadcast + has_broadcast = 0 in original_stride + + if has_broadcast: + # Copy only the actual underlying storage, not the materialized broadcast + # Create CPU tensor with same storage size as original + storage_size = activation.untyped_storage().size() + cpu_storage = torch.empty( + storage_size // activation.element_size(), + dtype=activation.dtype, + pin_memory=self.use_pin_memory, + device="cpu", + ) + # Copy the raw storage + cpu_storage_view = torch.as_strided( + activation, size=(storage_size // activation.element_size(),), stride=(1,), storage_offset=0 + ) + cpu_storage.copy_(cpu_storage_view, non_blocking=True) + cpu_tensor = cpu_storage + else: + # No broadcast - use normal contiguous copy + # .contiguous() can be a no-op for contiguous views with + # non-zero storage_offset. Force a clone for those views + # so later as_strided reconstruction stays in bounds. + if not activation.is_contiguous() or activation.storage_offset() != 0: + if activation.storage_offset() != 0: + activation = activation.clone(memory_format=torch.contiguous_format) + else: + activation = activation.contiguous() + original_stride = activation.stride() + original_storage_offset = activation.storage_offset() + cpu_tensor = torch.empty_like(activation, pin_memory=self.use_pin_memory, device="cpu") + cpu_tensor.copy_(activation, non_blocking=True) + + # Store CPU tensor along with stride information + self.tracker[tensor_id] = ( + cpu_tensor, + True, # True = (in future) modified + original_stride, # Save original GPU stride + original_storage_offset, # Save original storage offset + original_shape, # Save original shape for broadcast restoration + ) + + if self.use_streams: + event = self.s1.record_event() + + # Stash to keep activation alive til s1 is done + self.fwd_stash[tensor_id] = (activation, event) + + # Track this storage for deduplication + self.storage_to_tensor_id[storage_key] = tensor_id + + return tensor_id + + def unpack_tensor_single_stream(unpack_tensor_id: int) -> torch.Tensor: + # backward pass - we are called with the tensor_id, which + # we will use to retrieve the saved/offloaded tensor + if self.is_first_backward_call: + if self.is_first_forward_pass: + self.is_first_forward_pass = False + if self.use_pin_memory: + verify_sufficient_virtual_memory() + + self.is_first_backward_call = False + + if unpack_tensor_id not in self.tracker: + raise ValueError(f"Untracked tensor with id {unpack_tensor_id}") + + ( + maybe_accelerator_tensor, + modified, + original_stride, + original_storage_offset, + original_shape, + ) = self.tracker[unpack_tensor_id] + + if modified: + # Restore tensor to GPU + accelerator_tensor = maybe_accelerator_tensor.to(self.accelerator_type, non_blocking=True) + # Restore original stride if we saved it (handles both broadcast and non-broadcast cases) + if original_stride is not None: + accelerator_tensor = torch.as_strided( + accelerator_tensor, + size=original_shape, + stride=original_stride, + storage_offset=original_storage_offset, + ) + maybe_accelerator_tensor = accelerator_tensor + + # clear tensor from tracking + del self.tracker[unpack_tensor_id] + # Only set is_first_forward_call to True when all tensors have been unpacked + if len(self.tracker) == 0: + self.is_first_forward_call = True + return maybe_accelerator_tensor + + def unpack_tensor_with_streams(unpack_tensor_id: int) -> torch.Tensor: + # backward pass - we are called with the tensor_id, which + # we will use to retrieve the saved/offloaded tensor + if self.is_first_backward_call: + self.curr_graph_id = torch._C._current_graph_task_id() + + def wait_and_del_remaining_references() -> None: + for id in list(self.bwd_tensor_stash.keys()): + if id in self.bwd_ev_stash: + event = self.bwd_ev_stash[id] + self.s1.wait_event(event) + del self.bwd_tensor_stash[id] + + # Register a callback to the end of autograd to clean everything up + torch.autograd.variable.Variable._execution_engine.queue_callback(wait_and_del_remaining_references) + + if self.is_first_forward_pass: + self.is_first_forward_pass = False + if self.use_pin_memory: + verify_sufficient_virtual_memory() + + self.is_first_backward_call = False + + if unpack_tensor_id not in self.tracker: + raise ValueError(f"untracked tensor with id {unpack_tensor_id}") + + ( + maybe_accelerator_tensor, + modified, + original_stride, + original_storage_offset, + original_shape, + ) = self.tracker[unpack_tensor_id] + + if modified: + # Get data on the current autograd node + graph_id = torch._C._current_graph_task_id() + node = torch._C._current_autograd_node() + prev_node_ids = [] + + # If we're on a new node, mark prev node's tensors to be freed later + if graph_id == self.curr_graph_id and self.curr_autograd_node != node: + self.curr_autograd_node = node + prev_node_ids = list(self.bwd_tensor_stash.keys()) + + brought_back_from_cpu = True + if unpack_tensor_id in self.fwd_stash: + maybe_accelerator_tensor = self.fwd_stash[unpack_tensor_id][0] + brought_back_from_cpu = False + else: + # Kick off the process to bring tensors back + if self.accelerator_type == "xpu": + stream_ctx = torch.xpu.stream(self.s1) + elif self.accelerator_type == "npu": + stream_ctx = torch.npu.stream(self.s1) + else: + stream_ctx = torch.cuda.stream(self.s1) + with stream_ctx: + # Restore tensor to GPU + accelerator_tensor = maybe_accelerator_tensor.to(self.accelerator_type, non_blocking=True) + # Restore original stride if we saved it (handles both broadcast and non-broadcast cases) + if original_stride is not None: + accelerator_tensor = torch.as_strided( + accelerator_tensor, + size=original_shape, + stride=original_stride, + storage_offset=original_storage_offset, + ) + maybe_accelerator_tensor = accelerator_tensor + + # Tell comp stream to wait for the info to be loaded before executing + self.s0.wait_stream(self.s1) + + # Stash the tensor to keep memory alive until compute stream is complete + self.bwd_tensor_stash[unpack_tensor_id] = maybe_accelerator_tensor + + # Note: [Track views of the unpacked] + # Why do we get the use count of the unpacked tensor here? We want an + # initial count to compare to later, during the post-hook of the + # backward node, when we need to decide whether we're allowed to free + # the tensor yet. In what obscure cases must we delay freeing the + # tensor (and thus call record_stream)? + # 1. Any of the outputs of the backward node is a view of the unpacked + # tensor. + # 2. In the case that this unpacked tensor will be used in a + # checkpointed region, if one of the recomputed saved tensors ends + # up as a view of the unpacked tensor. + # 3. The user abuses the system somehow and manually relies on the + # unpacked tensor to exist after the backward node has executed. + if self.accelerator_type == "npu": + storage_refcount = torch_npu._C._storage_Use_Count( + maybe_accelerator_tensor.untyped_storage()._cdata + ) + else: + storage_refcount = torch._C._storage_Use_Count( + maybe_accelerator_tensor.untyped_storage()._cdata + ) + + def hook(outputs, inputs): + # create events for the current node inputs/outputs if they were streamed in + if brought_back_from_cpu: + # See Note: [Track views of the unpacked] + # IF any of the outputs is a view of the tensor, OR if a view of + # the tensor has been saved as a part of checkpoint's recompute + # process, OR the user has abusedly incurred a reference on the + # unpacked tensor, THEN the tensor might be used later and we + # cannot presume to delete it after only the current node is + # done! So we use our frenemy, record_stream, to ensure the + # Tensor stays unmessed with until it's done getting used in the + # compute stream (s0 here). Note that the con here is we introduce + # non-deterministic (thus higher) memory usage, but this case + # should not happen often. + # Check if tensor still exists (might have been cleaned up by a previous node) + if unpack_tensor_id in self.bwd_tensor_stash: + unpacked_tensor = self.bwd_tensor_stash[unpack_tensor_id] + if self.accelerator_type == "npu": + storage_count = torch_npu._C._storage_Use_Count( + unpacked_tensor.untyped_storage()._cdata + ) + else: + storage_count = torch._C._storage_Use_Count(unpacked_tensor.untyped_storage()._cdata) + if storage_count > storage_refcount: + unpacked_tensor.record_stream(self.s0) + del self.bwd_tensor_stash[unpack_tensor_id] + else: + event = self.s0.record_event() + self.bwd_ev_stash[unpack_tensor_id] = event + + # if there are still things in the fwd_stash, get rid of them as we're in bwd now + for id in list(self.fwd_stash.keys()): + _, ev = self.fwd_stash[id] + self.s0.wait_event(ev) + del self.fwd_stash[id] + + # wait on prev node's events and del those + for id in prev_node_ids: + # Only wait on events that exist (some tensors may have used record_stream instead) + if id in self.bwd_ev_stash: + event = self.bwd_ev_stash[id] + self.s1.wait_event(event) + del self.bwd_ev_stash[id] + if id in self.bwd_tensor_stash: + del self.bwd_tensor_stash[id] + + return outputs + + node.register_hook(hook) + + # clear tensor from tracking + del self.tracker[unpack_tensor_id] + # Only set is_first_forward_call to True when all tensors have been unpacked + if len(self.tracker) == 0: + self.is_first_forward_call = True + return maybe_accelerator_tensor + + unpack_tensor = unpack_tensor_with_streams if self.use_streams else unpack_tensor_single_stream + super().__init__(pack_tensor, unpack_tensor) + + def update_model_params(self, model: nn.Module): + """ + Update the set of parameter storage pointers from the model. This allows filtering out model parameters during + offloading, which is especially important for FSDP models where parameters may not be detected by isinstance + checks. + + For FSDP v2, this method handles DTensor parameters which may be sharded across ranks and not have valid local + storage on all ranks. We extract the local tensor from DTensors using _local_tensor when available. + + Args: + model: The model whose parameters should be tracked + """ + param_storages = set() + + for p in model.parameters(): + # For FSDP v2: extract local tensor from DTensor + actual_tensor = p + if DTensor is not None and isinstance(p, DTensor) and hasattr(p, "_local_tensor"): + actual_tensor = p._local_tensor + + # Try to get storage pointer + try: + storage_ptr = actual_tensor.untyped_storage().data_ptr() + if storage_ptr != 0: + param_storages.add(storage_ptr) + except RuntimeError: + # Parameter doesn't have accessible storage (e.g., FSDP v2 sharded without local shard, FP8 parameters) + # These will be caught by other checks (isinstance for Parameter, class name for FP8) + continue + + self.param_storages = param_storages + + def __enter__(self): + """Clear stale state and release BNB buffers before entering. + + By the time __enter__ is called, the previous forward/backward has already completed, so anything still in + tracker, storage_to_tensor_id, or the stashes is leaked and safe to drop. + + Two leak paths are handled: + 1. MoE + sample_packing + torch.compile: dynamic expert routing may leave saved tensors on subgraphs whose + backward nodes never execute, so the unpack-then-delete logic never fires. tracker/stashes from the previous + step survive into the next. + 2. QLoRA BNB dequantization buffers: tracker retains references to tensors sharing allocator blocks with BNB + buffers, and the allocator cache is never flushed between steps (~0.6 GiB/step, OOM after 30-40). + + Returns super().__enter__() to register pack/unpack hooks via saved_tensors_hooks (PyTorch autograd engine). + """ + self.tracker.clear() + self.storage_to_tensor_id.clear() + self.tensor_id = 0 + self.is_first_forward_call = True + self.is_first_backward_call = True + if self.use_streams: + self.bwd_tensor_stash.clear() + self.bwd_ev_stash.clear() + self.fwd_stash.clear() + if "bitsandbytes" in sys.modules: + if self.accelerator_type == "xpu": + torch.xpu.empty_cache() + elif is_torch_npu_available() and self.accelerator_type == "npu": + torch.npu.empty_cache() + else: + torch.cuda.empty_cache() + return super().__enter__() + + def __exit__(self, *args, **kwargs): + """Sync streams and clear stashes before parent cleanup. + + try/finally ensures the saved_tensors_hooks parent cleanup runs even if stream sync raises — otherwise hooks + stay permanently installed, creating a silent memory leak. + """ + try: + if self.use_streams: + self.s0.synchronize() + self.s1.synchronize() + self.bwd_tensor_stash.clear() + self.bwd_ev_stash.clear() + self.fwd_stash.clear() + finally: + result = super().__exit__(*args, **kwargs) + return result + + +class NoOpManager(saved_tensors_hooks): + """ + A `saved_tensors_hook` manager used to disable any other `saved_tensors_hook` manager applied before. This relies + on the behavior that only the most recently registered `saved_tensors_hook` will run. + + One example usage is to opt a local region of code out of activations offloading, which is usually applied globally + to best track state. + """ + + def __init__(self) -> None: + def noop(tensor): + return tensor + + super().__init__(noop, noop) + + +def get_act_offloading_ctx_manager( + model: nn.Module, + use_pin_memory: bool = True, + use_streams: bool = True, + min_offload_size: int = 1024, + max_fwd_stash_size: int = 5, + warn_if_no_head: bool = True, +) -> OffloadActivations: + """ + Returns the activation offloading context manager for the model. All but the last output Linear in every step will + be offloaded. + + If activation offloading is enabled, we return the OffloadActivations context manager. If activation offloading is + disabled, we return a NoOpManager context manager. + + Args: + model (`nn.Module`): + Model to wrap with the activation offloading context manager. + use_pin_memory (`bool`, *optional*, defaults to `True`): + Whether to offloaded Tensor will be placed in pinned memory on the CPU. Pinned memory allows the Tensor to + be moved back onto GPU more quickly but is a limited resource. + use_streams (`bool`, *optional*, defaults to `True`): + Whether to use streams for performance optimization where the communications get overlapped with the + computation. Requires a torch build after torch-2.5.0. + min_offload_size (`int`, *optional*, defaults to `1024`): + Minimum number of bytes a Tensor must be in order to qualify for offloading. If the tensor is too small, we + do not want to waste bandwidth and resources moving it to CPU and back. + max_fwd_stash_size (`int`, *optional*, defaults to `5`): + Maximum size of the forward stash, or the maximum number of consecutive activations to keep alive during + the forward pass. This number must be at least 1. Keeping alive more activations will potentially allow + more overlap between the communication and compute streams at the cost of increasing memory usage. Keeping + alive fewer activations will conserve memory, but may cause poor overlap between the streams, increasing + runtime. + warn_if_no_head (`bool`, *optional*, defaults to `True`): + Whether to warn if no output head is detected. If set to `False`, no warning will be raised if no output + head is detected. + + Returns: + `contextlib.ContextDecorator`: + Activation offloading context manager for the model. + """ + activations_handling_ctx = OffloadActivations( + use_pin_memory=use_pin_memory, + use_streams=use_streams, + min_offload_size=min_offload_size, + max_fwd_stash_size=max_fwd_stash_size, + ) + + # Update parameter storages to filter them during offloading (important for FSDP) + activations_handling_ctx.update_model_params(model) + + # Below is our hack to disable offloading the last output Linear in every + # step, as the cost for offloading the activation and then soon after bringing + # it back is expensive. + output_head_detected = False + noop_ctx = NoOpManager() + + # Try to get the actual model if it's wrapped + unwrapped_model = model + if hasattr(unwrapped_model, "module"): + unwrapped_model = unwrapped_model.module + # check for PEFT models + if hasattr(unwrapped_model, "base_model") and hasattr(unwrapped_model, "peft_config"): + unwrapped_model = unwrapped_model.base_model + + # Check for different types of output heads + if hasattr(unwrapped_model, "output"): + if isinstance(unwrapped_model.output, nn.Module): + unwrapped_model.output.register_forward_pre_hook(lambda *args: noop_ctx.__enter__()) + unwrapped_model.output.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True) + output_head_detected = True + elif hasattr(unwrapped_model.output, "linear") and isinstance(unwrapped_model.output.linear, nn.Module): + unwrapped_model.output.linear.register_forward_pre_hook(lambda *args: noop_ctx.__enter__()) + unwrapped_model.output.linear.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True) + output_head_detected = True + + # Check for HuggingFace model output heads + elif hasattr(unwrapped_model, "lm_head"): + unwrapped_model.lm_head.register_forward_pre_hook(lambda *args: noop_ctx.__enter__()) + unwrapped_model.lm_head.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True) + output_head_detected = True + + # Check for decoder-based models + elif hasattr(unwrapped_model, "decoder"): + decoder = unwrapped_model.decoder + if hasattr(decoder, "output"): + decoder.output.register_forward_pre_hook(lambda *args: noop_ctx.__enter__()) + decoder.output.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True) + output_head_detected = True + # Some models have lm_head in the decoder + elif hasattr(decoder, "lm_head"): + decoder.lm_head.register_forward_pre_hook(lambda *args: noop_ctx.__enter__()) + decoder.lm_head.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True) + output_head_detected = True + + # Check for transformer models with final layer norm + elif hasattr(unwrapped_model, "final_layer_norm") or hasattr(unwrapped_model, "ln_f"): + final_norm = getattr(unwrapped_model, "final_layer_norm", None) or unwrapped_model.ln_f + final_norm.register_forward_pre_hook(lambda *args: noop_ctx.__enter__()) + final_norm.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True) + output_head_detected = True + + # Check for models with head module + elif hasattr(unwrapped_model, "head") and isinstance(unwrapped_model.head, nn.Module): + unwrapped_model.head.register_forward_pre_hook(lambda *args: noop_ctx.__enter__()) + unwrapped_model.head.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True) + output_head_detected = True + + if not output_head_detected and warn_if_no_head: + logger.warning( + "During activation offloading, no output head was detected. If your model has an output head, it will be " + "offloaded. This usually greatly slows training, given the large vocabulary size. To change this " + "behavior, set your output head as model.output and make it an nn.Module. You can disable this warning by " + "passing `warn_if_no_head=False`." + ) + + # Disable offloading for any Liger modules + for name, module in unwrapped_model.named_modules(): + if "liger" in name.lower(): + module.register_forward_pre_hook(lambda *args: noop_ctx.__enter__()) + module.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True) + + return activations_handling_ctx diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/models/utils.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/models/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..20f336b7f087ee2e0ffbde61f86ed8f1acb6e522 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/models/utils.py @@ -0,0 +1,406 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import itertools +import warnings +from collections.abc import Callable +from contextlib import contextmanager +from copy import deepcopy +from typing import TYPE_CHECKING, Any + +import accelerate +import torch.nn as nn +import transformers +from accelerate import Accelerator +from packaging.version import Version +from torch.distributed.fsdp import FSDPModule +from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP +from transformers import GenerationConfig, PreTrainedModel + +from ..import_utils import suppress_experimental_warning + + +with suppress_experimental_warning(): + from ..experimental.utils import create_reference_model as _create_reference_model + + +if Version(accelerate.__version__) >= Version("1.11.0"): + from accelerate.utils.fsdp_utils import get_parameters_from_modules + +if TYPE_CHECKING: + from deepspeed.runtime.engine import DeepSpeedEngine + from torch.nn import Module + from torch.nn.parallel.distributed import DistributedDataParallel + + +def remove_hooks(model: "DeepSpeedEngine") -> None: + """Removes the optimizer hooks from a DeepSpeed ZeRO-3 model.""" + if not hasattr(model, "optimizer"): # before the first training step, the model has no optimizer + return + if model.optimizer is not None and hasattr(model.optimizer, "parameter_offload"): + optimizer_offload = model.optimizer.parameter_offload + elif model.optimizer is not None: + optimizer_offload = model.optimizer + else: + raise RuntimeError("The model optimizer is None, which is not yet supported.") + + for param in iter_params(optimizer_offload.module, recurse=True): + param.ds_active_sub_modules.clear() + + for hook in optimizer_offload.forward_hooks: + hook.remove() + for hook in optimizer_offload.backward_hooks: + hook.remove() + + optimizer_offload.forward_hooks = [] + optimizer_offload.backward_hooks = [] + + +def get_all_parameters(sub_module, recurse=False): + return itertools.chain(sub_module.named_parameters(recurse=recurse), sub_module.ds_external_parameters()) + + +def iter_params(module, recurse=False): + return [param for _, param in get_all_parameters(module, recurse)] + + +def add_hooks(model: "DeepSpeedEngine") -> None: + """Adds the optimizer hooks from a DeepSpeed ZeRO-3 model.""" + import deepspeed + + if not hasattr(model, "optimizer"): # before the first training step, the model has no optimizer + return + if model.optimizer is not None and hasattr(model.optimizer, "parameter_offload"): + optimizer_offload = model.optimizer.parameter_offload + elif model.optimizer is not None: + optimizer_offload = model.optimizer + else: + raise RuntimeError("The model optimizer is None, which is not yet supported.") + + # Invalidate parameter coordinator trace to prevent stale state + # after generation forward passes (fixes ZeRO-3 + GKD compatibility) + if hasattr(optimizer_offload, "param_coordinator"): # param_coordinator only exists in ZeRO stage 3 + coordinator = optimizer_offload.param_coordinator + # Only invalidate if trace is not already invalid + if not coordinator.is_invalid_trace(): + coordinator._invalidate_trace() + + if Version(deepspeed.__version__) >= Version("0.16.4"): + # Account for renaming in https://github.com/deepspeedai/DeepSpeed/pull/6847 + optimizer_offload._register_deepspeed_module(optimizer_offload.module) + else: + optimizer_offload._register_hooks_recursively(optimizer_offload.module) + + +@contextmanager +def _unwrap_model_for_generation( + model: "DistributedDataParallel | DeepSpeedEngine", + accelerator: "Accelerator", + gather_deepspeed3_params: bool = True, +): + """ + Context manager to unwrap distributed or accelerated models for generation tasks. + + Args: + model (`DistributedDataParallel | DeepSpeedEngine`): + Model to be unwrapped. + accelerator ([`~accelerate.Accelerator`]): + Accelerator instance managing the model. + gather_deepspeed3_params (`bool`, *optional*, defaults to `True`): + Whether to gather weights for DeepSpeed ZeRO Stage 3 models. If `False`, skips parameter gathering, which + can be more memory-efficient but may lead to slower generation times. + + Yields: + Unwrapped model. + + Example: + ```python + >>> with _unwrap_model_for_generation(model, accelerator) as unwrapped_model: + ... generated_outputs = unwrapped_model.generate(input_ids) + ``` + """ + unwrapped_model = accelerator.unwrap_model(model) + is_gradient_checkpointing = unwrapped_model.is_gradient_checkpointing + if is_gradient_checkpointing: + unwrapped_model.gradient_checkpointing_disable() + from ..distributed import DistributedBackend + + if DistributedBackend(accelerator).is_zero3: + if not gather_deepspeed3_params: + yield accelerator.unwrap_model(model) + else: + import deepspeed + + with deepspeed.zero.GatheredParameters(model.parameters()): + remove_hooks(model) + yield accelerator.unwrap_model(model) + add_hooks(model) + else: + yield unwrapped_model + if is_gradient_checkpointing: + unwrapped_model.gradient_checkpointing_enable() + + +@contextmanager +def _override_model_generation_config(model, generation_kwargs=None): + """ + Context manager to temporarily override a model's generation_config with training config. + + This works around transformers' config merging logic that would otherwise overwrite values matching global defaults + with model-specific values (see upstream issue transformers#42762; fixed in transformers v5 by PR + `transformers#42702`). + + By temporarily setting the model's generation_config to match the passed generation_config, we avoid the conflict. + + The model's original generation_config is preserved outside this context, ensuring that saved/pushed models retain + their intended inference behavior. + + Args: + model: The model (typically unwrapped_model) whose generation_config to temporarily override. + generation_kwargs (dict): Generation kwargs to be used to override model's generation config. + """ + if ( + # Issue fixed in transformers v5 by PR transformers#42702 + Version(transformers.__version__) >= Version("5.0.0") + or generation_kwargs is None + or not hasattr(model, "generation_config") + ): + yield model + return + # If it is a PEFT model, override the underlying base model + if hasattr(model, "get_base_model"): + model = model.get_base_model() + # Keep original model generation_config + original_config = model.generation_config + # Create training-specific generation config from the model's original generation config + # Then overwrite it with the training-specific generation kwargs + generation_config = GenerationConfig.from_dict(model.generation_config.to_dict()) + generation_config.update(**generation_kwargs) + model.generation_config = generation_config + try: + yield + finally: + model.generation_config = original_config + + +@contextmanager +def unwrap_model_for_generation( + model: "DistributedDataParallel | DeepSpeedEngine", + accelerator: "Accelerator", + gather_deepspeed3_params: bool = True, + generation_kwargs: dict | None = None, +): + """ + Context manager to unwrap distributed or accelerated models for generation tasks. + + This function unwraps distributed models (FSDP, DeepSpeed) and optionally overrides the model's generation_config + temporarily during generation. This is useful for applying training-specific generation parameters without + permanently modifying the model's original generation_config. + + Args: + model (`DistributedDataParallel | DeepSpeedEngine`): + Model to be unwrapped. + accelerator ([`~accelerate.Accelerator`]): + Accelerator instance managing the model. + gather_deepspeed3_params (`bool`, *optional*, defaults to `True`): + Whether to gather weights for DeepSpeed ZeRO Stage 3 models. If `False`, skips parameter gathering, which + can be more memory-efficient but may lead to slower generation times. + generation_kwargs (dict, *optional*): + If provided, temporarily overrides the model's generation_config during generation. The original config is + automatically restored when exiting the context. This is useful for using different generation parameters + during training vs. inference. + + Yields: + Unwrapped model with optionally overridden generation_config. + """ + with ( + _unwrap_model_for_generation( + model, accelerator, gather_deepspeed3_params=gather_deepspeed3_params + ) as unwrapped_model, + _override_model_generation_config(unwrapped_model, generation_kwargs=generation_kwargs), + ): + yield unwrapped_model + + +def prepare_deepspeed(model: "Module", accelerator: "Accelerator"): + """Prepares the model for DeepSpeed inference or evaluation by initializing it with the appropriate configuration. + + Adapted from accelerate: + https://github.com/huggingface/accelerate/blob/739b135f8367becb67ffaada12fe76e3aa60fefd/src/accelerate/accelerator.py#L1473 + """ + import deepspeed # local import (instead of top-level) to avoid DS init interfering with other backends (like vllm): https://github.com/deepspeedai/DeepSpeed/issues/7252 + + deepspeed_plugin = accelerator.state.deepspeed_plugin + config_kwargs = deepcopy(deepspeed_plugin.deepspeed_config) + stage = config_kwargs["zero_optimization"]["stage"] + + if model is not None: + hidden_size = ( + max(model.config.hidden_sizes) + if getattr(model.config, "hidden_sizes", None) + else getattr(model.config, "hidden_size", None) + ) + if hidden_size is not None and stage == 3: + # Note that `stage3_prefetch_bucket_size` can produce DeepSpeed messages like: `Invalidate trace cache + # @ step 0: expected module 1, but got module 0` + # This is expected and is not an error, see: https://github.com/microsoft/DeepSpeed/discussions/4081 + config_kwargs.update( + { + "zero_optimization.reduce_bucket_size": hidden_size * hidden_size, + "zero_optimization.stage3_param_persistence_threshold": 10 * hidden_size, + "zero_optimization.stage3_prefetch_bucket_size": 0.9 * hidden_size * hidden_size, + } + ) + + # If ZeRO-3 is used, we shard both the active and reference model. + # Otherwise, we assume the reference model fits in memory and is initialized on each device with ZeRO + # disabled (stage 0) + if stage != 3: + config_kwargs["zero_optimization"]["stage"] = 0 + model, *_ = deepspeed.initialize(model=model, config=config_kwargs) + model.eval() + return model + + +def prepare_fsdp(model, accelerator: Accelerator) -> FSDP | FSDPModule: + # Check if the model is already a FSDP model due to `Manual Wrapping` and if so, don't wrap it again + if not isinstance(model, (FSDP, FSDPModule)): + fsdp_plugin = accelerator.state.fsdp_plugin + if fsdp_plugin.fsdp_version == 1: + accelerator.state.fsdp_plugin.set_auto_wrap_policy(model) + kwargs = { + "sharding_strategy": fsdp_plugin.sharding_strategy or fsdp_plugin.reshard_after_forward, + "cpu_offload": fsdp_plugin.cpu_offload, + "auto_wrap_policy": fsdp_plugin.auto_wrap_policy, + "mixed_precision": fsdp_plugin.mixed_precision_policy, + "sync_module_states": fsdp_plugin.sync_module_states, + "backward_prefetch": fsdp_plugin.backward_prefetch, + "forward_prefetch": fsdp_plugin.forward_prefetch, + "use_orig_params": fsdp_plugin.use_orig_params, + "param_init_fn": fsdp_plugin.param_init_fn, + "ignored_modules": fsdp_plugin.ignored_modules, + "limit_all_gathers": fsdp_plugin.limit_all_gathers, + "device_id": accelerator.device, + } + model = FSDP(model, **kwargs) + elif fsdp_plugin.fsdp_version == 2: + from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard + + mesh = getattr(accelerator, "torch_device_mesh", None) + if Version(accelerate.__version__) >= Version("1.11.0"): + ignored_params = get_parameters_from_modules(fsdp_plugin.ignored_modules, model, accelerator.device) + else: + warnings.warn( + "FSDP version 2 is being used with accelerate version < 1.11.0, which may lead to incorrect " + "handling of ignored modules. Please upgrade accelerate to v1.11.0 or later for proper support." + ) + ignored_params = None + fully_shard( + model, + reshard_after_forward=fsdp_plugin.reshard_after_forward, + offload_policy=fsdp_plugin.cpu_offload, + # `fully_shard` doesn't accept `None` in case of `MixedPrecisionPolicy` + mp_policy=fsdp_plugin.mixed_precision_policy or MixedPrecisionPolicy(), + mesh=mesh[tuple(accelerator.parallelism_config.fsdp_dim_names)] if mesh is not None else None, + ignored_params=ignored_params, + ) + else: + raise ValueError(f"FSDP version {fsdp_plugin.fsdp_version} is not supported.") + model.eval() + return model + + +class _ForwardRedirection: + """Implements the `forward-redirection`. + + Taken from Pytorch-lightning: + https://github.com/Lightning-AI/pytorch-lightning/blob/02311d03fb982560246eead7c08104481fac9579/src/lightning/pytorch/strategies/strategy.py#L602 + + A method call to a wrapped module gets rerouted through the wrapper's `forward` method instead. + + """ + + def __call__( + self, wrapper_module: nn.Module, original_module: nn.Module, method: Callable, *args: Any, **kwargs: Any + ): + """Reroutes a method call through the `wrapper_module`'s `forward` method. + + Args: + wrapper_module: The module that has `original_module` wrapped. + original_module: The module that was wrapped inside `wrapper_module`. + method: The method that should be called on the `original_module` after inputs get + redirected through the `wrapper_module`'s `forward` method. + *args: The positional arguments to the `method`. They will get passed to a patched + `forward` method instead. + **kwargs: The keyword arguments to the `method`. They will get passed to a patched + `forward` method instead. + + """ + original_forward = original_module.forward + + def wrapped_forward(*_args: Any, **_kwargs: Any) -> Any: + # Unpatch ourselves immediately before calling the method `method_name` + # because itself may want to call the real `forward` + original_module.forward = original_forward # type: ignore[method-assign] + # Call the actual method e.g. `.training_step(...)` + out = method(*_args, **_kwargs) + self.on_after_inner_forward(wrapper_module, original_module) + return out + + # Patch the original_module's forward so we can redirect the arguments back to the real method + original_module.forward = wrapped_forward # type: ignore[method-assign] + + wrapper_output = wrapper_module(*args, **kwargs) + self.on_after_outer_forward(wrapper_module, original_module) + return wrapper_output + + def on_after_inner_forward(self, wrapper_module: nn.Module, original_module: nn.Module) -> None: + pass + + def on_after_outer_forward(self, wrapper_module: nn.Module, original_module: nn.Module) -> None: + pass + + +@contextmanager +def disable_gradient_checkpointing(model: PreTrainedModel, gradient_checkpointing_kwargs: dict | None = None): + """ + Temporarily disable gradient checkpointing, restoring the previous state afterward. + + Args: + model (`PreTrainedModel`): + Model for which to temporarily disable gradient checkpointing. + gradient_checkpointing_kwargs (`dict` or `None`, *optional*): + Additional kwargs for gradient checkpointing enabling. + """ + was_enabled = model.is_gradient_checkpointing + if was_enabled: + model.gradient_checkpointing_disable() + try: + yield + finally: + if was_enabled: + model.gradient_checkpointing_enable(gradient_checkpointing_kwargs) + + +def create_reference_model( + model: nn.Module, num_shared_layers: int | None = None, pattern: str | None = None +) -> nn.Module: + warnings.warn( + "The `create_reference_model` function is now located in `trl.experimental.utils`. Please update your " + "imports to `from trl.experimental.utils import create_reference_model`. This import path will be removed in " + "TRL 1.0.0.", + FutureWarning, + stacklevel=2, + ) + return _create_reference_model(model, num_shared_layers=num_shared_layers, pattern=pattern) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/py.typed b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/rewards/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/rewards/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0bf247a6f322cfdf78ef56f993b2d03ed49425b7 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/rewards/__init__.py @@ -0,0 +1,35 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys +from typing import TYPE_CHECKING + +from .._lazy_module import _LazyModule + + +_import_structure = { + "accuracy_rewards": ["accuracy_reward", "get_cosine_scaled_reward", "reasoning_accuracy_reward"], + "format_rewards": ["think_format_reward"], + "other_rewards": ["get_repetition_penalty_reward", "get_soft_overlong_punishment"], +} + + +if TYPE_CHECKING: + from .accuracy_rewards import accuracy_reward, get_cosine_scaled_reward, reasoning_accuracy_reward + from .format_rewards import think_format_reward + from .other_rewards import get_repetition_penalty_reward, get_soft_overlong_punishment + + +else: + sys.modules[__name__] = _LazyModule(__name__, __file__, _import_structure, module_spec=__spec__) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/rewards/accuracy_rewards.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/rewards/accuracy_rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..c78583c5ff060bc878ff973402660b19d76b0a92 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/rewards/accuracy_rewards.py @@ -0,0 +1,350 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import math +import threading +from collections.abc import Callable + +from ..import_utils import is_math_verify_available + + +if is_math_verify_available(): + from latex2sympy2_extended import NormalizationConfig + from math_verify import LatexExtractionConfig, parse, verify + + +def accuracy_reward( + completions: list[list[dict[str, str]]], + solution: list[str], + log_extra: Callable[[str, list], None] | None = None, + **kwargs, +) -> list[float | None]: + r""" + Reward function that checks if the completion matches the ground truth. + - If both gold and prediction are parseable → use math verification. + - If gold is not parseable → return `None` to skip the example. + + Args: + completions (`list[list[dict[str, str]]]`): + List of completions to be evaluated. Each completion must be a list of one message, i.e. a dictionary + containing the key `"content"` with the value being the text of the completion. + solution (`list[str]`): + List of the raw-text solutions to the questions/problems/prompts. + log_extra (`callable`, *optional*): + Callable to log extra columns to the completions table, provided automatically by the trainer. Defaults to + `None` to allow calling the function directly outside of a trainer (e.g., for testing). + **kwargs: + Additional keyword arguments. This function does not use them, but they are required in the function + signature to ensure compatibility with trainers like [`GRPOTrainer`]. + Example: + ```python + >>> from trl.rewards import accuracy_reward + + >>> solutions = [r"\frac{1}{3}", r"\frac{1}{3}"] + >>> completions = [ + ... [{"role": "assistant", "content": r"My answer is \boxed{\frac{1}{3}}"}], + ... [{"role": "assistant", "content": r"My answer is \boxed{\frac{1}{2}}"}], + ... ] + >>> accuracy_reward(completions, solutions) + [1.0, 0.0] + ``` + """ + if not is_math_verify_available(): + raise ImportError("Please install the `math_verify` package to use accuracy_reward") + + contents = [completion[0]["content"] for completion in completions] + rewards = [] + gold_parsed_strs = [] + answer_parsed_strs = [] + + # math_verify uses signal.alarm() for timeouts, which only works in the main thread. + # Disable timeouts when running in a non-main thread to avoid ValueError. + is_main_thread = threading.current_thread() is threading.main_thread() + parsing_timeout = None if not is_main_thread else 10 + verify_timeout = None if not is_main_thread else 5 + + # Suppress the "Timeout is disabled" warnings from math_verify when we intentionally disable timeouts + if not is_main_thread: + logging.getLogger("math_verify.parser").setLevel(logging.ERROR) + logging.getLogger("math_verify.grader").setLevel(logging.ERROR) + + for content, sol in zip(contents, solution, strict=True): + gold_parsed = parse(sol, parsing_timeout=parsing_timeout) + if len(gold_parsed) != 0: + # We require the answer to be provided in correct latex (no malformed operators) + answer_parsed = parse( + content, + extraction_config=[ + LatexExtractionConfig( + normalization_config=NormalizationConfig(units=True), + # Ensures that boxed is tried first + boxed_match_priority=0, + try_extract_without_anchor=False, + ) + ], + extraction_mode="first_match", + parsing_timeout=parsing_timeout, + ) + reward = float(verify(gold_parsed, answer_parsed, timeout_seconds=verify_timeout)) + gold_parsed_strs.append(str(gold_parsed)) + answer_parsed_strs.append(str(answer_parsed) if answer_parsed else "[unparseable]") + else: + # If the gold solution cannot be parsed, we assign `None` to skip this example + reward = None + gold_parsed_strs.append("[unparseable]") + answer_parsed_strs.append("[skipped]") + rewards.append(reward) + + if log_extra is not None: + log_extra("solution", list(solution)) + log_extra("gold_parsed", gold_parsed_strs) + log_extra("answer_parsed", answer_parsed_strs) + + return rewards + + +def get_cosine_scaled_reward( + max_len: int, + min_value_wrong: float = -1.0, + max_value_wrong: float = -0.5, + min_value_correct: float = 0.5, + max_value_correct: float = 1.0, +) -> Callable: + # docstyle-ignore + r""" + Reward function that scales a correctness reward by the completion length following a cosine schedule, to favor + concise reasoning. Reference: Appendix C.1 of the "Demystifying Long Chain-of-Thought Reasoning" paper + (https://huggingface.co/papers/2502.03373). + + Correctness is determined by math verification (as in [`~rewards.accuracy_reward`]), and the length is the number + of completion tokens. The reward interpolates along a cosine schedule between a short-completion and a + long-completion bound: + + $$ + R_{\text{cosine}}(y) = v_{\min} + \frac{1}{2}(v_{\max} - v_{\min})\left(1 + \cos\left(\frac{|y|}{L_{\max}}\pi\right)\right) + $$ + + For a **correct** completion, $(v_{\min}, v_{\max}) = (\texttt{min\_value\_correct}, \texttt{max\_value\_correct})$, + so a shorter completion is rewarded more. For a **wrong** completion, the bounds are swapped to + $(v_{\min}, v_{\max}) = (\texttt{max\_value\_wrong}, \texttt{min\_value\_wrong})$, so a shorter completion is + penalized more (a longer wrong completion is penalized less, preserving exploration). When the gold solution is not + parseable, the example is skipped (reward `None`), as in [`~rewards.accuracy_reward`]. + + Args: + max_len (`int`): + Maximum completion length (in tokens) used to normalize the cosine schedule, $L_{\max}$. + min_value_wrong (`float`, *optional*, defaults to `-1.0`): + Reward of a wrong completion at the shortest length. + max_value_wrong (`float`, *optional*, defaults to `-0.5`): + Reward of a wrong completion at the longest length. + min_value_correct (`float`, *optional*, defaults to `0.5`): + Reward of a correct completion at the longest length. + max_value_correct (`float`, *optional*, defaults to `1.0`): + Reward of a correct completion at the shortest length. + + Returns: + `Callable`: + A reward function that takes completions, their solutions and token ids, and returns a list of rewards + (`None` for examples with an unparseable gold solution). + + Example: + ```python + >>> from trl.rewards import get_cosine_scaled_reward + + >>> cosine_scaled_reward = get_cosine_scaled_reward(max_len=100) + >>> completions = [[{"content": r"\boxed{\frac{1}{3}}"}], [{"content": r"\boxed{\frac{1}{2}}"}]] + >>> solution = [r"\frac{1}{3}", r"\frac{1}{3}"] + >>> completion_ids = [[1] * 50, [1] * 50] # both completions are 50 tokens, half of max_len + >>> cosine_scaled_reward(completions, solution, completion_ids) + [0.75, -0.75] + ``` + """ + return _CosineScaledReward(max_len, min_value_wrong, max_value_wrong, min_value_correct, max_value_correct) + + +class _CosineScaledReward: + # Callable class rather than a closure so the reward stays picklable: the async GRPO rollout + # worker forwards reward funcs to a spawned child process, and closures can't be pickled. + __name__ = "cosine_scaled_reward" + + def __init__( + self, + max_len: int, + min_value_wrong: float, + max_value_wrong: float, + min_value_correct: float, + max_value_correct: float, + ): + self.max_len = max_len + self.min_value_wrong = min_value_wrong + self.max_value_wrong = max_value_wrong + self.min_value_correct = min_value_correct + self.max_value_correct = max_value_correct + + def __call__( + self, + completions: list[list[dict[str, str]]], + solution: list[str], + completion_ids: list[list[int]], + **kwargs, + ) -> list[float | None]: + is_correct = accuracy_reward(completions, solution) + rewards = [] + for correct, ids in zip(is_correct, completion_ids, strict=True): + if correct is None: + # Gold solution was not parseable; skip the example, as in accuracy_reward. + rewards.append(None) + continue + # Clamp to 1.0 so completions longer than max_len stay at the long-length bound: cos is periodic, so + # without clamping the schedule would climb back up past max_len and reward very long completions. + progress = min(len(ids) / self.max_len, 1.0) + cosine = math.cos(progress * math.pi) + if correct: + min_value, max_value = self.min_value_correct, self.max_value_correct + else: + # Swap the bounds so that a shorter wrong completion is penalized more than a longer one. + min_value, max_value = self.max_value_wrong, self.min_value_wrong + rewards.append(float(min_value + 0.5 * (max_value - min_value) * (1.0 + cosine))) + return rewards + + +def reasoning_accuracy_reward( + completions: list[list[dict[str, str]]], + solution: list[str], + reasoning_delimiters: list[str] | None = None, + log_extra: Callable[[str, list], None] | None = None, + **kwargs, +) -> list[float | None]: + r""" + Reward function that removes the reasoning content and checks if the final answer matches the ground truth. + - If both gold and prediction are parseable → use math verification. + - If gold is not parseable → return `None` to skip the example. + + Args: + completions (`list[list[dict[str, str]]]`): + List of completions to be evaluated. Each completion must be a list of one message, i.e. a dictionary + containing the key `"content"` with the value being the text of the completion. + solution (`list[str]`): + List of the raw-text solutions to the questions/problems/prompts. + reasoning_delimiters (`list[str]]`, *optional*): + List of strings indicating where the reasoning content ends. The final answer is assumed to be after the + last occurrence of any of these delimiters. If `None`, defaults to `[""]`. + log_extra (`callable`, *optional*): + Callable to log extra columns to the completions table, provided automatically by the trainer. Defaults to + `None` to allow calling the function directly outside of a trainer (e.g., for testing). + **kwargs: + Additional keyword arguments. This function does not use them, but they are required in the function + signature to ensure compatibility with trainers like [`GRPOTrainer`]. + Example: + ```python + >>> from trl.rewards import reasoning_accuracy_reward + + >>> reasoning_delimiters = [""] + >>> solutions = [r"\frac{1}{3}", r"\frac{1}{3}", r"\frac{1}{3}"] + >>> completions = [ + ... [ + ... { + ... "role": "assistant", + ... "content": r" Reasoning content The final answer is \boxed{\frac{1}{3}}", + ... } + ... ], + ... [ + ... { + ... "role": "assistant", + ... "content": r" Reasoning content The final answer is \boxed{\frac{1}{2}}", + ... } + ... ], + ... [ + ... { + ... "role": "assistant", + ... "content": r" Reasoning content with partial answers \boxed{\frac{1}{3}} but no final answer", + ... } + ... ], + ... ] + >>> reasoning_accuracy_reward(completions, solutions, reasoning_delimiters=reasoning_delimiters) + [1.0, 0.0, 0.0] + ``` + """ + if not is_math_verify_available(): + raise ImportError("Please install the `math_verify` package to use reasoning_accuracy_reward") + + if reasoning_delimiters is None: + # Use sensible defaults for majority of reasoning models + reasoning_delimiters = [""] + + rewards = [] + contents = [completion[0]["content"] for completion in completions] + gold_parsed_strs = [] + answer_parsed_strs = [] + + # math_verify uses signal.alarm() for timeouts, which only works in the main thread. + # Disable timeouts when running in a non-main thread to avoid ValueError. + is_main_thread = threading.current_thread() is threading.main_thread() + parsing_timeout = None if not is_main_thread else 10 + verify_timeout = None if not is_main_thread else 5 + + # Suppress the "Timeout is disabled" warnings from math_verify when we intentionally disable timeouts + if not is_main_thread: + logging.getLogger("math_verify.parser").setLevel(logging.ERROR) + logging.getLogger("math_verify.grader").setLevel(logging.ERROR) + + for content, sol in zip(contents, solution, strict=True): + # Split final answer from reasoning content + is_reasoning_complete = False + for delim in reasoning_delimiters: + if delim in content: + content = content.split(delim)[-1] + is_reasoning_complete = True + break + if not is_reasoning_complete: + # We assign zero reward instead of `None` to penalize incomplete reasoning + rewards.append(0.0) + gold_parsed_strs.append("[incomplete reasoning]") + answer_parsed_strs.append("[incomplete reasoning]") + continue + + gold_parsed = parse(sol, parsing_timeout=parsing_timeout) + if len(gold_parsed) != 0: + # We require the answer to be provided in correct latex (no malformed operators) + answer_parsed = parse( + content, + extraction_config=[ + LatexExtractionConfig( + boxed_match_priority=0, + normalization_config=NormalizationConfig( + units=True, + ), + try_extract_without_anchor=False, + ) + ], + extraction_mode="first_match", + parsing_timeout=parsing_timeout, + ) + reward = float(verify(gold_parsed, answer_parsed, timeout_seconds=verify_timeout)) + gold_parsed_strs.append(str(gold_parsed)) + answer_parsed_strs.append(str(answer_parsed) if answer_parsed else "[unparseable]") + else: + # If the gold solution cannot be parsed, we assign `None` to skip this example + reward = None + gold_parsed_strs.append("[unparseable]") + answer_parsed_strs.append("[skipped]") + rewards.append(reward) + + if log_extra is not None: + log_extra("solution", list(solution)) + log_extra("gold_parsed", gold_parsed_strs) + log_extra("answer_parsed", answer_parsed_strs) + + return rewards diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/rewards/format_rewards.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/rewards/format_rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..c737d0036b165ebf4a15e2c2558f82187e87038d --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/rewards/format_rewards.py @@ -0,0 +1,50 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import re + + +def think_format_reward(completions: list[list[dict[str, str]]], **kwargs) -> list[float]: + r""" + Reward function that checks if the reasoning process is enclosed within `""` and `""` tags. The + function returns a reward of 1.0 if the format is correct, otherwise 0.0. + + Args: + completions (`list[list[dict[str, str]]]`): + List of completions to be evaluated. Each completion must be a list of one message, i.e. a dictionary + containing the key `"content"` with the value being the text of the completion. + **kwargs: + Additional keyword arguments. This function does not use them, but they are required in the function + signature to ensure compatibility with trainers like [`GRPOTrainer`]. + + Returns: + `list[float]`: + A list of rewards, where each reward is 1.0 if the completion matches the expected format, otherwise 0.0. + + Example: + ```python + >>> from trl.rewards import think_format_reward + + >>> completions = [ + ... [{"content": "\nThis is my reasoning.\n\nThis is my answer."}], + ... [{"content": "\nThis is my reasoning.\nThis is my answer."}], + ... ] + >>> think_format_reward(completions) + [1.0, 0.0] + ``` + """ + pattern = r"^(?!.*)(.*?).*$" + completion_contents = [completion[0]["content"] for completion in completions] + matches = [re.match(pattern, content, re.DOTALL | re.MULTILINE) for content in completion_contents] + return [1.0 if match else 0.0 for match in matches] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/rewards/other_rewards.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/rewards/other_rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..4848d10d183a1fb1e21a35b631f1c68e6f678c34 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/rewards/other_rewards.py @@ -0,0 +1,138 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections.abc import Callable + + +def get_repetition_penalty_reward(ngram_size: int = 3, max_penalty: float = -1.0) -> Callable: + # docstyle-ignore + r""" + Reward function that penalizes repeated n-grams in a completion, used to discourage degenerate, repetitive text + (a common failure mode and reward-hacking strategy when length- or format-shaping rewards are used). Reference: + Appendix C.2 of the "Demystifying Long Chain-of-Thought Reasoning" paper (https://huggingface.co/papers/2502.03373). + + The penalty is proportional to the fraction of repeated n-grams in the completion: + + $$ + R_{\text{repetition}}(y) = \left(1 - \frac{\#\,\text{unique } n\text{-grams}}{\#\,\text{total } n\text{-grams}}\right) \times p + $$ + + where $p$ is `max_penalty`. A completion with no repeated n-gram gets a reward of `0.0`, while a fully repetitive + one approaches `max_penalty`. The n-grams are computed over the completion token ids (the paper applies the penalty + to repeated tokens), so the reward is tokenizer-defined and language-agnostic. Completions with fewer than + `ngram_size` tokens get a reward of `0.0`. + + Args: + ngram_size (`int`, *optional*, defaults to `3`): + Size of the token n-grams to consider. + max_penalty (`float`, *optional*, defaults to `-1.0`): + Most negative penalty, applied to a fully repetitive completion. Must be non-positive. + + Returns: + `Callable`: + A reward function that takes a list of completion token ids and returns a list of penalties (each in + `[max_penalty, 0.0]`). + + Example: + ```python + >>> from trl.rewards import get_repetition_penalty_reward + + >>> repetition_penalty = get_repetition_penalty_reward(ngram_size=2, max_penalty=-1.0) + >>> completion_ids = [[1, 2, 3, 4], [5, 5, 5, 5, 5]] + >>> repetition_penalty(completion_ids) + [0.0, -0.75] + ``` + """ + if max_penalty > 0: + raise ValueError(f"max_penalty {max_penalty} should not be positive") + return _RepetitionPenalty(ngram_size, max_penalty) + + +class _RepetitionPenalty: + # Callable class rather than a closure so the reward stays picklable: the async GRPO rollout + # worker forwards reward funcs to a spawned child process, and closures can't be pickled. + __name__ = "repetition_penalty_reward" + + def __init__(self, ngram_size: int, max_penalty: float): + self.ngram_size = ngram_size + self.max_penalty = max_penalty + + def __call__(self, completion_ids: list[list[int]], **kwargs) -> list[float]: + rewards = [] + for ids in completion_ids: + if len(ids) < self.ngram_size: + rewards.append(0.0) + continue + ngrams = list(zip(*[ids[i:] for i in range(self.ngram_size)], strict=False)) + scaling = 1 - len(set(ngrams)) / len(ngrams) + rewards.append(scaling * self.max_penalty if scaling else 0.0) + return rewards + + +def get_soft_overlong_punishment(max_completion_len: int, soft_punish_cache: int) -> Callable: + # docstyle-ignore + r""" + Reward function that penalizes overlong completions. It is used to penalize overlong completions, but not to reward + shorter completions. Reference: Eq. (13) from the DAPO paper (https://huggingface.co/papers/2503.14476) + + $$ + R_{\text{length}}(y) = \begin{cases} + 0, & |y| \le L_{\max} - L_{\text{cache}} \\ + \dfrac{(L_{\max} - L_{\text{cache}}) - |y|}{L_{\text{cache}}}, & L_{\max} - L_{\text{cache}} < |y| \le L_{\max} \\ + -1, & L_{\max} < |y| + \end{cases} + $$ + + Args: + max_completion_len (`int`): + Maximum length of the completion, \( L_{\max} \). + soft_punish_cache (`int`): + Minimum length of the completion, \( L_{\text{cache}} \). If set to `0`, no minimum length is applied. + + Example: + ```python + >>> from trl.rewards import get_soft_overlong_punishment + + >>> soft_overlong_punishment = get_soft_overlong_punishment(max_completion_len=100, soft_punish_cache=20) + >>> completion_ids = [[1] * 90] # simulating a completion with 90 tokens. 90 is between 80 and 100. + >>> soft_overlong_punishment(completion_ids) + >>> [-0.5] + ``` + """ + return _SoftOverlongPunishment(max_completion_len, soft_punish_cache) + + +class _SoftOverlongPunishment: + # Callable class rather than a closure so the reward stays picklable: the async GRPO rollout + # worker forwards reward funcs to a spawned child process, and closures can't be pickled. + # `__name__` mirrors the old inner-function name so metric logging keys are unchanged. + __name__ = "soft_overlong_punishment_reward" + + def __init__(self, max_completion_len: int, soft_punish_cache: int): + self.max_completion_len = max_completion_len + self.soft_punish_cache = soft_punish_cache + + def __call__(self, completion_ids: list[list[int]], **kwargs) -> list[float]: + rewards = [] + for ids in completion_ids: + completion_length = len(ids) + if completion_length <= self.max_completion_len - self.soft_punish_cache: + rewards.append(0.0) + elif self.max_completion_len - self.soft_punish_cache < completion_length <= self.max_completion_len: + rewards.append( + (self.max_completion_len - self.soft_punish_cache - completion_length) / self.soft_punish_cache + ) + else: + rewards.append(-1.0) + return rewards diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cb15e6cdfe5446affd20a72cd22a8c74c6f15e1e --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/__init__.py @@ -0,0 +1,29 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import TYPE_CHECKING + +from .._lazy_module import _LazyModule + + +_import_structure = { + "utils": ["DatasetMixtureConfig", "ScriptArguments", "TrlParser", "get_dataset", "init_zero_verbose"], +} + +if TYPE_CHECKING: + from .utils import DatasetMixtureConfig, ScriptArguments, TrlParser, get_dataset, init_zero_verbose +else: + import sys + + sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/_hf_argparser.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/_hf_argparser.py new file mode 100644 index 0000000000000000000000000000000000000000..f6b214154404dcc5f23791a577bdef85ac263eba --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/_hf_argparser.py @@ -0,0 +1,454 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +# Copied from: https://github.com/huggingface/transformers/blob/3a275d3581c0ecf962f7412aa764c2047331fd6b/src/transformers/hf_argparser.py +# This avoids an upstream latency issue: https://github.com/huggingface/transformers/issues/44273 +# - Moved yaml import inside function + + +import dataclasses +import json +import os +import sys +import types +from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError +from collections.abc import Callable, Iterable +from copy import copy +from enum import Enum +from inspect import isclass +from pathlib import Path +from typing import Any, Literal, NewType, Union, get_type_hints + + +DataClass = NewType("DataClass", Any) +DataClassType = NewType("DataClassType", Any) + + +# From https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse +def string_to_bool(v): + if isinstance(v, bool): + return v + if v.lower() in ("yes", "true", "t", "y", "1"): + return True + elif v.lower() in ("no", "false", "f", "n", "0"): + return False + else: + raise ArgumentTypeError( + f"Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive)." + ) + + +def _accept_none(inner: Callable[[str], Any]) -> Callable[[str], Any]: + """Wrap a type converter so `'none'` and `'null'` (case-insensitive) parse to Python `None`. + + Used for `T | None` fields so they can be set to `None` from the CLI (argparse's `type=int` rejects `'None'`). + Mirrors the case-insensitive convention of [`string_to_bool`]. + """ + + def parse(v: str) -> Any: + if v.lower() in ("none", "null"): + return None + return inner(v) + + parse.__name__ = getattr(inner, "__name__", "value") # so argparse error messages keep the inner type name + return parse + + +def make_choice_type_function(choices: list) -> Callable[[str], Any]: + """ + Creates a mapping function from each choices string representation to the actual value. Used to support multiple + value types for a single argument. + + Args: + choices (list): List of choices. + + Returns: + Callable[[str], Any]: Mapping function from string representation to actual value for each choice. + """ + str_to_choice = {str(choice): choice for choice in choices} + return lambda arg: str_to_choice.get(arg, arg) + + +def HfArg( + *, + aliases: str | list[str] | None = None, + help: str | None = None, + default: Any = dataclasses.MISSING, + default_factory: Callable[[], Any] = dataclasses.MISSING, + metadata: dict | None = None, + **kwargs, +) -> dataclasses.Field: + """Argument helper enabling a concise syntax to create dataclass fields for parsing with `HfArgumentParser`. + + Example comparing the use of `HfArg` and `dataclasses.field`: + ``` + @dataclass + class Args: + regular_arg: str = dataclasses.field(default="Huggingface", metadata={"aliases": ["--example", "-e"], "help": "This syntax could be better!"}) + hf_arg: str = HfArg(default="Huggingface", aliases=["--example", "-e"], help="What a nice syntax!") + ``` + + Args: + aliases (Union[str, list[str]], *optional*): + Single string or list of strings of aliases to pass on to argparse, e.g. `aliases=["--example", "-e"]`. + Defaults to None. + help (str, *optional*): + Help string to pass on to argparse that can be displayed with --help. Defaults to None. + default (Any, *optional*): + Default value for the argument. If not default or default_factory is specified, the argument is required. + Defaults to dataclasses.MISSING. + default_factory (Callable[[], Any], *optional*): + The default_factory is a 0-argument function called to initialize a field's value. It is useful to provide + default values for mutable types, e.g. lists: `default_factory=list`. Mutually exclusive with `default=`. + Defaults to dataclasses.MISSING. + metadata (dict, *optional*): Further metadata to pass on to `dataclasses.field`. Defaults to None. + + Returns: + Field: A `dataclasses.Field` with the desired properties. + """ + if metadata is None: + # Important, don't use as default param in function signature because dict is mutable and shared across function calls + metadata = {} + if aliases is not None: + metadata["aliases"] = aliases + if help is not None: + metadata["help"] = help + + return dataclasses.field(metadata=metadata, default=default, default_factory=default_factory, **kwargs) + + +class HfArgumentParser(ArgumentParser): + """ + This subclass of `argparse.ArgumentParser` uses type hints on dataclasses to generate arguments. + + The class is designed to play well with the native argparse. In particular, you can add more (non-dataclass backed) + arguments to the parser after initialization and you'll get the output back after parsing as an additional + namespace. Optional: To create sub argument groups use the `_argument_group_name` attribute in the dataclass. + + Args: + dataclass_types (`DataClassType` or `Iterable[DataClassType]`, *optional*): + Dataclass type, or list of dataclass types for which we will "fill" instances with the parsed args. + kwargs (`dict[str, Any]`, *optional*): + Passed to `argparse.ArgumentParser()` in the regular way. + """ + + dataclass_types: Iterable[DataClassType] + + def __init__(self, dataclass_types: DataClassType | Iterable[DataClassType] | None = None, **kwargs): + # Make sure dataclass_types is an iterable + if dataclass_types is None: + dataclass_types = [] + elif not isinstance(dataclass_types, Iterable): + dataclass_types = [dataclass_types] + + # To make the default appear when using --help + if "formatter_class" not in kwargs: + kwargs["formatter_class"] = ArgumentDefaultsHelpFormatter + super().__init__(**kwargs) + if dataclasses.is_dataclass(dataclass_types): + dataclass_types = [dataclass_types] + self.dataclass_types = list(dataclass_types) + for dtype in self.dataclass_types: + self._add_dataclass_arguments(dtype) + + @staticmethod + def _parse_dataclass_field(parser: ArgumentParser, field: dataclasses.Field): + # Long-option strings are conventionlly separated by hyphens rather + # than underscores, e.g., "--long-format" rather than "--long_format". + # Argparse converts hyphens to underscores so that the destination + # string is a valid attribute name. Hf_argparser should do the same. + long_options = [f"--{field.name}"] + if "_" in field.name: + long_options.append(f"--{field.name.replace('_', '-')}") + + kwargs = field.metadata.copy() + # field.metadata is not used at all by Data Classes, + # it is provided as a third-party extension mechanism. + if isinstance(field.type, str): + raise RuntimeError( + "Unresolved type detected, which should have been done with the help of " + "`typing.get_type_hints` method by default" + ) + + aliases = kwargs.pop("aliases", []) + if isinstance(aliases, str): + aliases = [aliases] + + origin_type = getattr(field.type, "__origin__", field.type) + accepts_none = False + if origin_type is Union or (hasattr(types, "UnionType") and isinstance(origin_type, types.UnionType)): + if str not in field.type.__args__ and ( + len(field.type.__args__) != 2 or type(None) not in field.type.__args__ + ): + raise ValueError( + "Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because" + " the argument parser only supports one type per argument." + f" Problem encountered in field '{field.name}'." + ) + if type(None) not in field.type.__args__: + # filter `str` in Union + field.type = field.type.__args__[0] if field.type.__args__[1] is str else field.type.__args__[1] + origin_type = getattr(field.type, "__origin__", field.type) + elif bool not in field.type.__args__: + # filter `NoneType` in Union (except for `Union[bool, NoneType]`) + field.type = ( + field.type.__args__[0] if isinstance(None, field.type.__args__[1]) else field.type.__args__[1] + ) + origin_type = getattr(field.type, "__origin__", field.type) + # Enable the `'none'`/`'null'` sentinel only when the inner type can't possibly accept those as + # legitimate string values (i.e. anything non-str). For str-typed fields, `'none'` may be a real + # value — e.g. `report_to`, whose CLI string `'none'` means "no integrations" downstream. + accepts_none = field.type is not str + + # A variable to store kwargs for a boolean field, if needed + # so that we can init a `no_*` complement argument (see below) + bool_kwargs = {} + if origin_type is Literal or (isinstance(field.type, type) and issubclass(field.type, Enum)): + if origin_type is Literal: + kwargs["choices"] = field.type.__args__ + else: + kwargs["choices"] = [x.value for x in field.type] + + kwargs["type"] = make_choice_type_function(kwargs["choices"]) + + if field.default is not dataclasses.MISSING: + kwargs["default"] = field.default + else: + kwargs["required"] = True + elif field.type is bool or field.type == bool | None: + # Copy the correct kwargs to use to instantiate a `no_*` complement argument below. + # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument + bool_kwargs = copy(kwargs) + + # Hack because type=bool in argparse does not behave as we want. + kwargs["type"] = string_to_bool + if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): + # Default value is False if we have no default when of type bool. + default = False if field.default is dataclasses.MISSING else field.default + # This is the value that will get picked if we don't include --{field.name} in any way + kwargs["default"] = default + # This tells argparse we accept 0 or 1 value after --{field.name} + kwargs["nargs"] = "?" + # This is the value that will get picked if we do --{field.name} (without value) + kwargs["const"] = True + elif isclass(origin_type) and issubclass(origin_type, list): + kwargs["type"] = field.type.__args__[0] + kwargs["nargs"] = "+" + if field.default_factory is not dataclasses.MISSING: + kwargs["default"] = field.default_factory() + elif field.default is dataclasses.MISSING: + kwargs["required"] = True + else: + kwargs["type"] = _accept_none(field.type) if accepts_none else field.type + if field.default is not dataclasses.MISSING: + kwargs["default"] = field.default + elif field.default_factory is not dataclasses.MISSING: + kwargs["default"] = field.default_factory() + else: + kwargs["required"] = True + parser.add_argument(*long_options, *aliases, **kwargs) + + # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. + # Order is important for arguments with the same destination! + # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down + # here and we do not need those changes/additional keys. + if field.default is True and (field.type is bool or field.type == bool | None): + bool_kwargs["default"] = False + parser.add_argument( + f"--no_{field.name}", + f"--no-{field.name.replace('_', '-')}", + action="store_false", + dest=field.name, + **bool_kwargs, + ) + + def _add_dataclass_arguments(self, dtype: DataClassType): + if hasattr(dtype, "_argument_group_name"): + parser = self.add_argument_group(dtype._argument_group_name) + else: + parser = self + + try: + type_hints: dict[str, type] = get_type_hints(dtype) + except NameError: + raise RuntimeError( + f"Type resolution failed for {dtype}. Try declaring the class in global scope or " + "removing line of `from __future__ import annotations` which opts in Postponed " + "Evaluation of Annotations (PEP 563)" + ) from None + + for field in dataclasses.fields(dtype): + if not field.init: + continue + field.type = type_hints[field.name] + self._parse_dataclass_field(parser, field) + + def parse_args_into_dataclasses( + self, + args=None, + return_remaining_strings=False, + look_for_args_file=True, + args_filename=None, + args_file_flag=None, + ) -> tuple[DataClass, ...]: + """ + Parse command-line args into instances of the specified dataclass types. + + This relies on argparse's `ArgumentParser.parse_known_args`. See the doc at: + docs.python.org/3/library/argparse.html#argparse.ArgumentParser.parse_args + + Args: + args: + List of strings to parse. The default is taken from sys.argv. (same as argparse.ArgumentParser) + return_remaining_strings: + If true, also return a list of remaining argument strings. + look_for_args_file: + If true, will look for a ".args" file with the same base name as the entry point script for this + process, and will append its potential content to the command line args. + args_filename: + If not None, will uses this file instead of the ".args" file specified in the previous argument. + args_file_flag: + If not None, will look for a file in the command-line args specified with this flag. The flag can be + specified multiple times and precedence is determined by the order (last one wins). + + Returns: + Tuple consisting of: + + - the dataclass instances in the same order as they were passed to the initializer.abspath + - if applicable, an additional namespace for more (non-dataclass backed) arguments added to the parser + after initialization. + - The potential list of remaining argument strings. (same as argparse.ArgumentParser.parse_known_args) + """ + + if args_file_flag or args_filename or (look_for_args_file and len(sys.argv)): + args_files = [] + + if args_filename: + args_files.append(Path(args_filename)) + elif look_for_args_file and len(sys.argv): + args_files.append(Path(sys.argv[0]).with_suffix(".args")) + + # args files specified via command line flag should overwrite default args files so we add them last + if args_file_flag: + # Create special parser just to extract the args_file_flag values + args_file_parser = ArgumentParser() + args_file_parser.add_argument(args_file_flag, type=str, action="append") + + # Use only remaining args for further parsing (remove the args_file_flag) + cfg, args = args_file_parser.parse_known_args(args=args) + cmd_args_file_paths = vars(cfg).get(args_file_flag.lstrip("-"), None) + + if cmd_args_file_paths: + args_files.extend([Path(p) for p in cmd_args_file_paths]) + + file_args = [] + for args_file in args_files: + if args_file.exists(): + file_args += args_file.read_text().split() + + # in case of duplicate arguments the last one has precedence + # args specified via the command line should overwrite args from files, so we add them last + args = file_args + args if args is not None else file_args + sys.argv[1:] + namespace, remaining_args = self.parse_known_args(args=args) + outputs = [] + for dtype in self.dataclass_types: + keys = {f.name for f in dataclasses.fields(dtype) if f.init} + inputs = {k: v for k, v in vars(namespace).items() if k in keys} + for k in keys: + delattr(namespace, k) + obj = dtype(**inputs) + outputs.append(obj) + if len(namespace.__dict__) > 0: + # additional namespace. + outputs.append(namespace) + if return_remaining_strings: + return (*outputs, remaining_args) + else: + if remaining_args: + raise ValueError(f"Some specified arguments are not used by the HfArgumentParser: {remaining_args}") + + return (*outputs,) + + def parse_dict(self, args: dict[str, Any], allow_extra_keys: bool = False) -> tuple[DataClass, ...]: + """ + Alternative helper method that does not use `argparse` at all, instead uses a dict and populating the dataclass + types. + + Args: + args (`dict`): + dict containing config values + allow_extra_keys (`bool`, *optional*, defaults to `False`): + Defaults to False. If False, will raise an exception if the dict contains keys that are not parsed. + + Returns: + Tuple consisting of: + + - the dataclass instances in the same order as they were passed to the initializer. + """ + unused_keys = set(args.keys()) + outputs = [] + for dtype in self.dataclass_types: + keys = {f.name for f in dataclasses.fields(dtype) if f.init} + inputs = {k: v for k, v in args.items() if k in keys} + unused_keys.difference_update(inputs.keys()) + obj = dtype(**inputs) + outputs.append(obj) + if not allow_extra_keys and unused_keys: + raise ValueError(f"Some keys are not used by the HfArgumentParser: {sorted(unused_keys)}") + return tuple(outputs) + + def parse_json_file(self, json_file: str | os.PathLike, allow_extra_keys: bool = False) -> tuple[DataClass, ...]: + """ + Alternative helper method that does not use `argparse` at all, instead loading a json file and populating the + dataclass types. + + Args: + json_file (`str` or `os.PathLike`): + File name of the json file to parse + allow_extra_keys (`bool`, *optional*, defaults to `False`): + Defaults to False. If False, will raise an exception if the json file contains keys that are not + parsed. + + Returns: + Tuple consisting of: + + - the dataclass instances in the same order as they were passed to the initializer. + """ + with open(Path(json_file), encoding="utf-8") as open_json_file: + data = json.loads(open_json_file.read()) + outputs = self.parse_dict(data, allow_extra_keys=allow_extra_keys) + return tuple(outputs) + + def parse_yaml_file(self, yaml_file: str | os.PathLike, allow_extra_keys: bool = False) -> tuple[DataClass, ...]: + """ + Alternative helper method that does not use `argparse` at all, instead loading a yaml file and populating the + dataclass types. + + Args: + yaml_file (`str` or `os.PathLike`): + File name of the yaml file to parse + allow_extra_keys (`bool`, *optional*, defaults to `False`): + Defaults to False. If False, will raise an exception if the json file contains keys that are not + parsed. + + Returns: + Tuple consisting of: + + - the dataclass instances in the same order as they were passed to the initializer. + """ + import yaml + + outputs = self.parse_dict(yaml.safe_load(Path(yaml_file).read_text()), allow_extra_keys=allow_extra_keys) + return tuple(outputs) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/dpo.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/dpo.py new file mode 100644 index 0000000000000000000000000000000000000000..5303906dcef18a954af4ac0f18d48c27aa4d1e1a --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/dpo.py @@ -0,0 +1,146 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl", +# "peft", +# "trackio", +# "kernels", +# ] +# /// + +""" +# Full training +```bash +python trl/scripts/dpo.py \ + --dataset_name trl-lib/ultrafeedback_binarized \ + --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ + --learning_rate 5.0e-7 \ + --num_train_epochs 1 \ + --per_device_train_batch_size 2 \ + --max_steps 1000 \ + --gradient_accumulation_steps 8 \ + --eval_strategy steps \ + --eval_steps 50 \ + --output_dir Qwen2-0.5B-DPO \ + --no_remove_unused_columns +``` + +# LoRA: +```bash +python trl/scripts/dpo.py \ + --dataset_name trl-lib/ultrafeedback_binarized \ + --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ + --learning_rate 5.0e-6 \ + --num_train_epochs 1 \ + --per_device_train_batch_size 2 \ + --max_steps 1000 \ + --gradient_accumulation_steps 8 \ + --eval_strategy steps \ + --eval_steps 50 \ + --output_dir Qwen2-0.5B-DPO \ + --no_remove_unused_columns \ + --use_peft \ + --lora_r 32 \ + --lora_alpha 16 +``` +""" + +import argparse + + +def main(script_args, training_args, model_args, dataset_args): + from accelerate.logging import get_logger + from datasets import load_dataset + + from trl import DPOTrainer, get_dataset, get_kbit_device_map, get_peft_config, get_quantization_config + + logger = get_logger(__name__) + + training_args.model_init_kwargs = dict( + revision=model_args.model_revision, + trust_remote_code=training_args.trust_remote_code, + attn_implementation=model_args.attn_implementation, + dtype=model_args.dtype, + ) + quantization_config = get_quantization_config(model_args) + if quantization_config is not None: + # Passing None would not be treated the same as omitting the argument, so we include it only when valid. + training_args.model_init_kwargs["device_map"] = get_kbit_device_map() + training_args.model_init_kwargs["quantization_config"] = quantization_config + + # Load the dataset + if dataset_args.datasets and script_args.dataset_name: + logger.warning( + "Both `datasets` and `dataset_name` are provided. The `datasets` argument will be used to load the " + "dataset and `dataset_name` will be ignored." + ) + dataset = get_dataset(dataset_args) + elif dataset_args.datasets and not script_args.dataset_name: + dataset = get_dataset(dataset_args) + elif not dataset_args.datasets and script_args.dataset_name: + dataset = load_dataset( + script_args.dataset_name, name=script_args.dataset_config, streaming=script_args.dataset_streaming + ) + else: + raise ValueError("Either `datasets` or `dataset_name` must be provided.") + + # Initialize the DPO trainer + trainer = DPOTrainer( + model=model_args.model_name_or_path, + args=training_args, + train_dataset=dataset[script_args.dataset_train_split], + eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, + peft_config=get_peft_config(model_args), + ) + + if script_args.ignore_bias_buffers: + import torch + + # torch distributed hack + trainer.model._ddp_params_and_buffers_to_ignore = [ + name for name, buffer in trainer.model.named_buffers() if buffer.dtype == torch.bool + ] + + # Train the model + trainer.train() + + # Log training complete + trainer.accelerator.print("✅ Training completed.") + + # Save and push to Hub + trainer.save_model(training_args.output_dir) + trainer.accelerator.print(f"💾 Model saved to {training_args.output_dir}.") + + if training_args.push_to_hub: + trainer.push_to_hub(dataset_name=script_args.dataset_name) + trainer.accelerator.print(f"🤗 Model pushed to the Hub in https://huggingface.co/{trainer.hub_model_id}.") + + +def make_parser(subparsers: argparse._SubParsersAction | None = None, prog: str | None = None): + from trl import DatasetMixtureConfig, DPOConfig, ModelConfig, ScriptArguments, TrlParser + + dataclass_types = (ScriptArguments, DPOConfig, ModelConfig, DatasetMixtureConfig) + if subparsers is not None: + parser = subparsers.add_parser("dpo", help="Run the DPO training script", dataclass_types=dataclass_types) + else: + parser = TrlParser(dataclass_types, prog=prog) + return parser + + +if __name__ == "__main__": + parser = make_parser() + script_args, training_args, model_args, dataset_args = parser.parse_args_and_config(fail_with_unknown_args=False) + main(script_args, training_args, model_args, dataset_args) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/env.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/env.py new file mode 100644 index 0000000000000000000000000000000000000000..830bbee0a9ab39e1426f011bcdf06df3a9b85f9e --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/env.py @@ -0,0 +1,81 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl", +# ] +# /// + +import os +import platform +from importlib.metadata import version + + +def print_env(): + import torch + from accelerate.commands.config import default_config_file, load_config_from_file + from transformers import is_bitsandbytes_available + from transformers.utils import is_peft_available + + from trl import __version__ + from trl.import_utils import is_deepspeed_available, is_liger_kernel_available, is_vllm_available + from trl.scripts.utils import get_git_commit_hash + + devices = None + if torch.cuda.is_available(): + devices = [torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())] + elif torch.backends.mps.is_available(): + devices = ["MPS"] + elif torch.xpu.is_available(): + devices = [torch.xpu.get_device_name(i) for i in range(torch.xpu.device_count())] + + accelerate_config = accelerate_config_str = "not found" + + # Get the default from the config file. + if os.path.isfile(default_config_file): + accelerate_config = load_config_from_file(default_config_file).to_dict() + + accelerate_config_str = ( + "\n" + "\n".join([f" - {prop}: {val}" for prop, val in accelerate_config.items()]) + if isinstance(accelerate_config, dict) + else accelerate_config + ) + + commit_hash = get_git_commit_hash("trl") + + info = { + "Platform": platform.platform(), + "Python version": platform.python_version(), + "TRL version": f"{__version__}+{commit_hash[:7]}" if commit_hash else __version__, + "PyTorch version": version("torch"), + "accelerator(s)": ", ".join(devices) if devices is not None else "cpu", + "Transformers version": version("transformers"), + "Accelerate version": version("accelerate"), + "Accelerate config": accelerate_config_str, + "Datasets version": version("datasets"), + "HF Hub version": version("huggingface_hub"), + "bitsandbytes version": version("bitsandbytes") if is_bitsandbytes_available() else "not installed", + "DeepSpeed version": version("deepspeed") if is_deepspeed_available() else "not installed", + "Liger-Kernel version": version("liger_kernel") if is_liger_kernel_available() else "not installed", + "PEFT version": version("peft") if is_peft_available() else "not installed", + "vLLM version": version("vllm") if is_vllm_available() else "not installed", + } + + info_str = "\n".join([f"- {prop}: {val}" for prop, val in info.items()]) + print(f"\nCopy-paste the following information when reporting an issue:\n\n{info_str}\n") # noqa + + +if __name__ == "__main__": + print_env() diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/grpo.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/grpo.py new file mode 100644 index 0000000000000000000000000000000000000000..fde837780c5dee88a2fbccdcdad242f94ac96c46 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/grpo.py @@ -0,0 +1,177 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl", +# "peft", +# "trackio", +# "kernels", +# ] +# /// + +import argparse +import importlib +import os +import sys +from dataclasses import dataclass, field + +from trl import ScriptArguments + + +@dataclass +class GRPOScriptArguments(ScriptArguments): + """ + Script arguments for the GRPO training script. + + Args: + reward_model_name_or_path (`str`, *optional*): + Reward model id of a pretrained model hosted inside a model repo on huggingface.co or local path to a + directory containing model weights saved using [`~transformers.PreTrainedModel.save_pretrained`]. + reward_funcs (`list[str]`, *optional*): + Reward functions to use. Supported values are: + - `"accuracy_reward"` + - `"reasoning_accuracy_reward"` + - `"think_format_reward"` + - `"get_soft_overlong_punishment"` (used value are `max_completion_len=1280`, `soft_punish_cache=256`) + - any dotted import path " (e.g., `'my_lib.rewards.custom_reward'`). + """ + + reward_model_name_or_path: str | None = field( + default=None, + metadata={ + "help": "Reward model id of a pretrained model hosted inside a model repo on huggingface.co or " + "local path to a directory containing model weights saved using `PreTrainedModel.save_pretrained`." + }, + ) + reward_funcs: list[str] | None = field( + default=None, + metadata={ + "help": "Reward functions to use. Supported values are: `accuracy_reward`, `reasoning_accuracy_reward`, `think_format_reward`, " + "`get_soft_overlong_punishment` (used values are `max_completion_len=1280`, `soft_punish_cache=256`), or " + "any dotted import path (e.g., `'my_lib.rewards.custom_reward'`)." + }, + ) + + +def main(script_args, training_args, model_args, dataset_args): + from accelerate.logging import get_logger + from datasets import load_dataset + + from trl import GRPOTrainer, get_dataset, get_kbit_device_map, get_peft_config, get_quantization_config + from trl.rewards import ( + accuracy_reward, + get_soft_overlong_punishment, + reasoning_accuracy_reward, + think_format_reward, + ) + + logger = get_logger(__name__) + + reward_funcs_registry = { + "accuracy_reward": accuracy_reward, + "reasoning_accuracy_reward": reasoning_accuracy_reward, + "think_format_reward": think_format_reward, + "get_soft_overlong_punishment": get_soft_overlong_punishment(max_completion_len=1280, soft_punish_cache=256), + } + + # Get the reward models and functions + reward_funcs = [] + if script_args.reward_model_name_or_path: + reward_funcs.append(script_args.reward_model_name_or_path) + + if script_args.reward_funcs: + for func_name in script_args.reward_funcs: + if func_name in reward_funcs_registry: + reward_funcs.append(reward_funcs_registry[func_name]) + elif "." in func_name: + module_path, func_name = func_name.rsplit(".", 1) + sys.path.insert(0, os.getcwd()) + module = importlib.import_module(module_path) + reward_func = getattr(module, func_name) + reward_funcs.append(reward_func) + else: + raise ValueError( + f"Could not load reward function '{func_name}'. Expected one of " + f"{list(reward_funcs_registry.keys())} or a valid import path." + ) + + training_args.model_init_kwargs = dict( + revision=model_args.model_revision, + trust_remote_code=training_args.trust_remote_code, + attn_implementation=model_args.attn_implementation, + dtype=model_args.dtype, + ) + quantization_config = get_quantization_config(model_args) + if quantization_config is not None: + # Passing None would not be treated the same as omitting the argument, so we include it only when valid. + training_args.model_init_kwargs["device_map"] = get_kbit_device_map() + training_args.model_init_kwargs["quantization_config"] = quantization_config + + # Load the dataset + if dataset_args.datasets and script_args.dataset_name: + logger.warning( + "Both `datasets` and `dataset_name` are provided. The `datasets` argument will be used to load the " + "dataset and `dataset_name` will be ignored." + ) + dataset = get_dataset(dataset_args) + elif dataset_args.datasets and not script_args.dataset_name: + dataset = get_dataset(dataset_args) + elif not dataset_args.datasets and script_args.dataset_name: + dataset = load_dataset( + script_args.dataset_name, name=script_args.dataset_config, streaming=script_args.dataset_streaming + ) + else: + raise ValueError("Either `datasets` or `dataset_name` must be provided.") + + # Initialize the GRPO trainer + trainer = GRPOTrainer( + model=model_args.model_name_or_path, + reward_funcs=reward_funcs, + args=training_args, + train_dataset=dataset[script_args.dataset_train_split], + eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, + peft_config=get_peft_config(model_args), + ) + + # Train the model + trainer.train() + + # Log training complete + trainer.accelerator.print("✅ Training completed.") + + # Save and push to Hub + trainer.save_model(training_args.output_dir) + trainer.accelerator.print(f"💾 Model saved to {training_args.output_dir}.") + + if training_args.push_to_hub: + trainer.push_to_hub(dataset_name=script_args.dataset_name) + trainer.accelerator.print(f"🤗 Model pushed to the Hub in https://huggingface.co/{trainer.hub_model_id}.") + + +def make_parser(subparsers: argparse._SubParsersAction | None = None, prog: str | None = None): + from trl import DatasetMixtureConfig, GRPOConfig, ModelConfig, TrlParser + + dataclass_types = (GRPOScriptArguments, GRPOConfig, ModelConfig, DatasetMixtureConfig) + if subparsers is not None: + parser = subparsers.add_parser("grpo", help="Run the GRPO training script", dataclass_types=dataclass_types) + else: + parser = TrlParser(dataclass_types, prog=prog) + return parser + + +if __name__ == "__main__": + parser = make_parser() + script_args, training_args, model_args, dataset_args = parser.parse_args_and_config(fail_with_unknown_args=False) + main(script_args, training_args, model_args, dataset_args) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/kto.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/kto.py new file mode 100644 index 0000000000000000000000000000000000000000..601b71e6cff581f40f87f1cc295002a6fd776fe7 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/kto.py @@ -0,0 +1,151 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl", +# "peft", +# "trackio", +# "kernels", +# ] +# /// + +""" +Run the KTO training script with the commands below. In general, the optimal configuration for KTO will be similar to +that of DPO. + +# Full training: +```bash +python trl/scripts/kto.py \ + --dataset_name trl-lib/kto-mix-14k \ + --model_name_or_path=trl-lib/qwen1.5-1.8b-sft \ + --per_device_train_batch_size 16 \ + --num_train_epochs 1 \ + --learning_rate 5e-7 \ + --lr_scheduler_type=cosine \ + --gradient_accumulation_steps 1 \ + --eval_steps 500 \ + --output_dir=kto-aligned-model \ + --warmup_steps 0.1 \ + --logging_first_step +``` + +# QLoRA: +```bash +# QLoRA: +python trl/scripts/kto.py \ + --dataset_name trl-lib/kto-mix-14k \ + --model_name_or_path=trl-lib/qwen1.5-1.8b-sft \ + --per_device_train_batch_size 8 \ + --num_train_epochs 1 \ + --learning_rate 5e-7 \ + --lr_scheduler_type=cosine \ + --gradient_accumulation_steps 1 \ + --eval_steps 500 \ + --output_dir=kto-aligned-model-lora \ + --warmup_steps 0.1 \ + --logging_first_step \ + --use_peft \ + --load_in_4bit \ + --lora_target_modules=all-linear \ + --lora_r=16 \ + --lora_alpha=16 +``` +""" + +import argparse + + +def main(script_args, training_args, model_args, dataset_args): + from accelerate.logging import get_logger + from datasets import load_dataset + from transformers import AutoModelForCausalLM, AutoTokenizer + + from trl import get_dataset, get_peft_config + from trl.experimental.kto import KTOTrainer + + logger = get_logger(__name__) + + # Load a pretrained model + model = AutoModelForCausalLM.from_pretrained( + model_args.model_name_or_path, trust_remote_code=training_args.trust_remote_code + ) + ref_model = AutoModelForCausalLM.from_pretrained( + model_args.model_name_or_path, trust_remote_code=training_args.trust_remote_code + ) + + tokenizer = AutoTokenizer.from_pretrained( + model_args.model_name_or_path, trust_remote_code=training_args.trust_remote_code + ) + if tokenizer.pad_token is None: + tokenizer.pad_token = tokenizer.eos_token + + # Load the dataset + if dataset_args.datasets and script_args.dataset_name: + logger.warning( + "Both `datasets` and `dataset_name` are provided. The `datasets` argument will be used to load the " + "dataset and `dataset_name` will be ignored." + ) + dataset = get_dataset(dataset_args) + elif dataset_args.datasets and not script_args.dataset_name: + dataset = get_dataset(dataset_args) + elif not dataset_args.datasets and script_args.dataset_name: + dataset = load_dataset( + script_args.dataset_name, name=script_args.dataset_config, streaming=script_args.dataset_streaming + ) + else: + raise ValueError("Either `datasets` or `dataset_name` must be provided.") + + # Initialize the KTO trainer + trainer = KTOTrainer( + model, + ref_model, + args=training_args, + train_dataset=dataset[script_args.dataset_train_split], + eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, + processing_class=tokenizer, + peft_config=get_peft_config(model_args), + ) + + # Train the model + trainer.train() + + # Log training complete + trainer.accelerator.print("✅ Training completed.") + + # Save and push to Hub + trainer.save_model(training_args.output_dir) + trainer.accelerator.print(f"💾 Model saved to {training_args.output_dir}.") + + if training_args.push_to_hub: + trainer.push_to_hub(dataset_name=script_args.dataset_name) + trainer.accelerator.print(f"🤗 Model pushed to the Hub in https://huggingface.co/{trainer.hub_model_id}.") + + +def make_parser(subparsers: argparse._SubParsersAction | None = None, prog: str | None = None): + from trl import DatasetMixtureConfig, ModelConfig, ScriptArguments, TrlParser + from trl.experimental.kto import KTOConfig + + dataclass_types = (ScriptArguments, KTOConfig, ModelConfig, DatasetMixtureConfig) + if subparsers is not None: + parser = subparsers.add_parser("kto", help="Run the KTO training script", dataclass_types=dataclass_types) + else: + parser = TrlParser(dataclass_types, prog=prog) + return parser + + +if __name__ == "__main__": + parser = make_parser() + script_args, training_args, model_args, dataset_args = parser.parse_args_and_config(fail_with_unknown_args=False) + main(script_args, training_args, model_args, dataset_args) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/reward.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..9cec8e9de84f60a5498cf98f542969d24b83e8b4 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/reward.py @@ -0,0 +1,103 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl", +# "peft", +# "trackio", +# "kernels", +# ] +# /// + +import argparse + + +def main(script_args, training_args, model_args, dataset_args): + from accelerate.logging import get_logger + from datasets import load_dataset + + from trl import RewardTrainer, get_dataset, get_kbit_device_map, get_peft_config, get_quantization_config + + logger = get_logger(__name__) + + training_args.model_init_kwargs = dict( + revision=model_args.model_revision, + trust_remote_code=training_args.trust_remote_code, + attn_implementation=model_args.attn_implementation, + dtype=model_args.dtype, + ) + quantization_config = get_quantization_config(model_args) + if quantization_config is not None: + # Passing None would not be treated the same as omitting the argument, so we include it only when valid. + training_args.model_init_kwargs["device_map"] = get_kbit_device_map() + training_args.model_init_kwargs["quantization_config"] = quantization_config + + # Load the dataset + if dataset_args.datasets and script_args.dataset_name: + logger.warning( + "Both `datasets` and `dataset_name` are provided. The `datasets` argument will be used to load the " + "dataset and `dataset_name` will be ignored." + ) + dataset = get_dataset(dataset_args) + elif dataset_args.datasets and not script_args.dataset_name: + dataset = get_dataset(dataset_args) + elif not dataset_args.datasets and script_args.dataset_name: + dataset = load_dataset( + script_args.dataset_name, name=script_args.dataset_config, streaming=script_args.dataset_streaming + ) + else: + raise ValueError("Either `datasets` or `dataset_name` must be provided.") + + # Initialize the reward trainer + trainer = RewardTrainer( + model=model_args.model_name_or_path, + args=training_args, + train_dataset=dataset[script_args.dataset_train_split], + eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, + peft_config=get_peft_config(model_args), + ) + + # Train the model + trainer.train() + + # Log training complete + trainer.accelerator.print("✅ Training completed.") + + # Save and push to Hub + trainer.save_model(training_args.output_dir) + trainer.accelerator.print(f"💾 Model saved to {training_args.output_dir}.") + + if training_args.push_to_hub: + trainer.push_to_hub(dataset_name=script_args.dataset_name) + trainer.accelerator.print(f"🤗 Model pushed to the Hub in https://huggingface.co/{trainer.hub_model_id}.") + + +def make_parser(subparsers: argparse._SubParsersAction | None = None, prog: str | None = None): + from trl import DatasetMixtureConfig, ModelConfig, RewardConfig, ScriptArguments, TrlParser + + dataclass_types = (ScriptArguments, RewardConfig, ModelConfig, DatasetMixtureConfig) + if subparsers is not None: + parser = subparsers.add_parser( + "reward", help="Run the reward training script", dataclass_types=dataclass_types + ) + else: + parser = TrlParser(dataclass_types, prog=prog) + return parser + + +if __name__ == "__main__": + parser = make_parser() + script_args, training_args, model_args, dataset_args = parser.parse_args_and_config(fail_with_unknown_args=False) + main(script_args, training_args, model_args, dataset_args) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/rloo.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/rloo.py new file mode 100644 index 0000000000000000000000000000000000000000..7ec6f3806951db8d738bf9bfea4d6e65cbe89b8d --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/rloo.py @@ -0,0 +1,177 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl", +# "peft", +# "trackio", +# "kernels", +# ] +# /// + +import argparse +import importlib +import os +import sys +from dataclasses import dataclass, field + +from trl import ScriptArguments + + +@dataclass +class RLOOScriptArguments(ScriptArguments): + """ + Script arguments for the RLOO training script. + + Args: + reward_model_name_or_path (`str`, *optional*): + Reward model id of a pretrained model hosted inside a model repo on huggingface.co or local path to a + directory containing model weights saved using [`~transformers.PreTrainedModel.save_pretrained`]. + reward_funcs (`list[str]`, *optional*): + Reward functions to use. Supported values are: + - `"accuracy_reward"` + - `"reasoning_accuracy_reward"` + - `"think_format_reward"` + - `"get_soft_overlong_punishment"` (used value are `max_completion_len=1280`, `soft_punish_cache=256`) + - any dotted import path " (e.g., `'my_lib.rewards.custom_reward'`). + """ + + reward_model_name_or_path: str | None = field( + default=None, + metadata={ + "help": "Reward model id of a pretrained model hosted inside a model repo on huggingface.co or " + "local path to a directory containing model weights saved using `PreTrainedModel.save_pretrained`." + }, + ) + reward_funcs: list[str] | None = field( + default=None, + metadata={ + "help": "Reward functions to use. Supported values are: `accuracy_reward`, `reasoning_accuracy_reward`, `think_format_reward`, " + "`get_soft_overlong_punishment` (used values are `max_completion_len=1280`, `soft_punish_cache=256`), or " + "any dotted import path (e.g., `'my_lib.rewards.custom_reward'`)." + }, + ) + + +def main(script_args, training_args, model_args, dataset_args): + from accelerate.logging import get_logger + from datasets import load_dataset + + from trl import RLOOTrainer, get_dataset, get_kbit_device_map, get_peft_config, get_quantization_config + from trl.rewards import ( + accuracy_reward, + get_soft_overlong_punishment, + reasoning_accuracy_reward, + think_format_reward, + ) + + logger = get_logger(__name__) + + reward_funcs_registry = { + "accuracy_reward": accuracy_reward, + "reasoning_accuracy_reward": reasoning_accuracy_reward, + "think_format_reward": think_format_reward, + "get_soft_overlong_punishment": get_soft_overlong_punishment(max_completion_len=1280, soft_punish_cache=256), + } + + # Get the reward models and functions + reward_funcs = [] + if script_args.reward_model_name_or_path: + reward_funcs.append(script_args.reward_model_name_or_path) + + if script_args.reward_funcs: + for func_name in script_args.reward_funcs: + if func_name in reward_funcs_registry: + reward_funcs.append(reward_funcs_registry[func_name]) + elif "." in func_name: + module_path, func_name = func_name.rsplit(".", 1) + sys.path.insert(0, os.getcwd()) + module = importlib.import_module(module_path) + reward_func = getattr(module, func_name) + reward_funcs.append(reward_func) + else: + raise ValueError( + f"Could not load reward function '{func_name}'. Expected one of " + f"{list(reward_funcs_registry.keys())} or a valid import path." + ) + + training_args.model_init_kwargs = dict( + revision=model_args.model_revision, + trust_remote_code=training_args.trust_remote_code, + attn_implementation=model_args.attn_implementation, + dtype=model_args.dtype, + ) + quantization_config = get_quantization_config(model_args) + if quantization_config is not None: + # Passing None would not be treated the same as omitting the argument, so we include it only when valid. + training_args.model_init_kwargs["device_map"] = get_kbit_device_map() + training_args.model_init_kwargs["quantization_config"] = quantization_config + + # Load the dataset + if dataset_args.datasets and script_args.dataset_name: + logger.warning( + "Both `datasets` and `dataset_name` are provided. The `datasets` argument will be used to load the " + "dataset and `dataset_name` will be ignored." + ) + dataset = get_dataset(dataset_args) + elif dataset_args.datasets and not script_args.dataset_name: + dataset = get_dataset(dataset_args) + elif not dataset_args.datasets and script_args.dataset_name: + dataset = load_dataset( + script_args.dataset_name, name=script_args.dataset_config, streaming=script_args.dataset_streaming + ) + else: + raise ValueError("Either `datasets` or `dataset_name` must be provided.") + + # Initialize the RLOO trainer + trainer = RLOOTrainer( + model=model_args.model_name_or_path, + reward_funcs=reward_funcs, + args=training_args, + train_dataset=dataset[script_args.dataset_train_split], + eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, + peft_config=get_peft_config(model_args), + ) + + # Train the model + trainer.train() + + # Log training complete + trainer.accelerator.print("✅ Training completed.") + + # Save and push to Hub + trainer.save_model(training_args.output_dir) + trainer.accelerator.print(f"💾 Model saved to {training_args.output_dir}.") + + if training_args.push_to_hub: + trainer.push_to_hub(dataset_name=script_args.dataset_name) + trainer.accelerator.print(f"🤗 Model pushed to the Hub in https://huggingface.co/{trainer.hub_model_id}.") + + +def make_parser(subparsers: argparse._SubParsersAction | None = None, prog: str | None = None): + from trl import DatasetMixtureConfig, ModelConfig, RLOOConfig, TrlParser + + dataclass_types = (RLOOScriptArguments, RLOOConfig, ModelConfig, DatasetMixtureConfig) + if subparsers is not None: + parser = subparsers.add_parser("rloo", help="Run the RLOO training script", dataclass_types=dataclass_types) + else: + parser = TrlParser(dataclass_types, prog=prog) + return parser + + +if __name__ == "__main__": + parser = make_parser() + script_args, training_args, model_args, dataset_args = parser.parse_args_and_config(fail_with_unknown_args=False) + main(script_args, training_args, model_args, dataset_args) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/sft.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/sft.py new file mode 100644 index 0000000000000000000000000000000000000000..82c9622cb0da0f9fb9e1541a09c765af14647a8a --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/sft.py @@ -0,0 +1,140 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl", +# "peft", +# "trackio", +# "kernels", +# ] +# /// + +""" +# Full training +``` +python trl/scripts/sft.py \ + --model_name_or_path Qwen/Qwen2-0.5B \ + --dataset_name trl-lib/Capybara \ + --learning_rate 2.0e-5 \ + --num_train_epochs 1 \ + --packing \ + --per_device_train_batch_size 2 \ + --gradient_accumulation_steps 8 \ + --eos_token '<|im_end|>' \ + --eval_strategy steps \ + --eval_steps 100 \ + --output_dir Qwen2-0.5B-SFT \ + --push_to_hub +``` + +# LoRA +``` +python trl/scripts/sft.py \ + --model_name_or_path Qwen/Qwen2-0.5B \ + --dataset_name trl-lib/Capybara \ + --learning_rate 2.0e-4 \ + --num_train_epochs 1 \ + --packing \ + --per_device_train_batch_size 2 \ + --gradient_accumulation_steps 8 \ + --eos_token '<|im_end|>' \ + --eval_strategy steps \ + --eval_steps 100 \ + --use_peft \ + --lora_r 32 \ + --lora_alpha 16 \ + --output_dir Qwen2-0.5B-SFT \ + --push_to_hub +``` +""" + +import argparse + + +def main(script_args, training_args, model_args, dataset_args): + from accelerate.logging import get_logger + from datasets import load_dataset + + from trl import SFTTrainer, get_dataset, get_kbit_device_map, get_peft_config, get_quantization_config + + logger = get_logger(__name__) + + training_args.model_init_kwargs = dict( + revision=model_args.model_revision, + trust_remote_code=training_args.trust_remote_code, + attn_implementation=model_args.attn_implementation, + dtype=model_args.dtype, + ) + quantization_config = get_quantization_config(model_args) + if quantization_config is not None: + # Passing None would not be treated the same as omitting the argument, so we include it only when valid. + training_args.model_init_kwargs["device_map"] = get_kbit_device_map() + training_args.model_init_kwargs["quantization_config"] = quantization_config + + # Load the dataset + if dataset_args.datasets and script_args.dataset_name: + logger.warning( + "Both `datasets` and `dataset_name` are provided. The `datasets` argument will be used to load the " + "dataset and `dataset_name` will be ignored." + ) + dataset = get_dataset(dataset_args) + elif dataset_args.datasets and not script_args.dataset_name: + dataset = get_dataset(dataset_args) + elif not dataset_args.datasets and script_args.dataset_name: + dataset = load_dataset( + script_args.dataset_name, name=script_args.dataset_config, streaming=script_args.dataset_streaming + ) + else: + raise ValueError("Either `datasets` or `dataset_name` must be provided.") + + # Initialize the SFT trainer + trainer = SFTTrainer( + model=model_args.model_name_or_path, + args=training_args, + train_dataset=dataset[script_args.dataset_train_split], + eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, + peft_config=get_peft_config(model_args), + ) + + # Train the model + trainer.train() + + # Log training complete + trainer.accelerator.print("✅ Training completed.") + + # Save and push to Hub + trainer.save_model(training_args.output_dir) + trainer.accelerator.print(f"💾 Model saved to {training_args.output_dir}.") + + if training_args.push_to_hub: + trainer.push_to_hub(dataset_name=script_args.dataset_name) + trainer.accelerator.print(f"🤗 Model pushed to the Hub in https://huggingface.co/{trainer.hub_model_id}.") + + +def make_parser(subparsers: argparse._SubParsersAction | None = None, prog: str | None = None): + from trl import DatasetMixtureConfig, ModelConfig, ScriptArguments, SFTConfig, TrlParser + + dataclass_types = (ScriptArguments, SFTConfig, ModelConfig, DatasetMixtureConfig) + if subparsers is not None: + parser = subparsers.add_parser("sft", help="Run the SFT training script", dataclass_types=dataclass_types) + else: + parser = TrlParser(dataclass_types, prog=prog) + return parser + + +if __name__ == "__main__": + parser = make_parser() + script_args, training_args, model_args, dataset_args = parser.parse_args_and_config(fail_with_unknown_args=False) + main(script_args, training_args, model_args, dataset_args) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/utils.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..040661a09c0a5b78f40d595064121c0490a2bba4 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/utils.py @@ -0,0 +1,462 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import importlib +import inspect +import logging +import os +import subprocess +import sys +from collections.abc import Iterable +from dataclasses import dataclass, field +from typing import TYPE_CHECKING + +# Temporarily import from the local module instead of transformers to avoid an upstream latency issue +# See: https://github.com/huggingface/transformers/issues/44273 +# This workaround can be reverted once the fix is included in the minimum required transformers version +from trl.scripts._hf_argparser import DataClass, DataClassType, HfArgumentParser + + +if TYPE_CHECKING: + from datasets import DatasetDict + + +logger = logging.getLogger(__name__) + + +@dataclass +class DatasetConfig: + """ + Configuration for a dataset. + + This class matches the signature of [`~datasets.load_dataset`] and the arguments are used directly in the + [`~datasets.load_dataset`] function. You can refer to the [`~datasets.load_dataset`] documentation for more + details. + + Parameters: + path (`str`): + Path or name of the dataset. + name (`str`, *optional*): + Defining the name of the dataset configuration. + data_dir (`str`, *optional*): + Defining the `data_dir` of the dataset configuration. If specified for the generic builders(csv, text etc.) + or the Hub datasets and `data_files` is `None`, the behavior is equal to passing `os.path.join(data_dir, + **)` as `data_files` to reference all the files in a directory. + data_files (`str` or `Sequence` or `Mapping`, *optional*): + Path(s) to source data file(s). + split (`str`, *optional*, defaults to `"train"`): + Which split of the data to load. + columns (`list[str]`, *optional*): + List of column names to select from the dataset. If `None`, all columns are selected. + """ + + path: str + name: str | None = None + data_dir: str | None = None + data_files: str | list[str] | dict[str, str] | None = None + split: str = "train" + columns: list[str] | None = None + + +@dataclass +class DatasetMixtureConfig: + """ + Configuration class for a mixture of datasets. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + datasets (`list[DatasetConfig]`): + List of dataset configurations to include in the mixture. + streaming (`bool`, *optional*, defaults to `False`): + Whether to stream the datasets. If `True`, the datasets will be loaded in streaming mode. + test_split_size (`float`, *optional*): + Size of the test split. Refer to the `test_size` parameter in the [`~datasets.train_test_split`] function + for more details. If `None`, the dataset will not be split into train and test sets. + + Usage: + When using the CLI, you can add the following section to your YAML config file: + + ```yaml + datasets: + - path: ... + name: ... + data_dir: ... + data_files: ... + split: ... + columns: ... + - path: ... + name: ... + data_dir: ... + data_files: ... + split: ... + columns: ... + streaming: ... + test_split_size: ... + ``` + """ + + datasets: list[DatasetConfig] = field( + default_factory=list, + metadata={"help": "List of dataset configurations to include in the mixture."}, + ) + streaming: bool = field( + default=False, + metadata={"help": "Whether to stream the datasets. If True, the datasets will be loaded in streaming mode."}, + ) + test_split_size: float | None = field( + default=None, + metadata={ + "help": "Size of the test split. Refer to the `test_size` parameter in the `datasets.train_test_split` " + "function for more details. If None, the dataset will not be split into train and test sets." + }, + ) + + def __post_init__(self): + # Convert any dataset dicts (from CLI/config parsing) into DatasetConfig objects + for idx, dataset in enumerate(self.datasets): + if isinstance(dataset, dict): + # If it's a dict, convert it to DatasetConfig + self.datasets[idx] = DatasetConfig(**dataset) + + +@dataclass +class ScriptArguments: + """ + Arguments common to all scripts. + + Args: + dataset_name (`str`,, *optional*): + Path or name of the dataset to load. If `datasets` is provided, this will be ignored. + dataset_config (`str`, *optional*): + Dataset configuration name. Corresponds to the `name` argument of the [`~datasets.load_dataset`] function. + If `datasets` is provided, this will be ignored. + dataset_train_split (`str`, *optional*, defaults to `"train"`): + Dataset split to use for training. If `datasets` is provided, this will be ignored. + dataset_test_split (`str`, *optional*, defaults to `"test"`): + Dataset split to use for evaluation. If `datasets` is provided, this will be ignored. + dataset_streaming (`bool`, *optional*, defaults to `False`): + Whether to stream the dataset. If True, the dataset will be loaded in streaming mode. If `datasets` is + provided, this will be ignored. + ignore_bias_buffers (`bool`, *optional*, defaults to `False`): + Debug argument for distributed training. Fix for DDP issues with LM bias/mask buffers - invalid scalar + type, inplace operation. See + https://github.com/huggingface/transformers/issues/22482#issuecomment-1595790992. + """ + + dataset_name: str | None = field( + default=None, + metadata={"help": "Path or name of the dataset to load. If `datasets` is provided, this will be ignored."}, + ) + dataset_config: str | None = field( + default=None, + metadata={ + "help": "Dataset configuration name. Corresponds to the `name` argument of the `datasets.load_dataset` " + "function. If `datasets` is provided, this will be ignored." + }, + ) + dataset_train_split: str = field( + default="train", + metadata={"help": "Dataset split to use for training. If `datasets` is provided, this will be ignored."}, + ) + dataset_test_split: str = field( + default="test", + metadata={"help": "Dataset split to use for evaluation. If `datasets` is provided, this will be ignored."}, + ) + dataset_streaming: bool = field( + default=False, + metadata={ + "help": "Whether to stream the dataset. If True, the dataset will be loaded in streaming mode. If " + "`datasets` is provided, this will be ignored." + }, + ) + ignore_bias_buffers: bool = field( + default=False, + metadata={ + "help": "Debug argument for distributed training. Fix for DDP issues with LM bias/mask buffers - invalid " + "scalar type, inplace operation. See " + "https://github.com/huggingface/transformers/issues/22482#issuecomment-1595790992." + }, + ) + + +def init_zero_verbose(): + """ + Perform zero verbose init - use this method on top of the CLI modules to make logging and warning output cleaner. + Uses Rich if available, falls back otherwise. + """ + import logging + import warnings + + from transformers.utils import is_rich_available + + FORMAT = "%(message)s" + + if is_rich_available(): + from rich.logging import RichHandler + + handler = RichHandler() + else: + handler = logging.StreamHandler() + + logging.basicConfig(format=FORMAT, datefmt="[%X]", handlers=[handler], level=logging.ERROR) + + # Custom warning handler to redirect warnings to the logging system + def warning_handler(message, category, filename, lineno, file=None, line=None): + logging.warning(f"{filename}:{lineno}: {category.__name__}: {message}") + + # Add the custom warning handler - we need to do that before importing anything to make sure the loggers work well + warnings.showwarning = warning_handler + + +class TrlParser(HfArgumentParser): + """ + A subclass of [`transformers.HfArgumentParser`] designed for parsing command-line arguments with dataclass-backed + configurations, while also supporting configuration file loading and environment variable management. + + Args: + dataclass_types (`DataClassType | Iterable[DataClassType]`, *optional*): + Dataclass types to use for argument parsing. + **kwargs: + Additional keyword arguments passed to the [`transformers.HfArgumentParser`] constructor. + + Examples: + + ```yaml + # config.yaml + env: + VAR1: value1 + arg1: 23 + ``` + + ```python + # main.py + import os + from dataclasses import dataclass + from trl import TrlParser + + + @dataclass + class MyArguments: + arg1: int + arg2: str = "alpha" + + + parser = TrlParser(dataclass_types=[MyArguments]) + training_args = parser.parse_args_and_config() + + print(training_args, os.environ.get("VAR1")) + ``` + + ```bash + $ python main.py --config config.yaml + (MyArguments(arg1=23, arg2='alpha'),) value1 + + $ python main.py --arg1 5 --arg2 beta + (MyArguments(arg1=5, arg2='beta'),) None + ``` + """ + + def __init__( + self, + dataclass_types: DataClassType | Iterable[DataClassType] | None = None, + **kwargs, + ): + # Make sure dataclass_types is an iterable + if dataclass_types is None: + dataclass_types = [] + elif not isinstance(dataclass_types, Iterable): + dataclass_types = [dataclass_types] + + # Check that none of the dataclasses have the "config" field + for dataclass_type in dataclass_types: + if "config" in dataclass_type.__dataclass_fields__: + raise ValueError( + f"Dataclass {dataclass_type.__name__} has a field named 'config'. This field is reserved for the " + f"config file path and should not be used in the dataclass." + ) + + super().__init__(dataclass_types=dataclass_types, **kwargs) + + def parse_args_and_config( + self, + args: Iterable[str] | None = None, + return_remaining_strings: bool = False, + fail_with_unknown_args: bool = True, + separate_remaining_strings: bool = False, + ) -> tuple[DataClass, ...]: + """ + Parse command-line args and config file into instances of the specified dataclass types. + + This method wraps [`transformers.HfArgumentParser.parse_args_into_dataclasses`] and also parses the config file + specified with the `--config` flag. The config file (in YAML format) provides argument values that replace the + default values in the dataclasses. Command line arguments can override values set by the config file. The + method also sets any environment variables specified in the `env` field of the config file. + """ + import yaml + + args = list(args) if args is not None else sys.argv[1:] + if "--config" in args: + # Get the config file path from + config_index = args.index("--config") + args.pop(config_index) # remove the --config flag + config_path = args.pop(config_index) # get the path to the config file + with open(config_path) as yaml_file: + config = yaml.safe_load(yaml_file) + + # Set the environment variables specified in the config file + if "env" in config: + env_vars = config.pop("env", {}) + if not isinstance(env_vars, dict): + raise ValueError("`env` field should be a dict in the YAML file.") + for key, value in env_vars.items(): + os.environ[key] = str(value) + + # Set the defaults from the config values + config_remaining_strings = self.set_defaults_with_config(**config) + else: + config_remaining_strings = [] + + # Parse the arguments from the command line + output = self.parse_args_into_dataclasses(args=args, return_remaining_strings=return_remaining_strings) + + # Merge remaining strings from the config file with the remaining strings from the command line + if return_remaining_strings: + args_remaining_strings = output[-1] + if separate_remaining_strings: + return output[:-1] + (config_remaining_strings, args_remaining_strings) + return output[:-1] + (config_remaining_strings + args_remaining_strings,) + elif fail_with_unknown_args and config_remaining_strings: + raise ValueError( + f"Unknown arguments from config file: {config_remaining_strings}. Please remove them, add them to the " + "dataclass, or set `fail_with_unknown_args=False`." + ) + else: + return output + + def set_defaults_with_config(self, **kwargs) -> list[str]: + """ + Overrides the parser's default values with those provided via keyword arguments, including for subparsers. + + Any argument with an updated default will also be marked as not required if it was previously required. + + Returns a list of strings that were not consumed by the parser. + """ + + def apply_defaults(parser, kw): + used_keys = set() + for action in parser._actions: + # Handle subparsers recursively + if isinstance(action, argparse._SubParsersAction): + for subparser in action.choices.values(): + used_keys.update(apply_defaults(subparser, kw)) + elif action.dest in kw: + action.default = kw[action.dest] + action.required = False + used_keys.add(action.dest) + return used_keys + + used_keys = apply_defaults(self, kwargs) + # Remaining args not consumed by the parser + remaining = [ + item for key, value in kwargs.items() if key not in used_keys for item in (f"--{key}", str(value)) + ] + return remaining + + +def get_git_commit_hash(package_name): + try: + # Import the package to locate its path + package = importlib.import_module(package_name) + # Get the path to the package using inspect + package_path = os.path.dirname(inspect.getfile(package)) + + # Navigate up to the Git repository root if the package is inside a subdirectory + git_repo_path = os.path.abspath(os.path.join(package_path, "..")) + git_dir = os.path.join(git_repo_path, ".git") + + if os.path.isdir(git_dir): + # Run the git command to get the current commit hash + commit_hash = ( + subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=git_repo_path).strip().decode("utf-8") + ) + return commit_hash + else: + return None + except Exception as e: + return f"Error: {str(e)}" + + +def get_dataset(mixture_config: DatasetMixtureConfig) -> "DatasetDict": + """ + Load a mixture of datasets based on the configuration. + + Args: + mixture_config ([`DatasetMixtureConfig`]): + Script arguments containing dataset configuration. + + Returns: + [`~datasets.DatasetDict`]: + Combined dataset(s) from the mixture configuration, with optional train/test split if `test_split_size` is + set. + + Example: + ```python + >>> from trl import DatasetMixtureConfig, get_dataset + >>> from trl.scripts.utils import DatasetConfig + + >>> mixture_config = DatasetMixtureConfig(datasets=[DatasetConfig(path="trl-lib/tldr")]) + >>> get_dataset(mixture_config) + DatasetDict({ + train: Dataset({ + features: ['prompt', 'completion'], + num_rows: 116722 + }) + }) + ``` + """ + import datasets + + logger.info(f"Creating dataset mixture with {len(mixture_config.datasets)} datasets") + datasets_list = [] + for dataset_config in mixture_config.datasets: + logger.info(f"Loading dataset for mixture: {dataset_config.path} (config name: {dataset_config.name})") + dataset = datasets.load_dataset( + path=dataset_config.path, + name=dataset_config.name, + data_dir=dataset_config.data_dir, + data_files=dataset_config.data_files, + split=dataset_config.split, + streaming=mixture_config.streaming, + ) + if dataset_config.columns is not None: + dataset = dataset.select_columns(dataset_config.columns) + datasets_list.append(dataset) + + if datasets_list: + combined_dataset = datasets.concatenate_datasets(datasets_list) + if isinstance(combined_dataset, datasets.Dataset): # IterableDataset does not have a length + logger.info(f"Created dataset mixture with {len(combined_dataset)} examples") + + if mixture_config.test_split_size is not None: + logger.info(f"Splitting dataset into train and test sets with test size: {mixture_config.test_split_size}") + combined_dataset = combined_dataset.train_test_split(test_size=mixture_config.test_split_size) + return combined_dataset + else: + return datasets.DatasetDict({"train": combined_dataset}) + else: + raise ValueError("No datasets were loaded from the mixture configuration") diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/vllm_serve.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/vllm_serve.py new file mode 100644 index 0000000000000000000000000000000000000000..ccf182eeaacfbc498b3fbcd5c455a3e93be16536 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/scripts/vllm_serve.py @@ -0,0 +1,1220 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import base64 +import json +import logging +import math +import os +from collections.abc import Sequence +from contextlib import asynccontextmanager +from dataclasses import dataclass, field +from io import BytesIO +from itertools import chain +from multiprocessing import Pipe, Process +from multiprocessing.connection import Connection + + +# We use CUDA with multiprocessing, so we must use the 'spawn' start method. Otherwise, we will get the following +# error: RuntimeError: Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use +# the 'spawn' start method +os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn" + + +class WeightSyncWorkerExtension: + """ + A vLLM worker extension that enables weight synchronization between a client and multiple server workers. + + This worker uses a `StatelessProcessGroup` to establish communication and a `PyNcclCommunicator` or + `ProcessGroupXCCL` to handle efficient GPU-based communication using NCCL. The primary purpose of this class is to + receive updated model weights from a client process and distribute them to all worker processes participating in + model inference. + """ + + # The following attributes are initialized when `init_communicator` method is called. + communicator = None # Communicator for weight updates + client_rank = None # Source rank for broadcasting updated weights + + def init_communicator(self, host: str, port: int, world_size: int, client_device_uuid: str) -> None: + """ + Initializes the weight update communicator using a stateless process group. + + This method creates a `StatelessProcessGroup` that allows external training processes to communicate with vLLM + workers without interfering with the global torch distributed group. + + Args: + host (`str`): + Hostname or IP address of the master node. + port (`int`): + Port number to be used for communication. + world_size (`int`): + Total number of participating processes in the update group. + client_device_uuid (`str`): + UUID of the device of client main process. Used to assert that devices are different from vllm workers + devices. + """ + import torch + import torch.distributed.distributed_c10d as c10d + from transformers import is_torch_xpu_available + from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator + from vllm.distributed.parallel_state import get_world_group + from vllm.distributed.utils import StatelessProcessGroup + + from trl.import_utils import is_vllm_ascend_available + + if is_vllm_ascend_available(): + from vllm_ascend.distributed.device_communicators.pyhccl import PyHcclCommunicator as PyNcclCommunicator + + if self.communicator is not None: + raise RuntimeError("Weight update group already initialized. Call close_communicator first.") + + # TODO: will remove after torch xpu 2.9 support uuid in get_device_properties + if torch.cuda.is_available() or ( + is_torch_xpu_available() and hasattr(torch.xpu.get_device_properties(self.device), "uuid") + ): + accelerator_module = torch.xpu if is_torch_xpu_available() else torch.cuda + if client_device_uuid == str(accelerator_module.get_device_properties(self.device).uuid): + raise RuntimeError( + f"Attempting to use the same CUDA device (UUID: {client_device_uuid}) for multiple distinct " + "roles/ranks within the same communicator. This setup is unsupported and will likely lead to program " + "hangs or incorrect behavior. Ensure that trainer is using different devices than vLLM server." + ) + # Get the rank of the current worker in the global world group. + rank = get_world_group().rank + + if is_torch_xpu_available(): + store = torch.distributed.TCPStore(host_name=host, port=port, world_size=world_size, is_master=(rank == 0)) + prefixed_store = c10d.PrefixStore("client2server", store) + xccl_options = c10d.ProcessGroupXCCL.Options() + pg = c10d.ProcessGroupXCCL( + store=prefixed_store, + rank=rank, + size=world_size, + options=xccl_options, + ) + self.communicator = pg + else: + # Create a stateless process group to manage communication between training processes and vLLM workers. + # Initialize the NCCL-based communicator for weight synchronization. + pg = StatelessProcessGroup.create(host=host, port=port, rank=rank, world_size=world_size) + self.communicator = PyNcclCommunicator(pg, device=self.device) + + # The client process that sends updated weights has the highest rank (world_size - 1). + self.client_rank = world_size - 1 + + def update_named_param(self, name: str, dtype: str, shape: Sequence[int]) -> None: + """ + Receives updated weights from the client process and updates the named parameter in the model. + + Args: + name (`str`): + Name of the weight tensor being updated. + dtype (`str`): + Data type of the weight tensor as a string (e.g., `"torch.float32"`). + shape (`Sequence[int]`): + Shape of the weight tensor. + """ + import torch + from transformers import is_torch_xpu_available + + if self.communicator is None: + raise RuntimeError("Communicator not initialized. Call `init_communicator` first.") + + dtype = getattr(torch, dtype.split(".")[-1]) + # Allocate memory for the incoming weight tensor on the correct device. + weight = torch.empty(shape, dtype=dtype, device=self.device) + + if is_torch_xpu_available(): + # Use XCCL to broadcast the updated weights from the client (src) to all workers. + self.communicator.broadcast(weight, root=self.client_rank) + self.communicator.barrier() + else: + # Use NCCL to broadcast the updated weights from the client (src) to all workers. + self.communicator.broadcast(weight, src=self.client_rank) + self.communicator.group.barrier() + + # Load the received weights into the model. + self.model_runner.model.load_weights(weights=[(name, weight)]) + + def close_communicator(self) -> None: + """ + Closes the communicator when weight synchronization is no longer needed. + + This method deletes the NCCL communicator to release associated resources. + """ + + if self.communicator is not None: + del self.communicator + self.communicator = None # Ensure attribute is reset to None + self.client_rank = None # Ensure attribute is reset to None + + +@dataclass +class ScriptArguments: + r""" + Arguments for the script. + + Args: + model (`str`): + Model name or path to load the model from. + revision (`str`, *optional*): + Revision to use for the model. If not specified, the default branch will be used. + tensor_parallel_size (`int`, *optional*, defaults to `1`): + Number of tensor parallel workers to use. + data_parallel_size (`int`, *optional*, defaults to `1`): + Number of data parallel workers to use. For dense models, keep this at 1. Starting from vLLM `0.14.0`, + setting this above `1` for dense models is no longer supported/useful and will error out (see vLLM PR + #30739). + host (`str`, *optional*, defaults to `"0.0.0.0"`): + Host address to run the server on. + port (`int`, *optional*, defaults to `8000`): + Port to run the server on. + gpu_memory_utilization (`float`, *optional*, defaults to `0.9`): + Ratio (between 0 and 1) of GPU memory to reserve for the model weights, activations, and KV cache on the + device dedicated to generation powered by vLLM. Higher values will increase the KV cache size and thus + improve the model's throughput. However, if the value is too high, it may cause out-of-memory (OOM) errors + during initialization. + dtype (`str`, *optional*, defaults to `"auto"`): + Data type to use for vLLM generation. If set to `"auto"`, the data type will be automatically determined + based on the model configuration. Find the supported values in the vLLM documentation. + max_model_len (`int`, *optional*): + If set, the `max_model_len` to use for vLLM. This can be useful when running with reduced + `vllm_gpu_memory_utilization`, leading to a reduced KV cache size. If not set, vLLM will use the model + context size, which might be much larger than the KV cache, leading to inefficiencies. + enable_prefix_caching (`bool`, *optional*): + Whether to enable prefix caching in vLLM. If set to `True`, ensure that the model and the hardware support + this feature. + enforce_eager (`bool`, *optional*, defaults to `False`): + Whether to enforce eager execution. If set to `True`, we will disable CUDA graph and always execute the + model in eager mode. If `False` (default behavior), we will use CUDA graph and eager execution in hybrid. + vllm_model_impl (`str`, *optional*, defaults to `"vllm"`): + Model implementation to use for vLLM. Must be one of `"transformers"` or `"vllm"`. `"transformers"`: Use + the `transformers` backend for model implementation. `"vllm"`: Use the `vllm` library for model + implementation. + kv_cache_dtype (`str`, *optional*, defaults to `"auto"`): + Data type to use for KV cache. If set to `"auto"`, the dtype will default to the model data type. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to trust remote code when loading models. Set to `True` to allow executing code from model + repositories. This is required for some custom models but introduces security risks. + log_level (`str`, *optional*, defaults to `"info"`): + Log level for uvicorn. Possible choices: `"critical"`, `"error"`, `"warning"`, `"info"`, `"debug"`, + `"trace"`. + distributed_executor_backend (`str` or `None`, *optional*): + Distributed executor backend for vLLM. Set to `"ray"` to distribute tensor parallel workers across multiple + nodes via a Ray cluster. Required when `tensor_parallel_size` exceeds the number of local GPUs. If not set, + vLLM defaults to the multiproc backend (single-node only). + speculative_config (`str`, *optional*): + JSON string for vLLM speculative decoding config, forwarded to `LLM(speculative_config=...)`. When unset, + speculative decoding is disabled. Example: `'{"method": "qwen3_next_mtp", "num_speculative_tokens": 5}'`. + """ + + model: str = field( + metadata={"help": "Model name or path to load the model from."}, + ) + revision: str | None = field( + default=None, + metadata={"help": "Revision to use for the model. If not specified, the default branch will be used."}, + ) + tensor_parallel_size: int = field( + default=1, + metadata={"help": "Number of tensor parallel workers to use."}, + ) + data_parallel_size: int = field( + default=1, + metadata={ + "help": "Number of data parallel workers to use. For dense models, keep this at 1. Starting from vLLM " + "`0.14.0`, setting this above `1` for dense models is no longer supported/useful and will error out (see " + "vLLM PR #30739)." + }, + ) + host: str = field( + default="0.0.0.0", + metadata={"help": "Host address to run the server on."}, + ) + port: int = field( + default=8000, + metadata={"help": "Port to run the server on."}, + ) + gpu_memory_utilization: float = field( + default=0.9, + metadata={ + "help": "Ratio (between 0 and 1) of GPU memory to reserve for the model weights, activations, and KV " + "cache on the device dedicated to generation powered by vLLM. Higher values will increase the KV cache " + "size and thus improve the model's throughput. However, if the value is too high, it may cause " + "out-of-memory (OOM) errors during initialization." + }, + ) + dtype: str = field( + default="auto", + metadata={ + "help": "Data type to use for vLLM generation. If set to 'auto', the data type will be automatically " + "determined based on the model configuration. Find the supported values in the vLLM documentation." + }, + ) + max_model_len: int | None = field( + default=None, + metadata={ + "help": "If set, the `max_model_len` to use for vLLM. This can be useful when running with reduced " + "`vllm_gpu_memory_utilization`, leading to a reduced KV cache size. If not set, vLLM will use the model " + "context size, which might be much larger than the KV cache, leading to inefficiencies." + }, + ) + enable_prefix_caching: bool | None = field( + default=None, + metadata={ + "help": "Whether to enable prefix caching in vLLM. If set to `True`, ensure that the model and the " + "hardware support this feature." + }, + ) + enforce_eager: bool | None = field( + default=False, + metadata={ + "help": "Whether to enforce eager execution. If set to `True`, we will disable CUDA graph and always " + "execute the model in eager mode. If `False` (default behavior), we will use CUDA graph and eager " + "execution in hybrid." + }, + ) + kv_cache_dtype: str = field( + default="auto", + metadata={ + "help": "Data type to use for KV cache. If set to 'auto', the dtype will default to the model data type." + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": "Whether to trust remote code when loading models. Set to True to allow executing code from model " + "repositories. This is required for some custom models but introduces security risks." + }, + ) + log_level: str = field( + default="info", + metadata={ + "help": "Log level for uvicorn. Possible choices: 'critical', 'error', 'warning', 'info', 'debug', " + "'trace'." + }, + ) + vllm_model_impl: str = field( + default="vllm", + metadata={ + "help": "Model implementation to use for vLLM. Must be one of `transformers` or `vllm`. `transformers`: " + "Use the `transformers` backend for model implementation. `vllm`: Use the `vllm` library for " + "model implementation." + }, + ) + distributed_executor_backend: str | None = field( + default=None, + metadata={ + "help": "Distributed executor backend for vLLM. When set to 'ray', vLLM uses Ray to distribute tensor " + "parallel workers across multiple nodes. Required when tensor_parallel_size exceeds the number of local " + "GPUs. If not set, vLLM defaults to the multiproc backend (single-node only)." + }, + ) + speculative_config: str | None = field( + default=None, + metadata={ + "help": "JSON string for vLLM speculative decoding config. " + 'Example: \'{"method": "qwen3_next_mtp", "num_speculative_tokens": 5}\'' + }, + ) + + +def llm_worker( + script_args: ScriptArguments, data_parallel_rank: int, master_port: int, connection: Connection +) -> None: + from vllm import LLM + + # Set required environment variables for DP to work with vLLM + os.environ["VLLM_DP_RANK"] = str(data_parallel_rank) + os.environ["VLLM_DP_RANK_LOCAL"] = str(data_parallel_rank) + os.environ["VLLM_DP_SIZE"] = str(script_args.data_parallel_size) + os.environ["VLLM_DP_MASTER_PORT"] = str(master_port) + + llm = LLM( + model=script_args.model, + revision=script_args.revision, + tensor_parallel_size=script_args.tensor_parallel_size, + gpu_memory_utilization=script_args.gpu_memory_utilization, + enforce_eager=script_args.enforce_eager, + dtype=script_args.dtype, + # Automatic Prefix Caching caches the KV cache of existing queries, so that a new query can + # directly reuse the KV cache if it shares the same prefix with one of the existing queries. + # This is particularly useful here because we generate completions from the same prompts. + enable_prefix_caching=script_args.enable_prefix_caching, + kv_cache_dtype=script_args.kv_cache_dtype, + max_model_len=script_args.max_model_len, + worker_extension_cls="trl.scripts.vllm_serve.WeightSyncWorkerExtension", + trust_remote_code=script_args.trust_remote_code, + model_impl=script_args.vllm_model_impl, + distributed_executor_backend=script_args.distributed_executor_backend, + # Important so temperature scaling/logit tweaking affects the TIS log probs + logprobs_mode="processed_logprobs", + speculative_config=json.loads(script_args.speculative_config) if script_args.speculative_config else None, + ) + + # Send ready signal to parent process + connection.send({"status": "ready"}) + + while True: + # Wait for commands from the parent process + try: + command = connection.recv() + except KeyboardInterrupt: + llm.collective_rpc(method="close_communicator") + break + + # Handle commands + if command["type"] in ["call", "fire_and_forget"]: + method_name = command["method"] + args, kwargs = command.get("args", ()), command.get("kwargs", {}) + method = getattr(llm, method_name) + result = method(*args, **kwargs) + if command["type"] == "call": + connection.send(result) + elif command["type"] == "shutdown": + break + + +def chunk_list(lst: list, n: int) -> list[list]: + """ + Split list `lst` into `n` evenly distributed sublists. + + Example: + ```python + >>> chunk_list([1, 2, 3, 4, 5, 6], 2) + [[1, 2, 3], [4, 5, 6]] + + >>> chunk_list([1, 2, 3, 4, 5, 6], 4) + [[1, 2], [3, 4], [5], [6]] + + >>> chunk_list([1, 2, 3, 4, 5, 6], 8) + [[1], [2], [3], [4], [5], [6], [], []] + ``` + """ + k, r = divmod(len(lst), n) + return [lst[i * k + min(i, r) : (i + 1) * k + min(i + 1, r)] for i in range(n)] + + +def main(script_args: ScriptArguments): + import asyncio + + from transformers import is_vision_available + + from trl.generation.vllm_generation import extract_logprobs + from trl.import_utils import ( + is_fastapi_available, + is_pydantic_available, + is_uvicorn_available, + is_vllm_available, + ) + + if not is_fastapi_available(): + raise ImportError( + "FastAPI is required to run the vLLM serve script. Please install it using `pip install fastapi`." + ) + + if not is_pydantic_available(): + raise ImportError( + "Pydantic is required to run the vLLM serve script. Please install it using `pip install pydantic`." + ) + + if not is_uvicorn_available(): + raise ImportError( + "Uvicorn is required to run the vLLM serve script. Please install it using `pip install uvicorn`." + ) + + if not is_vllm_available(): + raise ImportError("vLLM is required to run the vLLM serve script. Please install it using `pip install vllm`.") + + import uvicorn + from fastapi import FastAPI + from pydantic import BaseModel + from vllm import SamplingParams + from vllm.sampling_params import StructuredOutputsParams + from vllm.utils.network_utils import get_open_port + + if is_vision_available(): + from PIL import Image + + logger = logging.getLogger(__name__) + + # Spawn dp workers, and setup pipes for communication + master_port = get_open_port() + connections = [] + processes = [] + for data_parallel_rank in range(script_args.data_parallel_size): + parent_connection, child_connection = Pipe() + process = Process(target=llm_worker, args=(script_args, data_parallel_rank, master_port, child_connection)) + process.start() + connections.append(parent_connection) + processes.append(process) + + @asynccontextmanager + async def lifespan(app: FastAPI): + # Wait for all workers to send "ready" + ready_connections = set() + while len(ready_connections) < script_args.data_parallel_size: + for connection in connections: + msg = connection.recv() + if isinstance(msg, dict) and msg.get("status") == "ready": + ready_connections.add(connection) + + # Start the logprob request batcher background task + batcher_task = asyncio.create_task(_logprob_batcher()) + + yield + + batcher_task.cancel() + + # Wait for processes to terminate + for process in processes: + process.join(timeout=10) # Wait for 10 seconds for the process to terminate + if process.is_alive(): + logger.warning(f"Process {process} is still alive after 10 seconds, attempting to terminate...") + process.terminate() + process.join() # ensure process termination after calling terminate() + + app = FastAPI(lifespan=lifespan) + + # Define the endpoints for the model server + @app.get("/health/") + async def health(): + """ + Health check endpoint to verify that the server is running. + """ + return {"status": "ok"} + + @app.get("/get_world_size/") + async def get_world_size(): + """ + Retrieves the world size of the LLM engine, which is `tensor_parallel_size * data_parallel_size`. + + Returns: + `dict`: + A dictionary containing the world size. + + Example response: + ```json + {"world_size": 8} + ``` + """ + return {"world_size": script_args.tensor_parallel_size * script_args.data_parallel_size} + + class GenerateRequest(BaseModel): + prompts: list[str] | list[list[int]] + images: list[list[str] | None] | None = None + n: int = 1 + repetition_penalty: float = 1.0 + temperature: float = 1.0 + top_p: float = 1.0 + top_k: int = -1 + min_p: float = 0.0 + max_tokens: int = 16 + logprobs: int | None = 0 + structured_outputs_regex: str | None = None + generation_kwargs: dict = field(default_factory=dict) + + class GenerateResponse(BaseModel): + prompt_ids: list[list[int]] + completion_ids: list[list[int]] + logprobs: list[list[list[float | None]]] | None + logprob_token_ids: list[list[list[int]]] | None + + @app.post("/generate/", response_model=GenerateResponse) + async def generate(request: GenerateRequest): + """ + Generates completions for the provided prompts. + + Args: + request (`GenerateRequest`): + - `prompts` (list of `str` or list of list of `int`): A list of prompts. It accepts either text strings + or pre-tokenized token ID lists. When text strings are provided, `images` can optionally be included. + - `images` (list of list of `str` or `None`, *optional*): A list of image lists. Each element is a list + of base64-encoded images for the corresponding prompt, or `None` if no images for that prompt. + - `n` (`int`, *optional*, defaults to `1`): Number of completions to generate for each prompt. + - `repetition_penalty` (`float`, *optional*, defaults to `1.0`): Repetition penalty to apply during + generation. + - `temperature` (`float`, *optional*, defaults to `1.0`): Temperature for sampling. Higher values lead + to more random outputs. + - `top_p` (`float`, *optional*, defaults to `1.0`): Top-p (nucleus) sampling parameter. It controls the + diversity of the generated text. + - `top_k` (`int`, *optional*, defaults to `-1`): Top-k sampling parameter. If set to `-1`, it disables + top-k sampling. + - `min_p` (`float`, *optional*, defaults to `0.0`): Minimum probability threshold for sampling. + - `max_tokens` (`int`, *optional*, defaults to `16`): Maximum number of tokens to generate for each + completion. + - `logprobs` (`int`, *optional*, defaults to `0`): Number of top logprobs to return per token. When 0, + only the sampled token's logprob is returned. When N>0, returns up to N+1 logprobs sorted by + descending probability, because vLLM always includes the sampled token's logprob (which may fall + outside the top-N). + - `structured_outputs_regex` (`str`, *optional*): A regex pattern for structured outputs. If provided, + the model will only generate tokens that match this regex pattern. + - `generation_kwargs` (`dict`, *optional*): Additional generation parameters to pass to the vLLM + `SamplingParams`. This can include parameters like `seed`, `frequency_penalty`, etc. If it contains + keys that conflict with the other parameters, they will override them. + + Returns: + `GenerateResponse`: + - `prompt_ids` (list of list of `int`): A list of lists of token IDs for each input prompt. + - `completion_ids` (list of list of `int`): A list of lists of token IDs for each generated completion. + - `logprobs` (list of list of list of `float`): Per-token logprobs of shape (num_sequences, seq_len, + num_logprobs), sorted by descending probability. + - `logprob_token_ids` (list of list of list of `int`): Token IDs corresponding to each logprob, same + shape as `logprobs`. + + Example request (text prompts): + ```json + {"prompts": ["Hello world", "What is AI?"]} + ``` + + Example request (token IDs): + ```json + {"prompts": [[101, 102], [201, 202]]} + ``` + + Example response: + ```json + { + "prompt_ids": [[101, 102], [201, 202]], + "completion_ids": [[103, 104, 105], [203, 204, 205]], + "logprobs": [[[-0.1], [-0.2], [-0.3]], [[-0.4], [-0.5], [-0.6]]], + "logprob_token_ids": [[[103], [104], [105]], [[203], [204], [205]]] + } + ``` + """ + # Build vLLM-compatible prompt inputs + is_token_ids = request.prompts and isinstance(request.prompts[0], list) + request.images = request.images or [None] * len(request.prompts) + + prompts = [] + for prompt, image_list in zip(request.prompts, request.images, strict=True): + row = {"prompt_token_ids": prompt} if is_token_ids else {"prompt": prompt} + if image_list is not None: + row["multi_modal_data"] = {"image": [Image.open(BytesIO(base64.b64decode(img))) for img in image_list]} + prompts.append(row) + + generation_kwargs = { + "n": request.n, + "repetition_penalty": request.repetition_penalty, + "temperature": request.temperature, + "top_p": request.top_p, + "top_k": request.top_k, + "min_p": request.min_p, + "max_tokens": request.max_tokens, + "logprobs": request.logprobs, + } + generation_kwargs.update(request.generation_kwargs) + + # Structured outputs, if enabled + if request.structured_outputs_regex is not None: + if generation_kwargs.get("structured_outputs") is not None: + logger.warning( + "Both `structured_outputs_regex` and `generation_kwargs['structured_outputs']` are set; " + "`structured_outputs_regex` takes precedence." + ) + generation_kwargs["structured_outputs"] = StructuredOutputsParams(regex=request.structured_outputs_regex) + elif isinstance(structured_outputs_kwargs := generation_kwargs.get("structured_outputs"), dict): + generation_kwargs["structured_outputs"] = StructuredOutputsParams(**structured_outputs_kwargs) + sampling_params = SamplingParams(**generation_kwargs) + + # Evenly distribute prompts across DP ranks + chunked_prompts = chunk_list(prompts, script_args.data_parallel_size) + + # Send the prompts to each worker + for connection, prompts in zip(connections, chunked_prompts, strict=True): + # When the number of prompts is less than data_parallel_size, some workers will receive empty prompts. + # However, vLLM requires that we always send at least one prompt. So we send a placeholder prompt to comply + # with vLLM's requirement, and we later ignore the result. + if not prompts: + prompts = [""] + kwargs = {"prompts": prompts, "sampling_params": sampling_params} + connection.send({"type": "call", "method": "generate", "kwargs": kwargs}) + + # Receive results + all_outputs = [connection.recv() for connection in connections] + + # Handle empty prompts (see above) + all_outputs = [output for output, prompts in zip(all_outputs, chunked_prompts, strict=True) if prompts] + + # Flatten and combine all results + all_outputs = list(chain.from_iterable(all_outputs)) # from list of list to single list + prompt_ids = [output.prompt_token_ids for output in all_outputs] + completion_ids = [list(output.token_ids) for outputs in all_outputs for output in outputs.outputs] + logprobs, logprob_token_ids = extract_logprobs(all_outputs) + + return { + "prompt_ids": prompt_ids, + "completion_ids": completion_ids, + "logprobs": logprobs, + "logprob_token_ids": logprob_token_ids, + } + + class SequenceLogprobsRequest(BaseModel): + sequences: list[list[int]] + prompt_lengths: list[int] + top_logprobs: int = 100 + temperature: float = 1.0 + response_format: str = "json" # "json" (legacy) or "binary" (base64 numpy arrays) + + class SequenceLogprobsResponse(BaseModel): + logprobs: list[list[list[float | None]]] | None = None + logprob_token_ids: list[list[list[int]]] | None = None + # Binary format fields (base64-encoded numpy arrays) + logprobs_b64: str | None = None + token_ids_b64: str | None = None + actual_logprobs_b64: str | None = None + actual_token_ids_b64: str | None = None + shape: list[int] | None = None # [batch_size, max_completion_len, top_logprobs] + completion_lengths: list[int] | None = None # actual completion length per sample + + def _run_prompt_logprobs(prompts, sampling_params): + """Send prompts to DP workers and collect outputs.""" + chunked_prompts = chunk_list(prompts, script_args.data_parallel_size) + for connection, chunk in zip(connections, chunked_prompts, strict=True): + if not chunk: + chunk = [{"prompt_token_ids": [0]}] + kwargs = {"prompts": chunk, "sampling_params": sampling_params} + connection.send({"type": "call", "method": "generate", "kwargs": kwargs}) + all_outputs = [connection.recv() for connection in connections] + all_outputs = [output for output, chunk in zip(all_outputs, chunked_prompts, strict=True) if chunk] + return list(chain.from_iterable(all_outputs)) + + # ── Request batching for get_sequence_logprobs ── + # Collects concurrent requests into batches and dispatches them together so that + # all DP workers stay busy. Without this, async endpoint handlers block the event + # loop during pipe I/O, serializing requests and leaving DP workers idle. + _logprob_queue: asyncio.Queue = asyncio.Queue() + + # Maximum time (seconds) to wait for more requests before dispatching a batch. + _BATCH_WAIT_S = 0.005 # 5ms - short enough to not add much latency when lightly loaded + # Maximum number of HTTP requests to collect per batcher cycle + _MAX_BATCH_REQUESTS = max(script_args.data_parallel_size * 4, 16) + # Maximum total tokens per batch. prompt_logprobs materializes full-vocab logits + # during the forward pass, so each worker can safely handle ~1 max-length sequence. + # Budget = max_model_len * dp_size gives ~1 sequence per worker at max length. + _max_model_len = script_args.max_model_len or 8192 + _MAX_BATCH_TOKENS = _max_model_len * script_args.data_parallel_size + + async def _logprob_batcher(): + """Background task that continuously drains the queue, batches requests, and dispatches.""" + loop = asyncio.get_running_loop() + + while True: + batch = [] + try: + # Wait for the first request + batch_tokens = 0 + item = await _logprob_queue.get() + batch.append(item) + # Count tokens in this item's sequences + for prompt in item[0]: + batch_tokens += len(prompt.get("prompt_token_ids", [])) + + # Collect more requests up to batch limit, timeout, or token budget + deadline = loop.time() + _BATCH_WAIT_S + while len(batch) < _MAX_BATCH_REQUESTS and batch_tokens < _MAX_BATCH_TOKENS: + remaining = deadline - loop.time() + if remaining <= 0: + break + try: + item = await asyncio.wait_for(_logprob_queue.get(), timeout=remaining) + # Check if adding this item would exceed the token budget + item_tokens = sum(len(p.get("prompt_token_ids", [])) for p in item[0]) + if batch_tokens + item_tokens > _MAX_BATCH_TOKENS and len(batch) > 0: + # Put it back and dispatch current batch + await _logprob_queue.put(item) + break + batch.append(item) + batch_tokens += item_tokens + except asyncio.TimeoutError: + break + + # batch is a list of (prompts, prompt_lengths, top_logprobs, temperature, response_format, future) + # All items in a batch must share the same (top_logprobs, temperature) pair. + # Group by those execution parameters to handle mixed requests. + groups = {} + for prompts, prompt_lengths, top_logprobs, temperature, response_format, future in batch: + key = (top_logprobs, temperature) + if key not in groups: + groups[key] = [] + groups[key].append((prompts, prompt_lengths, response_format, future)) + + for (top_logprobs, temperature), items in groups.items(): + # Merge all sequences into a single batch + all_prompts = [] + all_prompt_lengths = [] + offsets = [] # (start_idx, count) per original request + for prompts, prompt_lengths, _response_format, _future in items: + start = len(all_prompts) + all_prompts.extend(prompts) + all_prompt_lengths.extend(prompt_lengths) + offsets.append((start, len(prompts))) + + sampling_params = SamplingParams( + max_tokens=1, + temperature=temperature, + prompt_logprobs=top_logprobs, + ) + + # Dispatch to workers in a thread to avoid blocking the event loop + try: + all_outputs = await loop.run_in_executor( + None, _run_prompt_logprobs, all_prompts, sampling_params + ) + + # Split results back to individual requests + for (start, count), (_, prompt_lengths, response_format, future) in zip( + offsets, items, strict=True + ): + outputs_slice = all_outputs[start : start + count] + if not future.done(): + future.set_result((outputs_slice, prompt_lengths, top_logprobs, response_format)) + except Exception as e: + # Signal error to all waiting requests in this execution-parameter group + for *_, future in items: + if not future.done(): + future.set_exception(e) + except Exception as e: + # Prevent killing the batcher task — signal error to all unfulfilled futures + for *_, future in batch: + if not future.done(): + future.set_exception(e) + + def _format_logprob_response(all_outputs, prompt_lengths, top_k, response_format): + """Format vLLM outputs into the response dict (runs in any thread).""" + import numpy as np + + batch_size = len(all_outputs) + use_binary = response_format == "binary" + + if use_binary: + from starlette.responses import Response + + comp_lengths = [] + for output, prompt_length in zip(all_outputs, prompt_lengths, strict=True): + prompt_lps = output.prompt_logprobs + if prompt_lps is None: + raise ValueError("prompt_logprobs is None.") + comp_lengths.append(len(prompt_lps) - prompt_length) + + max_comp_len = max(comp_lengths) if comp_lengths else 0 + + # logprobs_arr / token_ids_arr: teacher's sorted top-k logprobs + token ids (for forward KL). + # actual_logprobs_arr / actual_token_ids_arr: actual token's teacher logprob (for reverse KL). + logprobs_arr = np.full((batch_size, max_comp_len, top_k), float("-inf"), dtype=np.float32) + token_ids_arr = np.zeros((batch_size, max_comp_len, top_k), dtype=np.int32) + actual_logprobs_arr = np.full((batch_size, max_comp_len, 1), float("-inf"), dtype=np.float32) + actual_token_ids_arr = np.zeros((batch_size, max_comp_len, 1), dtype=np.int32) + + for i, (output, prompt_length) in enumerate(zip(all_outputs, prompt_lengths, strict=True)): + prompt_lps = output.prompt_logprobs + seq_tokens = output.prompt_token_ids + if comp_lengths[i] == 0: + continue + + for pos in range(prompt_length, len(prompt_lps)): + lp = prompt_lps[pos] + if lp is None: + continue + t = pos - prompt_length + actual_token = seq_tokens[pos] + + # Actual token's logprob (for reverse KL) + if actual_token in lp: + val = lp[actual_token].logprob + if not math.isnan(val): + actual_logprobs_arr[i, t, 0] = val + actual_token_ids_arr[i, t, 0] = actual_token + + # Teacher's top-k logprobs (for forward KL) + if top_k == 1: + # Fast path: find rank-1 directly instead of sorting + for token_id, logprob_obj in lp.items(): + if logprob_obj.rank == 1: + val = logprob_obj.logprob + if not math.isnan(val): + logprobs_arr[i, t, 0] = val + token_ids_arr[i, t, 0] = token_id + break + else: + sorted_items = sorted(lp.items(), key=lambda x: x[1].rank) + for k_idx, (token_id, logprob_obj) in enumerate(sorted_items[:top_k]): + val = logprob_obj.logprob + if not math.isnan(val): + logprobs_arr[i, t, k_idx] = val + token_ids_arr[i, t, k_idx] = token_id + + payload = { + "logprobs_b64": base64.b64encode(logprobs_arr.tobytes()).decode("ascii"), + "token_ids_b64": base64.b64encode(token_ids_arr.tobytes()).decode("ascii"), + "actual_logprobs_b64": base64.b64encode(actual_logprobs_arr.tobytes()).decode("ascii"), + "actual_token_ids_b64": base64.b64encode(actual_token_ids_arr.tobytes()).decode("ascii"), + "shape": [batch_size, max_comp_len, top_k], + "completion_lengths": comp_lengths, + } + + try: + import orjson + + return Response(content=orjson.dumps(payload), media_type="application/json") + except ImportError: + return payload + else: + all_logprobs = [] + all_token_ids = [] + for output, prompt_length in zip(all_outputs, prompt_lengths, strict=True): + prompt_lps = output.prompt_logprobs + if prompt_lps is None: + raise ValueError("prompt_logprobs is None.") + seq_logprobs = [] + seq_token_ids = [] + for pos in range(prompt_length, len(prompt_lps)): + lp = prompt_lps[pos] + if lp is None: + seq_logprobs.append([]) + seq_token_ids.append([]) + continue + sorted_items = sorted(lp.items(), key=lambda x: x[1].rank) + seq_token_ids.append([token_id for token_id, _ in sorted_items]) + seq_logprobs.append( + [None if math.isnan(item.logprob) else item.logprob for _, item in sorted_items] + ) + all_logprobs.append(seq_logprobs) + all_token_ids.append(seq_token_ids) + return {"logprobs": all_logprobs, "logprob_token_ids": all_token_ids} + + @app.post("/get_sequence_logprobs/", response_model=SequenceLogprobsResponse) + async def get_sequence_logprobs(request: SequenceLogprobsRequest): + """ + Computes teacher logprobs for existing token sequences without generating new tokens. + + Concurrent requests are automatically batched and dispatched together to maximize GPU utilization across DP + workers. This avoids the event-loop-blocking problem where synchronous pipe I/O serializes requests despite + having multiple DP workers. + + Args: + request (`SequenceLogprobsRequest`): + - `sequences` (list of list of `int`): Full token sequences (prompt + completion) per sample. + - `prompt_lengths` (list of `int`): Number of prompt tokens per sequence; completion logprobs start + after each prompt. + - `top_logprobs` (`int`, *optional*, defaults to `100`): Number of top teacher logprobs to return per + completion position (sorted by vLLM rank). + - `temperature` (`float`, *optional*, defaults to `1.0`): Sampling temperature passed to vLLM for + logprob computation. + - `response_format` (`str`, *optional*, defaults to `"json"`): Either `"json"` (nested lists, + backward-compatible) or `"binary"` (base64-encoded numpy arrays for fast serialization). + + Returns: + `SequenceLogprobsResponse` or Starlette `Response`: + When `response_format` is `"json"`, a JSON object with: + - `logprobs` (list of list of list of `float` or `None`): Top-k teacher logprobs per completion token. + - `logprob_token_ids` (list of list of list of `int`): Token IDs aligned with `logprobs`. + When `response_format` is `"binary"`, a JSON response (Starlette `Response` if `orjson` is installed) + whose body is a JSON object with base64-encoded float32/int32 arrays: `logprobs_b64`, `token_ids_b64`, + `actual_logprobs_b64`, `actual_token_ids_b64`, plus `shape` (`list[int]`, `[batch_size, + max_completion_len, top_k]`) and `completion_lengths` (`list[int]`). + """ + if len(request.sequences) != len(request.prompt_lengths): + raise ValueError("sequences and prompt_lengths must have the same length.") + + for i, (seq, pl) in enumerate(zip(request.sequences, request.prompt_lengths, strict=True)): + if pl < 0 or pl > len(seq): + raise ValueError( + f"Sequence {i} has prompt_length={pl} which is out of range [0, {len(seq)}]. " + f"prompt_length must be between 0 and the sequence length inclusive." + ) + + # Validate sequence lengths against max_model_len to prevent worker OOM crashes + if _max_model_len: + for i, seq in enumerate(request.sequences): + if len(seq) > _max_model_len: + raise ValueError( + f"Sequence {i} has length {len(seq)} which exceeds max_model_len={_max_model_len}. " + f"Truncate sequences or increase --max-model-len." + ) + + prompts = [{"prompt_token_ids": seq} for seq in request.sequences] + + # Submit to the batching queue and await result + loop = asyncio.get_running_loop() + future = loop.create_future() + await _logprob_queue.put( + ( + prompts, + list(request.prompt_lengths), + request.top_logprobs, + request.temperature, + request.response_format, + future, + ) + ) + + # Wait for the batcher to process our request + all_outputs, prompt_lengths, top_k, response_format = await future + + return await loop.run_in_executor( + None, _format_logprob_response, all_outputs, prompt_lengths, top_k, response_format + ) + + class ChatRequest(BaseModel): + messages: list[list[dict]] + n: int = 1 + repetition_penalty: float = 1.0 + temperature: float = 1.0 + top_p: float = 1.0 + top_k: int = -1 + min_p: float = 0.0 + max_tokens: int = 16 + logprobs: int | None = 0 + structured_outputs_regex: str | None = None + generation_kwargs: dict = field(default_factory=dict) + chat_template_kwargs: dict = field(default_factory=dict) + tools: list | None = None + + class ChatResponse(BaseModel): + prompt_ids: list[list[int]] + completion_ids: list[list[int]] + logprobs: list[list[list[float | None]]] | None + logprob_token_ids: list[list[list[int]]] | None + + @app.post("/chat/", response_model=ChatResponse) + async def chat(request: ChatRequest): + """ + Generates completions for the provided chat messages. + + Args: + request (`ChatRequest`): + - `messages` (list of `dict`): A list of messages (dicts with "role" and "content" keys) for the model + to generate completions. + - `n` (`int`, *optional*, defaults to `1`): Number of completions to generate for each prompt. + - `repetition_penalty` (`float`, *optional*, defaults to `1.0`): Repetition penalty to apply during + generation. + - `temperature` (`float`, *optional*, defaults to `1.0`): Temperature for sampling. Higher values lead + to more random outputs. + - `top_p` (`float`, *optional*, defaults to `1.0`): Top-p (nucleus) sampling parameter. It controls the + diversity of the generated text. + - `top_k` (`int`, *optional*, defaults to `-1`): Top-k sampling parameter. If set to `-1`, it disables + top-k sampling. + - `min_p` (`float`, *optional*, defaults to `0.0`): Minimum probability threshold for sampling. + - `max_tokens` (`int`, *optional*, defaults to `16`): Maximum number of tokens to generate for each + completion. + - `logprobs` (`int`, *optional*, defaults to `0`): Number of top logprobs to return per token. When 0, + only the sampled token's logprob is returned. When N>0, returns up to N+1 logprobs sorted by + descending probability, because vLLM always includes the sampled token's logprob (which may fall + outside the top-N). + - `structured_outputs_regex` (`str`, *optional*): A regex pattern for structured outputs. If provided, + the model will only generate tokens that match this regex pattern. + - `generation_kwargs` (`dict`, *optional*): Additional generation parameters to pass to the vLLM + `SamplingParams`. This can include parameters like `seed`, `frequency_penalty`, etc. If it contains + keys that conflict with the other parameters, they will override them. + - `chat_template_kwargs` (`dict`, *optional*): Additional keyword arguments to pass to the chat + template. + + Returns: + `ChatResponse`: + - `prompt_ids` (list of list of `int`): A list of lists of token IDs for each input prompt. + - `completion_ids` (list of list of `int`): A list of lists of token IDs for each generated completion. + - `logprobs` (list of list of list of `float`): Per-token logprobs of shape (num_sequences, seq_len, + num_logprobs), sorted by descending probability. + - `logprob_token_ids` (list of list of list of `int`): Token IDs corresponding to each logprob, same + shape as `logprobs`. + + Example request: + ```bash + curl -X POST 'http://0.0.0.0:8000/chat/' \ + -H 'Content-Type: application/json' \ + -d '{"messages": [[{ "role": "user", "content": "Hello!" }]]}' + ``` + + Example response: + ```json + { + "prompt_ids": [[151644, 872, 198, 9707, 0, 151645, 198, 151644, 77091, 198]], + "completion_ids": [[151667, 198, 32313, 11, 279]], + "logprobs": [[[-0.0003], [-3.58e-07], [-0.0902], [-6.39e-05], [-0.0387]]], + "logprob_token_ids": [[[151667], [198], [32313], [11], [279]]] + } + ``` + """ + # Convert PIL images to base64 strings + for message_list in request.messages: + for message in message_list: + if isinstance(message["content"], list): + for part in message["content"]: + if part["type"] == "image_pil": + part["image_pil"] = Image.open(BytesIO(base64.b64decode(part["image_pil"]))) + + generation_kwargs = { + "n": request.n, + "repetition_penalty": request.repetition_penalty, + "temperature": request.temperature, + "top_p": request.top_p, + "top_k": request.top_k, + "min_p": request.min_p, + "max_tokens": request.max_tokens, + "logprobs": request.logprobs, + } + generation_kwargs.update(request.generation_kwargs) + + # Structured outputs, if enabled + if request.structured_outputs_regex is not None: + if generation_kwargs.get("structured_outputs") is not None: + logger.warning( + "Both `structured_outputs_regex` and `generation_kwargs['structured_outputs']` are set; " + "`structured_outputs_regex` takes precedence." + ) + generation_kwargs["structured_outputs"] = StructuredOutputsParams(regex=request.structured_outputs_regex) + elif isinstance(structured_outputs_kwargs := generation_kwargs.get("structured_outputs"), dict): + generation_kwargs["structured_outputs"] = StructuredOutputsParams(**structured_outputs_kwargs) + sampling_params = SamplingParams(**generation_kwargs) + + # Evenly distribute prompts across DP ranks + chunked_messages = chunk_list(request.messages, script_args.data_parallel_size) + + # Send the messages to each worker + for connection, messages in zip(connections, chunked_messages, strict=True): + # When the number of messages is less than data_parallel_size, some workers will receive empty messages. + # However, vLLM requires that we always send at least one prompt. So we send a placeholder prompt to comply + # with vLLM's requirement, and we later ignore the result. + if not messages: + messages = [[{"role": "user", "content": ""}]] + kwargs = { + "messages": messages, + "sampling_params": sampling_params, + "chat_template_kwargs": request.chat_template_kwargs, + "tools": request.tools, + } + connection.send({"type": "call", "method": "chat", "kwargs": kwargs}) + + # Receive results + all_outputs = [connection.recv() for connection in connections] + + # Handle empty prompts (see above) + all_outputs = [output for output, prompts in zip(all_outputs, chunked_messages, strict=True) if prompts] + + # Flatten and combine all results + all_outputs = list(chain.from_iterable(all_outputs)) # from list of list to single list + prompt_ids = [output.prompt_token_ids for output in all_outputs] + completion_ids = [list(output.token_ids) for outputs in all_outputs for output in outputs.outputs] + logprobs, logprob_token_ids = extract_logprobs(all_outputs) + + return { + "prompt_ids": prompt_ids, + "completion_ids": completion_ids, + "logprobs": logprobs, + "logprob_token_ids": logprob_token_ids, + } + + class InitCommunicatorRequest(BaseModel): + host: str + port: int + world_size: int + client_device_uuid: str + + @app.post("/init_communicator/") + async def init_communicator(request: InitCommunicatorRequest): + """ + Initializes the communicator for synchronizing model weights between a client and multiple server workers. + + Args: + request (`InitCommunicatorRequest`): + - `host` (`str`): Hostname or IP address of the master node. + - `port` (`int`): Port number to be used for communication. + - `world_size` (`int`): Total number of participating processes in the group. + - `client_device_uuid` (`str`): UUID of the device of client main process. Used to assert that devices + are different from vLLM workers devices. + """ + world_size = script_args.tensor_parallel_size * script_args.data_parallel_size + 1 + + # The function init_communicator is called this way: init_communicator(host, port, world_size) + # So with collective_rpc we need to call it this way: + # llm.collective_rpc(method="init_communicator", args=(host, port, world_size)) + kwargs = { + "method": "init_communicator", + "args": (request.host, request.port, world_size, request.client_device_uuid), + } + for connection in connections: + connection.send({"type": "fire_and_forget", "method": "collective_rpc", "kwargs": kwargs}) + + return {"message": "Request received, initializing communicator"} + + class UpdateWeightsRequest(BaseModel): + name: str + dtype: str + shape: list[int] + + @app.post("/update_named_param/") + async def update_named_param(request: UpdateWeightsRequest): + """ + Updates the model weights with the provided tensor. + + Once this endpoint is called, the client process should broadcast the updated weights to all server workers. + + Args: + request (`UpdateWeightsRequest`): + - `name` (`str`): Name of the weight tensor being updated. + - `dtype` (`str`): Data type of the weight tensor (e.g., `"torch.float32"`). + - `shape` (list of `int`): Shape of the weight + + """ + # The function update_named_param is called this way: update_named_param("name", "torch.float32", (10, 10)) + # So with collective_rpc we need to call it this way: + # llm.collective_rpc("update_named_param", args=("name", "torch.float32", (10, 10))) + kwargs = {"method": "update_named_param", "args": (request.name, request.dtype, tuple(request.shape))} + for connection in connections: + connection.send({"type": "fire_and_forget", "method": "collective_rpc", "kwargs": kwargs}) + + return {"message": "Request received, updating named parameter"} + + @app.post("/reset_prefix_cache/") + async def reset_prefix_cache(): + """ + Resets the prefix cache for the model. + """ + for connection in connections: + connection.send({"type": "call", "method": "reset_prefix_cache"}) + # Wait for and collect all results + all_outputs = [connection.recv() for connection in connections] + success = all(output for output in all_outputs) + return {"message": "Request received, resetting prefix cache status: " + str(success)} + + @app.post("/close_communicator/") + async def close_communicator(): + """ + Closes the weight update group and cleans up associated resources. + """ + kwargs = {"method": "close_communicator"} + for connection in connections: + connection.send({"type": "fire_and_forget", "method": "collective_rpc", "kwargs": kwargs}) + return {"message": "Request received, closing communicator"} + + # Start the server + uvicorn.run(app, host=script_args.host, port=script_args.port, log_level=script_args.log_level) + + +def make_parser(subparsers: argparse._SubParsersAction | None = None, prog: str | None = None): + from trl import TrlParser + + if subparsers is not None: + parser = subparsers.add_parser("vllm-serve", help="Run the vLLM serve script", dataclass_types=ScriptArguments) + else: + parser = TrlParser(ScriptArguments, prog=prog) + return parser + + +if __name__ == "__main__": + parser = make_parser() + (script_args,) = parser.parse_args_and_config() + main(script_args) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/skills/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/skills/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..29603ebfd06c6042f7892ccff7426cf38a2936b7 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/skills/__init__.py @@ -0,0 +1,21 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .skills import ( + install_skill, + list_agent_names, + list_skills, + resolve_target_path, + uninstall_skill, +) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/skills/cli.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/skills/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..712f50d1b0b61d751a547dc99224d71b934785fc --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/skills/cli.py @@ -0,0 +1,199 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +CLI commands for TRL skills installation and management. + +This module provides command-line interface for installing TRL skills to various AI agent directories. +""" + +import argparse + +from .skills import install_skill, list_agent_names, list_skills, resolve_target_path, uninstall_skill + + +def add_skills_subcommands(subparsers: argparse._SubParsersAction) -> None: + """ + Add skills subcommands to the parser. + + This creates nested subcommands under 'trl skills' for managing skill installations. + + Args: + subparsers: Subparsers from 'trl skills' command + """ + # Parent parser for common target options + target_parser = argparse.ArgumentParser(add_help=False) + target_parser.add_argument( + "--target", + default="agents", + help=f"Installation target: agent name ({', '.join(list_agent_names())}) or directory path", + ) + target_parser.add_argument( + "--scope", + choices=["project", "global"], + default="project", + help="Scope when using --target with agent name: project (./agents/skills/) or global (user-level like ~/.agents/skills/)", + ) + + # trl skills list (no target required - lists TRL's built-in skills by default) + list_parser = subparsers.add_parser( + "list", + help="List available TRL skills or installed skills in a target", + description="Show TRL skills available for installation, or if --target is specified, show installed skills", + ) + list_parser.add_argument( + "--target", + help="Optional: show installed skills in target (agent name or directory path)", + ) + list_parser.add_argument( + "--scope", + choices=["project", "global"], + default="project", + help="Scope when using --target with agent name: project (./agents/skills/) or global (user-level like ~/.agents/skills/)", + ) + list_parser.set_defaults(func=cmd_list) + + # trl skills install + install_parser = subparsers.add_parser( + "install", + parents=[target_parser], + help="Install skill", + description="Install TRL skill to target", + ) + install_parser.add_argument("skill", nargs="?", help="Skill name to install (omit to use --all)") + install_parser.add_argument("--all", action="store_true", help="Install all available TRL skills") + install_parser.add_argument("--force", action="store_true", help="Overwrite if skill already exists") + install_parser.set_defaults(func=cmd_install) + + # trl skills uninstall + uninstall_parser = subparsers.add_parser( + "uninstall", + parents=[target_parser], + help="Uninstall skill from target", + description="Remove a TRL skill from an AI agent's skills directory", + ) + uninstall_parser.add_argument("skill", help="Skill name to uninstall") + uninstall_parser.set_defaults(func=cmd_uninstall) + + +def cmd_install(args): + """Handle 'trl skills install' command.""" + # Validate arguments + if not args.skill and not args.all: + print("Error: Either provide a skill name or use --all to install all skills") + print("Usage: trl skills install --target ") + print(" or: trl skills install --all --target ") + return 1 + + if args.skill and args.all: + print("Error: Cannot specify both a skill name and --all") + return 1 + + # Determine skills to install + if args.all: + skills_to_install = list_skills() + if not skills_to_install: + print("No skills available to install") + return 1 + print(f"Installing {len(skills_to_install)} skills to {args.target}") + else: + skills_to_install = [args.skill] + + # Install each skill + success_count = 0 + for skill_name in skills_to_install: + try: + print(f"Installing '{skill_name}'...", end=" ") + install_skill( + skill_name=skill_name, + target=args.target, + scope=args.scope, + force=args.force, + ) + print("✓") + success_count += 1 + + except FileExistsError as e: + print("✗") + print(f" Error: {e}") + if not args.force: + print(" Use --force to overwrite") + except (FileNotFoundError, ValueError) as e: + print("✗") + print(f" Error: {e}") + + # Summary + print(f"\n{success_count}/{len(skills_to_install)} skills installed successfully") + + if success_count > 0: + target_path = resolve_target_path(args.target, args.scope) + print(f"\nSkills are now available at: {target_path}") + print("You may need to restart your AI agent to use the new skills.") + + return 0 if success_count == len(skills_to_install) else 1 + + +def cmd_uninstall(args): + """Handle 'trl skills uninstall' command.""" + try: + print(f"Uninstalling '{args.skill}' from {args.target}...", end=" ") + uninstall_skill(args.skill, target=args.target, scope=args.scope) + print("✓") + print(f"\nSkill '{args.skill}' has been removed") + return 0 + + except (FileNotFoundError, PermissionError, ValueError) as e: + print("✗") + print(f"Error: {e}") + return 1 + + +def cmd_list(args): + """Handle 'trl skills list' command.""" + try: + # List skills - if no target specified, list TRL's built-in skills + if args.target: + skills = list_skills(target=args.target, scope=args.scope) + location = args.target + else: + skills = list_skills() + location = "TRL (available for installation)" + + if not skills: + if args.target: + print(f"No skills installed in {args.target}") + else: + print("No TRL skills available") + return 0 + + print(f"\nSkills in {location}:\n") + + for skill in skills: + print(f" {skill}") + + print(f"\nTotal: {len(skills)} skill(s)") + + if not args.target: + print("\nUse 'trl skills install --target ' to install a skill") + + return 0 + + except ValueError as e: + print(f"Error: {e}") + return 1 + + +__all__ = [ + "add_skills_subcommands", +] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/skills/skills.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/skills/skills.py new file mode 100644 index 0000000000000000000000000000000000000000..c4ddb152cf72daedfcb1fc30da7c431debf12f0e --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/skills/skills.py @@ -0,0 +1,353 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Agent Skills. + +This module: +- provides utilities for discovering and accessing TRL skills that can be used by AI agents to learn how to use the TRL + CLI +- handles installation, uninstallation, and management of TRL skills +- defines where different AI agents and coding tools look for skills, enabling easy installation of TRL skills to the + appropriate directories + +Agent Skills are folders of instructions, scripts, and resources that agents can discover and use to perform tasks more +accurately and efficiently. Learn more at https://agentskills.io +""" + +import importlib.resources as resources +import shutil +from pathlib import Path + + +AGENT_PATHS = { + "agents": { + "global": Path("~/.agents/skills"), + "project": Path("./.agents/skills"), + }, + "claude": { + "global": Path("~/.claude/skills"), + "project": Path("./.claude/skills"), + }, +} + + +def list_agent_names() -> list[str]: + """ + List available predefined agent names. + + Returns: + `list[str]`: Sorted list of agent names (e.g., ['agents', 'claude']). + """ + return sorted(AGENT_PATHS.keys()) + + +def _get_trl_skills_dir() -> Path: + """ + Get the path to the TRL skills directory. + + This is the directory inside the TRL package containing skills that can be installed to AI agent directories. + + Returns: + `Path`: TRL skills directory. + """ + return Path(str(resources.files("trl.skills"))) + + +def resolve_target_path(target: str | Path, scope: str = "project") -> Path: + """ + Resolve target to a concrete directory path. + + Converts semantic agent names (e.g., 'claude') with scope to actual filesystem paths, or normalizes provided paths. + + Args: + target (`str | Path`): Agent name (e.g., 'agents', 'claude') or directory path. + scope (`str`, defaults to `"project"`): + Scope for agent names: 'global' (user-level like ~/.agents/skills/) or 'project' (./agents/skills/). + + Returns: + `Path`: Resolved absolute path. + + Raises: + `ValueError`: If `scope` is invalid for a predefined agent target. + + Example: + ```python + >>> from trl.skills import resolve_target_path + + >>> # Resolve agent name with scope + >>> resolve_target_path("claude", "global") + /home/user/.claude/skills + + >>> # Resolve custom path + >>> resolve_target_path("/custom/skills") + /custom/skills + ``` + """ + if isinstance(target, Path): + return target.expanduser().resolve() + + # Check if it's a predefined agent + if target in AGENT_PATHS: + if scope not in AGENT_PATHS[target]: + valid_scopes = ", ".join(sorted(AGENT_PATHS[target])) + raise ValueError(f"Invalid scope '{scope}' for agent '{target}'. Expected one of: {valid_scopes}") + agent_path = AGENT_PATHS[target][scope] + return agent_path.expanduser().resolve() + + # Treat as custom path string + return Path(target).expanduser().resolve() + + +def _list_skills_in_dir(skills_dir: Path) -> list[str]: + """ + List skills in directory. + + A skill is a directory containing a SKILL.md file. + + Args: + skills_dir (`Path`): Skills directory to scan. + + Returns: + `list[str]`: Skill names (directory names containing SKILL.md). + """ + if not skills_dir.exists(): + return [] + skills = [] + for item in skills_dir.iterdir(): + if item.is_dir() and (item / "SKILL.md").exists(): + skills.append(item.name) + return sorted(skills) + + +def list_skills(target: str | Path | None = None, scope: str = "project") -> list[str]: + """ + List skills. + + A skill is a directory containing a SKILL.md file. + + Args: + target (`str | Path`, *optional*): + Agent name (e.g., 'claude'), directory path, or `None` for TRL's built-in skills. + scope (`str`, defaults to `"project"`): + For agent names: 'global' (user-level) or 'project' (current directory). + + Returns: + `list[str]`: Skill names (directory names containing SKILL.md). + + Example: + ```python + >>> from trl.skills import list_skills + + >>> # List TRL's built-in skills + >>> list_skills() + ['trl-training'] + + >>> # List skills installed for Claude globally + >>> list_skills(target="claude", scope="global") + ['trl-training', 'custom-skill'] + + >>> # List skills in custom directory + >>> list_skills(target="/path/to/skills") + [...] + ``` + """ + if target is None: + # List TRL's built-in skills + return _list_skills_in_dir(_get_trl_skills_dir()) + + target_dir = resolve_target_path(target, scope) + return _list_skills_in_dir(target_dir) + + +def _install_skill_to_dir( + skill_name: str, + target_dir: Path, + source_dir: Path, + force: bool = False, +) -> bool: + """ + Install a skill to target directory. + + Args: + skill_name (`str`): Name of skill to install. + target_dir (`Path`): Target installation directory. + source_dir (`Path`): Source directory containing skills. + force (`bool`, defaults to `False`): Whether to overwrite if exists. + + Returns: + `bool`: True if installed successfully. + + Raises: + - `FileNotFoundError`: If skill doesn't exist in source_dir. + - `FileExistsError`: If skill already installed and not force. + - `PermissionError`: If no permission to write to target_dir. + - `ValueError`: If source_dir entry exists but is not a directory. + - `OSError`: If copying the skill fails. + """ + source_skill = source_dir / skill_name + + # Check if source skill exists + if not source_skill.exists(): + available = ", ".join(list_skills(target=source_dir)) + source_msg = f"source directory {source_dir}" + if available: + raise FileNotFoundError(f"Skill '{skill_name}' not found in {source_msg}. Available skills: {available}") + raise FileNotFoundError(f"Skill '{skill_name}' not found in {source_msg}") + + if not source_skill.is_dir(): + raise ValueError(f"Skill '{skill_name}' is not a directory") + + target_skill = target_dir / skill_name + + # Check if already exists + if target_skill.exists() and not force: + raise FileExistsError(f"Skill '{skill_name}' already installed at {target_skill}. Use --force to overwrite.") + + # Create target directory + try: + target_dir.mkdir(parents=True, exist_ok=True) + except PermissionError as e: + raise PermissionError(f"Cannot create directory {target_dir}: {e}") from e + + # Remove existing if force + if target_skill.exists() and force: + if target_skill.is_symlink(): + target_skill.unlink() + else: + shutil.rmtree(target_skill) + + # Install + try: + shutil.copytree(source_skill, target_skill) + except OSError as e: + raise OSError(f"Failed to install skill: {e}") from e + + return True + + +def install_skill( + skill_name: str, + target: str | Path, + scope: str = "project", + source: str | Path | None = None, + force: bool = False, +) -> bool: + """ + Install a skill. + + Args: + skill_name (`str`): Name of skill to install. + target (`str | Path`): Agent name (e.g., 'agents', 'claude') or directory path. + scope (`str`, defaults to `"project"`): + Scope for agent names: 'global' (user-level) or 'project' (current directory). + source (`str | Path`, *optional*): + Source directory containing skills. If `None`, defaults to TRL skills directory. + force (`bool`, defaults to `False`): Whether to overwrite if skill already exists. + + Returns: + `bool`: True if installed successfully. + + Raises: + - `FileNotFoundError`: If skill doesn't exist in source. + - `FileExistsError`: If skill already installed and not force. + - `PermissionError`: If no permission to write to target. + - `ValueError`: + - If `scope` is invalid for a predefined agent target. + - If `source` entry exists but is not a directory. + - `OSError`: If copying the skill fails. + + Example: + ```python + >>> from trl.skills import install_skill + + >>> # Install to Claude's global skills directory + >>> install_skill("trl-training", target="claude", scope="global") + + >>> # Install to custom directory + >>> install_skill("trl-training", target="/path/to/skills") + + >>> # Overwrite existing installation + >>> install_skill("trl-training", target="claude", force=True) + ``` + """ + target_dir = resolve_target_path(target, scope) + source_dir = Path(source).expanduser().resolve() if source else _get_trl_skills_dir() + return _install_skill_to_dir(skill_name, target_dir, source_dir, force) + + +def _uninstall_skill_from_dir(skill_name: str, target_dir: Path) -> bool: + """ + Uninstall a skill from target directory. + + Args: + skill_name (`str`): Name of skill to uninstall. + target_dir (`Path`): Directory skill is installed in. + + Returns: + `bool`: True if uninstalled successfully. + + Raises: + - `FileNotFoundError`: If skill not installed. + - `PermissionError`: If no permission to remove. + - `OSError`: If removing the skill fails for another filesystem reason. + """ + target_skill = target_dir / skill_name + + if not target_skill.exists(): + raise FileNotFoundError(f"Skill '{skill_name}' not installed at {target_dir}") + + # Remove symlink or directory + try: + shutil.rmtree(target_skill) + except PermissionError as e: + raise PermissionError(f"Cannot remove skill: {e}") from e + except OSError as e: + raise OSError(f"Failed to remove skill: {e}") from e + + return True + + +def uninstall_skill(skill_name: str, target: str | Path, scope: str = "project") -> bool: + """ + Uninstall a skill. + + Args: + skill_name (`str`): Name of skill to uninstall. + target (`str | Path`): Agent name (e.g., 'agents', 'claude') or directory path. + scope (`str`, defaults to `"project"`): + Scope for agent names: 'global' (user-level) or 'project' (current directory). + + Returns: + `bool`: True if uninstalled successfully. + + Raises: + - `FileNotFoundError`: If skill not installed. + - `PermissionError`: If no permission to remove. + - `OSError`: If removing the skill fails for another filesystem reason. + - `ValueError`: If `scope` is invalid for a predefined agent target. + + Example: + ```python + >>> from trl.skills import uninstall_skill + + >>> # Uninstall from Claude's global directory + >>> uninstall_skill("trl-training", target="claude", scope="global") + + >>> # Uninstall from custom directory + >>> uninstall_skill("trl-training", target="/path/to/skills") + ``` + """ + target_dir = resolve_target_path(target, scope) + return _uninstall_skill_from_dir(skill_name, target_dir) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/skills/trl-training/SKILL.md b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/skills/trl-training/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..1941385812d82abbbe1f466aa1204e0f8d775ea9 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/skills/trl-training/SKILL.md @@ -0,0 +1,333 @@ +--- +name: trl-training +description: Train and fine-tune transformer language models using TRL (Transformers Reinforcement Learning). Supports SFT, DPO, GRPO, KTO, RLOO and Reward Model training via CLI commands. +license: Apache-2.0 +metadata: + version: "1.0.0" + author: huggingface + commands: + - trl sft + - trl dpo + - trl grpo + - trl kto + - trl rloo + - trl reward + categories: + - machine-learning + - llm-training + - reinforcement-learning + tags: + - rlhf + - supervised-fine-tuning + - dpo + - grpo + - huggingface + - transformers + documentation: https://huggingface.co/docs/trl/en/clis +--- + +# TRL Training Skill + +You are an expert at using the TRL (Transformers Reinforcement Learning) library to train and fine-tune large language models. + +## Overview + +TRL provides CLI commands for post-training foundation models using state-of-the-art techniques: + +- **SFT** (Supervised Fine-Tuning): Fine-tune models on instruction-following or conversational datasets +- **DPO** (Direct Preference Optimization): Align models using preference data +- **GRPO** (Group Relative Policy Optimization): Train models by ranking multiple sampled outputs relative to each other and optimizing based on their comparative rewards. +- **RLOO** (Reinforce Leave One Out): Online RL training with generation-based rewards +- **Reward Model Training**: Train reward models for RLHF + +TRL is built on top of Hugging Face Transformers and Accelerate, providing seamless integration with the Hugging Face ecosystem. + +## Core Commands + +### trl sft - Supervised Fine-Tuning + +Fine-tune language models on instruction-following or conversational datasets. + +**Full training:** + +```bash +trl sft \ + --model_name_or_path Qwen/Qwen2-0.5B \ + --dataset_name trl-lib/Capybara \ + --learning_rate 2.0e-5 \ + --num_train_epochs 1 \ + --packing \ + --per_device_train_batch_size 2 \ + --gradient_accumulation_steps 8 \ + --eos_token '<|im_end|>' \ + --eval_strategy steps \ + --eval_steps 100 \ + --output_dir Qwen2-0.5B-SFT \ + --push_to_hub +``` + +**Train with LoRA adapters:** + +```bash +trl sft \ + --model_name_or_path Qwen/Qwen2-0.5B \ + --dataset_name trl-lib/Capybara \ + --learning_rate 2.0e-4 \ + --num_train_epochs 1 \ + --packing \ + --per_device_train_batch_size 2 \ + --gradient_accumulation_steps 8 \ + --eos_token '<|im_end|>' \ + --eval_strategy steps \ + --eval_steps 100 \ + --use_peft \ + --lora_r 32 \ + --lora_alpha 16 \ + --output_dir Qwen2-0.5B-SFT \ + --push_to_hub +``` + +### trl dpo - Direct Preference Optimization + +Align models using preference data (chosen/rejected pairs). + +**Full training:** + +```bash +trl dpo \ + --dataset_name trl-lib/ultrafeedback_binarized \ + --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ + --learning_rate 5.0e-7 \ + --num_train_epochs 1 \ + --per_device_train_batch_size 2 \ + --max_steps 1000 \ + --gradient_accumulation_steps 8 \ + --eval_strategy steps \ + --eval_steps 50 \ + --output_dir Qwen2-0.5B-DPO \ + --no_remove_unused_columns +``` + +**Train with LoRA adapters:** + +```bash +trl dpo \ + --dataset_name trl-lib/ultrafeedback_binarized \ + --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ + --learning_rate 5.0e-6 \ + --num_train_epochs 1 \ + --per_device_train_batch_size 2 \ + --max_steps 1000 \ + --gradient_accumulation_steps 8 \ + --eval_strategy steps \ + --eval_steps 50 \ + --output_dir Qwen2-0.5B-DPO \ + --no_remove_unused_columns \ + --use_peft \ + --lora_r 32 \ + --lora_alpha 16 +``` + +### trl grpo - Group Relative Policy Optimization + +Train models using reward functions or LLM-as-a-judge for evaluating generations and providing rewards. + +**Basic usage:** + +```bash +trl grpo \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name trl-lib/gsm8k \ + --reward_funcs accuracy_reward \ + --output_dir Qwen2-0.5B-GRPO \ + --push_to_hub +``` + +### trl rloo - Reinforce Leave One Out + +Online RL training where the model generates text and receives rewards based on custom criteria. + +**Basic usage:** + +```bash +trl rloo \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name trl-lib/tldr \ + --reward_model_name_or_path sentiment-analysis:nlptown/bert-base-multilingual-uncased-sentiment \ + --output_dir Qwen2-0.5B-RLOO \ + --push_to_hub +``` + +### trl reward - Reward Model Training + +Train a reward model to score text quality for RLHF. + +**Full training:** + +```bash +trl reward \ + --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ + --dataset_name trl-lib/ultrafeedback_binarized \ + --output_dir Qwen2-0.5B-Reward \ + --per_device_train_batch_size 8 \ + --num_train_epochs 1 \ + --learning_rate 1.0e-5 \ + --eval_strategy steps \ + --eval_steps 50 \ + --max_length 2048 +``` + +**Train with LoRA adapters:** + +```bash +trl reward \ + --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ + --dataset_name trl-lib/ultrafeedback_binarized \ + --output_dir Qwen2-0.5B-Reward-LoRA \ + --per_device_train_batch_size 8 \ + --num_train_epochs 1 \ + --learning_rate 1.0e-4 \ + --eval_strategy steps \ + --eval_steps 50 \ + --max_length 2048 \ + --use_peft \ + --lora_task_type SEQ_CLS \ + --lora_r 32 \ + --lora_alpha 16 +``` + +## Configuration Files + +TRL supports YAML configuration files for reproducible training. All CLI arguments can be specified in a config file. + +**Example config (sft_config.yaml):** + +```yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +dataset_name: trl-lib/Capybara +learning_rate: 2.0e-5 +num_train_epochs: 1 +per_device_train_batch_size: 8 +gradient_accumulation_steps: 2 +output_dir: ./sft_output +use_peft: true +lora_r: 16 +lora_alpha: 16 +report_to: trackio +``` + +**Launch with config:** + +```bash +trl sft --config sft_config.yaml +``` + +**Override config values:** + +```bash +trl sft --config sft_config.yaml --learning_rate 1.0e-5 +``` + +## Distributed Training + +TRL integrates with Accelerate for multi-GPU and multi-node training. + +**Multi-GPU training:** + +```bash +trl sft \ + --config sft_config.yaml \ + --num_processes 4 +``` + +**Use predefined Accelerate configs:** + +TRL provides predefined configs: `single_gpu`, `multi_gpu`, `fsdp1`, `fsdp2`, `zero1`, `zero2`, `zero3` + +```bash +trl sft \ + --config sft_config.yaml \ + --accelerate_config zero2 +``` + +**Custom Accelerate config:** + +```bash +# Generate custom config +accelerate config + +# Use custom config +trl sft --config sft_config.yaml --config_file ~/.cache/huggingface/accelerate/default_config.yaml +``` + +**Fully Sharded Data Parallel (FSDP):** + +```bash +trl sft --config sft_config.yaml --accelerate_config fsdp2 +``` + +**DeepSpeed ZeRO:** + +```bash +trl sft --config sft_config.yaml --accelerate_config zero3 +``` + +## Troubleshooting + +### CUDA Out of Memory + +- Reduce `--per_device_train_batch_size` and increase `--gradient_accumulation_steps` +- Enable `--use_peft` for LoRA training +- Use `--gradient_checkpointing` to save memory +- Try smaller model or longer sequence truncation + +### Dataset Loading Issues + +- Verify dataset exists: check Hugging Face Hub or local path +- Check dataset format matches expected columns +- Use `--dataset_config` for multi-config datasets +- Inspect dataset: `from datasets import load_dataset; ds = load_dataset(name)` + +### Model Loading Issues + +- Verify model exists on Hugging Face Hub +- Check if gated model requires authentication: `hf auth login` +- For local models, provide absolute path +- Ensure sufficient disk space and memory + +### Slow Training + +- Enable dataset `--packing` for short sequences +- Use larger `--per_device_train_batch_size` if memory allows +- Enable `--tf32` for faster computation on Ampere GPUs +- Use `--bf16` on supported hardware +- Consider multi-GPU training with `--num_processes` + +### Generation Issues (GRPO/RLOO) + +- Check prompt format in dataset +- Adjust `--temperature` and `--top_p` for generation +- Verify the reward function (for GRPO/RLOO) + +## Additional Resources + +- **Documentation**: https://huggingface.co/docs/trl +- **GitHub**: https://github.com/huggingface/trl +- **Examples**: https://github.com/huggingface/trl/tree/main/examples + +## Best Practices + +1. **Start with SFT**: Always fine-tune base models with SFT before preference alignment +2. **Use LoRA for efficiency**: Enable `--use_peft` for faster training and lower memory +3. **Monitor training**: Use `--report_to trackio` (or `--report_to wandb` or `--report_to tensorboard`) for tracking +4. **Save checkpoints**: TRL automatically saves checkpoints in `--output_dir` +5. **Test on small datasets first**: Verify pipeline works before full training +6. **Use configuration files**: Create YAML configs for reproducibility +7. **Leverage Accelerate**: Use multi-GPU training for faster iteration + +When helping users with TRL: +- Always check which training method is appropriate for their use case +- Verify dataset format matches the expected schema +- Recommend starting with smaller models for testing +- Suggest LoRA for resource-constrained environments +- Point to specific documentation sections for advanced features diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/templates/completions_dataset_card.md b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/templates/completions_dataset_card.md new file mode 100644 index 0000000000000000000000000000000000000000..6246844db5738c7cc6807c9b221544f6939692c6 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/templates/completions_dataset_card.md @@ -0,0 +1,40 @@ +--- +{{ card_data }} +--- + +# TRL Completion logs + +This dataset contains the completions generated during training using `trl`. + +{% if hub_model_id %} +Find the trained model at https://huggingface.co/{{ hub_model_id }}. + +{% endif %} +The completions are stored in parquet files, and each file contains the completions for a single step of training (depending on the `logging_steps` argument). + +Each file contains the following columns: + +- `step`: the step of training +- `prompt`: the prompt used to generate the completion +- `completion`: the completion generated by the model +- ``: the reward(s) assigned to the completion by the reward function(s) used during training +- `advantage`: the computed advantage for the completion + +Having this data stored as a simple parquet file makes it easy to load and analyze using the Datasets Viewer, Polars, Pandas, etc. + +You can load the dataset using the `datasets` library: + +```python +import datasets + +dataset = datasets.load_dataset("{{ repo_id }}") +``` + +You can also load the dataset using Polars: + +```python +import polars as pl + +# Login using e.g. `hf auth login` to access this dataset if it's private +df = pl.read_parquet(f"hf://datasets/{{ repo_id }}/*.parquet") +``` diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/templates/lm_model_card.md b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/templates/lm_model_card.md new file mode 100644 index 0000000000000000000000000000000000000000..ae7e33bfb5d5e5864257fd0abf04bd78d1629c5f --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/templates/lm_model_card.md @@ -0,0 +1,55 @@ +--- +{{ card_data }} +--- + +# Model Card for {{ model_name }} + +This model is a fine-tuned version of [{{ base_model }}](https://huggingface.co/{{ base_model }}){% if dataset_name %} on the [{{ dataset_name }}](https://huggingface.co/datasets/{{ dataset_name }}) dataset{% endif %}. +It has been trained using [TRL](https://github.com/huggingface/trl). + +## Quick start + +```python +from transformers import pipeline + +question = "If you had a time machine, but could only go to the past or the future once and never return, which would you choose and why?" +generator = pipeline("text-generation", model="{{ hub_model_id }}", device="cuda") +output = generator([{"role": "user", "content": question}], max_new_tokens=128, return_full_text=False)[0] +print(output["generated_text"]) +``` + +## Training procedure + +{% if wandb_url %}[Visualize in Weights & Biases]({{ wandb_url }}){% endif %} +{% if trackio_url %}[Visualize in Trackio]({{ trackio_url }}){% endif %} +{% if comet_url %}[Visualize in Comet]({{ comet_url }}){% endif %} + +This model was trained with {{ trainer_name }}{% if paper_id %}, a method introduced in [{{ paper_title }}](https://huggingface.co/papers/{{ paper_id }}){% endif %}. + +### Framework versions + +- TRL: {{ trl_version }} +- Transformers: {{ transformers_version }} +- Pytorch: {{ pytorch_version }} +- Datasets: {{ datasets_version }} +- Tokenizers: {{ tokenizers_version }} + +## Citations + +{% if trainer_citation %}Cite {{ trainer_name }} as: + +```bibtex +{{ trainer_citation }} +```{% endif %} + +Cite TRL as: + +```bibtex +{% raw %}@software{vonwerra2020trl, + title = {{TRL: Transformers Reinforcement Learning}}, + author = {von Werra, Leandro and Belkada, Younes and Tunstall, Lewis and Beeching, Edward and Thrush, Tristan and Lambert, Nathan and Huang, Shengyi and Rasul, Kashif and Gallouédec, Quentin}, + license = {Apache-2.0}, + url = {https://github.com/huggingface/trl}, + year = {2020} +}{% endraw %} +``` diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/templates/rm_model_card.md b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/templates/rm_model_card.md new file mode 100644 index 0000000000000000000000000000000000000000..0e47e9724a6c38f262b63782507d5871bb4272c2 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/templates/rm_model_card.md @@ -0,0 +1,55 @@ +--- +{{ card_data }} +--- + +# Model Card for {{ model_name }} + +This model is a fine-tuned version of [{{ base_model }}](https://huggingface.co/{{ base_model }}){% if dataset_name %} on the [{{ dataset_name }}](https://huggingface.co/datasets/{{ dataset_name }}) dataset{% endif %}. +It has been trained using [TRL](https://github.com/huggingface/trl). + +## Quick start + +```python +from transformers import pipeline + +text = "The capital of France is Paris." +rewarder = pipeline(model="{{ hub_model_id }}", device="cuda") +output = rewarder(text)[0] +print(output["score"]) +``` + +## Training procedure + +{% if wandb_url %}[Visualize in Weights & Biases]({{ wandb_url }}){% endif %} +{% if trackio_url %}[Visualize in Trackio]({{ trackio_url }}){% endif %} +{% if comet_url %}[Visualize in Comet]({{ comet_url }}){% endif %} + +This model was trained with {{ trainer_name }}{% if paper_id %}, a method introduced in [{{ paper_title }}](https://huggingface.co/papers/{{ paper_id }}){% endif %}. + +### Framework versions + +- TRL: {{ trl_version }} +- Transformers: {{ transformers_version }} +- Pytorch: {{ pytorch_version }} +- Datasets: {{ datasets_version }} +- Tokenizers: {{ tokenizers_version }} + +## Citations + +{% if trainer_citation %}Cite {{ trainer_name }} as: + +```bibtex +{{ trainer_citation }} +```{% endif %} + +Cite TRL as: + +```bibtex +{% raw %}@software{vonwerra2020trl, + title = {{TRL: Transformers Reinforcement Learning}}, + author = {von Werra, Leandro and Belkada, Younes and Tunstall, Lewis and Beeching, Edward and Thrush, Tristan and Lambert, Nathan and Huang, Shengyi and Rasul, Kashif and Gallouédec, Quentin}, + license = {Apache-2.0}, + url = {https://github.com/huggingface/trl}, + year = {2020} +}{% endraw %} +``` diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/__init__.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1d79d365056136a5940af7d23fb964fb8db0e62c --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/__init__.py @@ -0,0 +1,83 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import TYPE_CHECKING + +from .._lazy_module import _LazyModule + + +_import_structure = { + "callbacks": [ + "BEMACallback", + "LogCompletionsCallback", + "RichProgressCallback", + "SyncRefModelCallback", + "WeaveCallback", + ], + "dpo_config": ["DPOConfig"], + "dpo_trainer": ["DPOTrainer"], + "grpo_config": ["GRPOConfig"], + "grpo_trainer": ["GRPOTrainer"], + "kto_config": ["KTOConfig"], + "kto_trainer": ["KTOTrainer"], + "model_config": ["ModelConfig"], + "reward_config": ["RewardConfig"], + "reward_trainer": ["RewardTrainer"], + "rloo_config": ["RLOOConfig"], + "rloo_trainer": ["RLOOTrainer"], + "sft_config": ["SFTConfig"], + "sft_trainer": ["SFTTrainer"], + "utils": [ + "disable_dropout_in_model", + "ensure_master_addr_port", + "get_kbit_device_map", + "get_peft_config", + "get_quantization_config", + "patch_chunked_lm_head", + ], +} + +if TYPE_CHECKING: + from .callbacks import ( + BEMACallback, + LogCompletionsCallback, + RichProgressCallback, + SyncRefModelCallback, + WeaveCallback, + ) + from .dpo_config import DPOConfig + from .dpo_trainer import DPOTrainer + from .grpo_config import GRPOConfig + from .grpo_trainer import GRPOTrainer + from .kto_config import KTOConfig + from .kto_trainer import KTOTrainer + from .model_config import ModelConfig + from .reward_config import RewardConfig + from .reward_trainer import RewardTrainer + from .rloo_config import RLOOConfig + from .rloo_trainer import RLOOTrainer + from .sft_config import SFTConfig + from .sft_trainer import SFTTrainer + from .utils import ( + disable_dropout_in_model, + ensure_master_addr_port, + get_kbit_device_map, + get_peft_config, + get_quantization_config, + patch_chunked_lm_head, + ) +else: + import sys + + sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/base_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/base_config.py new file mode 100644 index 0000000000000000000000000000000000000000..fd20188c74b342974ace79b863b0566c23673ec3 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/base_config.py @@ -0,0 +1,107 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field + +from transformers import TrainingArguments + + +@dataclass +class _BaseConfig(TrainingArguments): + """ + Base configuration class for all TRL trainer configurations. + + Subclasses [`~transformers.TrainingArguments`] and overrides fields that are common across TRL trainers or that + contain unescaped "%" characters which would cause argparse to raise a `TypeError` when rendering `--help` output. + + Parameters: + logging_steps (`int` or `float`, *optional*, defaults to `10`): + Number of update steps between two logs if `logging_strategy="steps"`. Should be an integer or a float in + range `[0,1)`. If smaller than 1, will be interpreted as ratio of total training steps. + gradient_checkpointing (`bool`, *optional*, defaults to `True`): + Whether to enable gradient checkpointing to trade compute for memory. Reduces memory usage by clearing + activations during forward pass and recomputing them during backward pass. Enables training larger models + or batch sizes at the cost of ~20% slower training. + bf16 (`bool`, *optional*): + Whether to use bfloat16 (BF16) mixed precision instead of 32-bit. Generally preferred over FP16 due to + better numerical stability and no loss scaling required. Requires Ampere or higher NVIDIA architecture or + Intel XPU or using CPU (use_cpu) or Ascend NPU. If not set, it defaults to `True` if `fp16` is not set. + lr_scheduler_kwargs (`dict` or `str`, *optional*): + Additional parameters for the lr_scheduler, such as `{'num_cycles': 1}` for cosine with hard restarts. See + the documentation of each scheduler for possible values. + use_liger_kernel (`bool`, *optional*, defaults to `False`): + Enable [Liger Kernel](https://github.com/linkedin/Liger-Kernel) optimizations. Increases multi-GPU + throughput by ~20% and reduces memory usage by ~60%. Works with Flash Attention, FSDP, and DeepSpeed. + Currently, supports Llama, Mistral, Mixtral, and Gemma models. + torch_empty_cache_steps (`int`, *optional*): + Number of steps to wait before calling `torch..empty_cache()`. If left unset or set to None, cache + will not be emptied. This can help avoid CUDA out-of-memory errors by lowering peak VRAM usage at a cost of + about [10% slower performance](https://github.com/huggingface/transformers/issues/31372). + """ + + # Override fields from TrainingArguments to set defaults preferred by all TRL trainers. + logging_steps: float = field( + default=10, + metadata={ + "help": "Log every X updates steps. Should be an integer or a float in range `[0,1)`. If smaller than 1, " + "will be interpreted as ratio of total training steps." + }, + ) + gradient_checkpointing: bool = field( + default=True, + metadata={ + "help": "Enable gradient checkpointing to trade compute for memory. Reduces memory at the cost of ~20%% slower training." + }, + ) + bf16: bool | None = field( + default=None, + metadata={ + "help": "Whether to use bf16 (mixed) precision instead of 32-bit. Requires Ampere or higher NVIDIA " + "architecture or Intel XPU or using CPU (use_cpu) or Ascend NPU. If not set, it defaults to `True` if " + "`fp16` is not set." + }, + ) + # Transformers 4.57.0 introduced a bug that caused the dtype of `lr_scheduler_kwargs` to be unparsable. This issue + # was fixed in https://github.com/huggingface/transformers/pull/41322 and released in 4.57.5. We add a temporary + # workaround here, which can be removed once we drop support for versions older than 4.57.5. + lr_scheduler_kwargs: dict | str | None = field( + default=None, + metadata={ + "help": "Additional parameters for the lr_scheduler, such as {'num_cycles': 1} for cosine with hard " + "restarts. See the documentation of each scheduler for possible values." + }, + ) + + # Override fields from TrainingArguments whose help strings contain unescaped "%" characters. + # argparse interprets "%" as a format specifier, raising TypeError when rendering --help output. + # Fixed upstream in transformers v5.3.0, but overridden here to support older versions. + # - Introduced in v5.2.0; fixed in v5.3.0 + use_liger_kernel: bool = field( + default=False, + metadata={ + "help": "Enable Liger Kernel optimizations. Increases throughput by ~20%% and reduces memory by ~60%%." + }, + ) + # - Introduced in v4.54.1; fixed in v5.3.0 + torch_empty_cache_steps: int | None = field( + default=None, + metadata={ + "help": "Number of steps to wait before calling `torch..empty_cache()`. Helps avoid CUDA OOM at a cost of ~10%% slower performance. If None, cache will not be emptied." + }, + ) + + def __post_init__(self): + self.bf16 = not (self.fp16) if self.bf16 is None else self.bf16 + + super().__post_init__() diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/base_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/base_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..705cdf11f236ad3bf50842c08eda4afdee69c5b4 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/base_trainer.py @@ -0,0 +1,191 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os + +import torch +from accelerate.utils import is_peft_model +from huggingface_hub.utils import send_telemetry +from transformers import CONFIG_MAPPING, Trainer, is_wandb_available + +from .. import __version__ +from .utils import generate_model_card, get_comet_experiment_url, get_config_model_id, get_trackio_space_url + + +if is_wandb_available(): + import wandb + + +# Trainer class names that may appear in telemetry topics. Any class outside this set — internal helpers, +# in-flight subclasses not yet shipped, user-defined subclasses — is reported as "other" so unreleased or +# private names never leak. Adding a new trainer requires an explicit entry here. +_TELEMETRY_TRAINERS = { + # Stable + "DPOTrainer", + "GRPOTrainer", + "KTOTrainer", + "RewardTrainer", + "RLOOTrainer", + "SFTTrainer", + # Experimental + "A2POTrainer", + "AsyncGRPOTrainer", + "BCOTrainer", + "CPOTrainer", + "DistillationTrainer", + "DPPOTrainer", + "GFPOTrainer", + "GKDTrainer", + "GOLDTrainer", + "GRPOWithReplayBufferTrainer", + "MiniLLMTrainer", + "NashMDTrainer", + "OnlineDPOTrainer", + "ORPOTrainer", + "PAPOTrainer", + "PPOTrainer", + "PRMTrainer", + "SDFTTrainer", + "SDPOTrainer", + "SSDTrainer", + "TPOTrainer", + "XPOTrainer", +} + + +class _BaseTrainer(Trainer): + _tag_names = [] + _name = "Base" + _paper = {} + _template_file = None + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._send_telemetry() + + def _send_telemetry(self): + # Only send from rank 0 to avoid multiplying pings by world size, and skip CI runs so automated tests don't + # bias the data. Honors `HF_HUB_DISABLE_TELEMETRY=1` and `HF_HUB_OFFLINE=1` (handled by `send_telemetry`). + if not self.accelerator.is_main_process or os.environ.get("CI"): + return + if self.is_deepspeed_enabled: + distributed = "deepspeed" + elif self.is_fsdp_enabled: + distributed = "fsdp" + elif self.accelerator.num_processes > 1: + distributed = "ddp" + else: + distributed = "none" + device = self.accelerator.device.type + if device == "cuda": + gpu = torch.cuda.get_device_name(0) + elif device == "xpu": + gpu = torch.xpu.get_device_name(0) + elif device == "npu": + gpu = torch.npu.get_device_name(0) + elif device == "mlu": + gpu = torch.mlu.get_device_name(0) + else: + gpu = "other" + # Bucketed to avoid fingerprinting individual deployments by their exact cluster size. + n = self.accelerator.num_processes + world_size = "1" if n == 1 else "2-8" if n <= 8 else "9-64" if n <= 64 else "65+" + # Trainer class and model arch are reported only if they come from a known upstream allowlist (TRL trainers, + # transformers `CONFIG_MAPPING`); anything else is reported as "other" so we never leak the names of internal, + # custom trainer subclasses or private model architectures. + cls = type(self) + trainer = ( + cls.__name__ if cls.__name__ in _TELEMETRY_TRAINERS and cls.__module__.startswith("trl.") else "other" + ) + model_type = self.model.config.model_type + model_arch = model_type if model_type in CONFIG_MAPPING else "other" + send_telemetry( + topic=f"trl/{trainer}", + library_name="trl", + library_version=__version__, + user_agent={ + "model_arch": model_arch, + "peft": str(is_peft_model(self.model)).lower(), + "distributed": distributed, + "world_size": world_size, + "device": device, + "gpu": gpu, + }, + ) + + def create_model_card( + self, + model_name: str | None = None, + dataset_name: str | None = None, + tags: str | list[str] | None = None, + ): + """ + Creates a draft of a model card using the information available to the `Trainer`. + + Args: + model_name (`str`, *optional*): + Name of the model. + dataset_name (`str`, *optional*): + Name of the dataset used for training. + tags (`str`, `list[str]`, *optional*): + Tags to be associated with the model card. + """ + if not self.is_world_process_zero(): + return + + model_name_or_path = get_config_model_id(self.model.config) + if model_name_or_path and not os.path.isdir(model_name_or_path): + base_model = model_name_or_path + else: + base_model = None + + # Normalize tags + if tags is None: + tags = set() + elif isinstance(tags, str): + tags = {tags} + else: + tags = set(tags) + if hasattr(self.model.config, "unsloth_version"): + tags.add("unsloth") + if "JOB_ID" in os.environ: + tags.add("hf_jobs") + tags.update(self._tag_names) + + trackio_url = get_trackio_space_url() + # Pop existing Trackio tag and re-add the one with the proper url parameters + if trackio_url is not None: + for tag in list(tags): + if tag.startswith("trackio:"): + tags.remove(tag) + tags.add(f"trackio:{trackio_url}") + + tags = list(tags) + + model_card = generate_model_card( + base_model=base_model, + model_name=model_name, + hub_model_id=self.hub_model_id, + dataset_name=dataset_name, + tags=tags, + wandb_url=wandb.run.url if is_wandb_available() and wandb.run is not None else None, + trackio_url=trackio_url, + comet_url=get_comet_experiment_url(), + trainer_name=self._name, + trainer_citation=self._paper.get("citation"), + template_file=self._template_file, + paper_title=self._paper.get("title"), + paper_id=self._paper.get("id"), + ) + model_card.save(os.path.join(self.args.output_dir, "README.md")) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/callbacks.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..6777c390e25263d2c12c0acaf90ee0038af89168 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/callbacks.py @@ -0,0 +1,758 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging + +import pandas as pd +import torch +from accelerate import Accelerator +from accelerate.state import AcceleratorState +from accelerate.utils import gather_object, is_wandb_available +from transformers import ( + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, + Trainer, + TrainerCallback, + TrainerControl, + TrainerState, + TrainingArguments, +) +from transformers.trainer_utils import has_length +from transformers.utils import is_rich_available + +from ..data_utils import maybe_apply_chat_template +from ..import_utils import is_weave_available +from ..models.utils import unwrap_model_for_generation +from .utils import log_table_to_comet_experiment + + +if is_rich_available(): + from rich.columns import Columns + from rich.console import Console, Group + from rich.live import Live + from rich.panel import Panel + from rich.progress import Progress + from rich.table import Table + +if is_wandb_available(): + import wandb + +if is_weave_available(): + import weave + from weave import EvaluationLogger + from weave.trace.context import weave_client_context + + +# Logger for module-level logging +logger = logging.getLogger(__name__) + + +def _generate_completions( + prompts: list[str], + model: PreTrainedModel, + tokenizer: PreTrainedTokenizerBase, + accelerator: Accelerator, + generation_config: GenerationConfig | None, + batch_size: int = 1, +) -> list[str]: + """ + Generates completions for a list of pre-formatted prompts from the given model. + + Args: + prompts (list[str]): A list of input prompts for which completions are to be generated. + model (PreTrainedModel): The pre-trained model to be used for generation. + tokenizer (PreTrainedTokenizerBase): The tokenizer to be used for encoding and decoding. + accelerator (Accelerator): The accelerator to be used for model execution. + generation_config (GenerationConfig): Configuration for text generation. + batch_size (int, *optional*): The number of prompts to process in each batch. Default is 1. + + Returns: + list[str]: A list of generated text completions corresponding to the input prompts. + """ + completions = [] + # TODO: Override model.generation_config with generation_kwargs + with unwrap_model_for_generation(model, accelerator) as unwrapped_model: + for idx in range(0, len(prompts), batch_size): + batch = prompts[idx : idx + batch_size] + tokenized_batch = tokenizer(batch, return_tensors="pt", padding=True, truncation=True).to(model.device) + generations = unwrapped_model.generate( + **tokenized_batch, + generation_config=generation_config, + ) + for prompt, generation in zip(tokenized_batch.input_ids, generations, strict=True): + # Remove prompt from generation + generation = generation[len(prompt) :] + completion = tokenizer.decode(generation, skip_special_tokens=True) + completions.append(completion) + return completions + + +class SyncRefModelCallback(TrainerCallback): + """ + Callback to synchronize the model with a reference model. + """ + + def __init__( + self, + ref_model: PreTrainedModel | torch.nn.Module, + accelerator: Accelerator | None, + ): + self.accelerator = accelerator + self.ref_model = ref_model + + @staticmethod + def _sync_target_model(model, target_model, alpha): + for target_param, copy_param in zip(target_model.parameters(), model.parameters(), strict=True): + target_param.data.mul_(1.0 - alpha).add_(copy_param.data, alpha=alpha) + + @staticmethod + def sync_target_model(model, target_model, alpha): + deepspeed_plugin = AcceleratorState().deepspeed_plugin + if deepspeed_plugin is not None and deepspeed_plugin.zero_stage == 3: + import deepspeed + + with deepspeed.zero.GatheredParameters( + list(model.parameters()) + list(target_model.parameters()), modifier_rank=0 + ): + if deepspeed.comm.get_rank() == 0: + SyncRefModelCallback._sync_target_model(model, target_model, alpha) + else: + SyncRefModelCallback._sync_target_model(model, target_model, alpha) + + def on_step_end(self, args, state, control, **kwargs): + model: PreTrainedModel = kwargs["model"] + + if self.ref_model is not None and state.global_step % args.ref_model_sync_steps == 0: + if self.accelerator: + model = self.accelerator.unwrap_model(model) + self.sync_target_model(model, self.ref_model, args.ref_model_mixup_alpha) + + +class RichProgressCallback(TrainerCallback): + """ + A [`TrainerCallback`] that displays the progress of training or evaluation using Rich. + """ + + def __init__(self): + if not is_rich_available(): + raise ImportError("RichProgressCallback requires the `rich` extra. To install, run `pip install rich`.") + + self.training_bar = None + self.evaluation_bar = None + self.training_task = None + self.evaluation_task = None + self.rich_group = None + self.rich_console = None + self.training_status = None + self.current_step = None + + def on_train_begin(self, args, state, control, **kwargs): + if not state.is_world_process_zero: + return + + self.training_bar = Progress() + self.evaluation_bar = Progress() + self.rich_console = Console() + self.training_status = self.rich_console.status("Nothing to log yet ...") + self.rich_group = Live(Panel(Group(self.training_bar, self.evaluation_bar, self.training_status))) + self.rich_group.start() + self.training_task = self.training_bar.add_task("[blue]Training ", total=state.max_steps) + self.current_step = 0 + + def on_step_end(self, args, state, control, **kwargs): + if not state.is_world_process_zero: + return + + self.training_bar.update(self.training_task, advance=state.global_step - self.current_step, update=True) + self.current_step = state.global_step + + def on_prediction_step(self, args, state, control, eval_dataloader=None, **kwargs): + if not state.is_world_process_zero: + return + + if has_length(eval_dataloader): + if self.evaluation_task is None: + self.evaluation_task = self.evaluation_bar.add_task("[blue]Evaluation", total=len(eval_dataloader)) + self.evaluation_bar.update(self.evaluation_task, advance=1, update=True) + + def on_evaluate(self, args, state, control, **kwargs): + if not state.is_world_process_zero: + return + + if self.evaluation_task is not None: + self.evaluation_bar.remove_task(self.evaluation_task) + self.evaluation_task = None + + def on_predict(self, args, state, control, **kwargs): + if not state.is_world_process_zero: + return + + if self.evaluation_task is not None: + self.evaluation_bar.remove_task(self.evaluation_task) + self.evaluation_task = None + + def on_log(self, args, state, control, logs=None, **kwargs): + if not (state.is_world_process_zero and self.training_bar): + return + + # Group keys by top-level prefix + grouped_logs = {} + for key, value in logs.items(): + parts = key.split("/") + group = parts[0] if len(parts) > 1 else None + subkey = "/".join(parts[1:]) if len(parts) > 1 else key + grouped_logs.setdefault(group, {})[subkey] = value + + # Create a table per group + tables = [] + for group_name, metrics in grouped_logs.items(): + table = Table( + title=f"[bold blue]{group_name}[/]" if group_name else None, header_style="bold magenta", box=None + ) + table.add_column("Metric", justify="left", no_wrap=True) + table.add_column("Value", justify="right") + + for metric, val in metrics.items(): + formatted = f"{val:.3f}" if isinstance(val, (float, int)) else str(val) + table.add_row(metric, formatted) + + tables.append(Panel(table, border_style="cyan", padding=(0, 1))) + + # Arrange tables in columns using Columns + column_layout = Columns(tables, equal=False, expand=True) + self.training_status.update( + Panel(column_layout, title=f"[bold green]Step {state.global_step}[/bold green]", border_style="green") + ) + + def on_train_end(self, args, state, control, **kwargs): + if not state.is_world_process_zero: + return + + self.rich_group.stop() + self.training_bar = None + self.evaluation_bar = None + self.training_task = None + self.evaluation_task = None + self.rich_group = None + self.rich_console = None + self.training_status = None + self.current_step = None + + +class LogCompletionsCallback(TrainerCallback): + r""" + A [`~transformers.TrainerCallback`] that logs completions to Weights & Biases and/or Comet. + + Usage: + ```python + >>> trainer = DPOTrainer(...) + >>> completions_callback = LogCompletionsCallback(trainer=trainer) + >>> trainer.add_callback(completions_callback) + ``` + + Args: + trainer (`Trainer`): + Trainer to which the callback will be attached. The trainer's evaluation dataset must include a `"prompt"` + column containing the prompts for generating completions. + generation_config ([`~transformers.GenerationConfig`], *optional*): + The generation config to use for generating completions. + num_prompts (`int`, *optional*): + The number of prompts to generate completions for. If not provided, defaults to the number of examples in + the evaluation dataset. + freq (`int`, *optional*): + The frequency at which to log completions. If not provided, defaults to the trainer's `eval_steps`. + """ + + def __init__( + self, + trainer: Trainer, + generation_config: GenerationConfig | None = None, + num_prompts: int | None = None, + freq: int | None = None, + ): + self.trainer = trainer + self.generation_config = generation_config + self.freq = freq + self.table = [] + self._last_logged_step = -1 + + if self.trainer.eval_dataset is None: + raise ValueError("Trainer must have an evaluation dataset to use the LogCompletionsCallback.") + else: + self.eval_dataset = self.trainer.eval_dataset + + if num_prompts is not None: + self.eval_dataset = self.eval_dataset.select(range(num_prompts)) + + def on_step_end(self, args, state, control, **kwargs): + # Only log once per step (this method may be called multiple times) + if state.global_step == self._last_logged_step: + return + + # Only log every `freq` steps (if no `freq` is provided, log every `eval_steps` steps) + freq = self.freq or state.eval_steps + if state.global_step % freq != 0: + return + + tokenizer = kwargs["processing_class"] + tokenizer.padding_side = "left" + accelerator = self.trainer.accelerator + model = self.trainer.model_wrapped + with accelerator.split_between_processes(self.eval_dataset["prompt"]) as prompts: + prompts = [maybe_apply_chat_template({"prompt": prompt}, tokenizer)["prompt"] for prompt in prompts] + completions = _generate_completions( + prompts, + model=model, + tokenizer=tokenizer, + accelerator=accelerator, + generation_config=self.generation_config, + batch_size=args.per_device_eval_batch_size, + ) + completions = gather_object(completions) + prompts = gather_object(prompts) + + # Build the data to log + if self.trainer.accelerator.is_main_process: + global_step = [str(state.global_step)] * len(prompts) + data = list(zip(global_step, prompts, completions, strict=True)) + self.table.extend(data) + table = pd.DataFrame(columns=["step", "prompt", "completion"], data=self.table) + + if "wandb" in args.report_to: + wandb.log({"completions": table}) + + if "comet_ml" in args.report_to: + log_table_to_comet_experiment( + name="completions.csv", + table=table, + ) + + # Save the last logged step, so we don't log the same completions multiple times + self._last_logged_step = state.global_step + + +class WeaveCallback(TrainerCallback): + r""" + A [`~transformers.TrainerCallback`] that logs traces and evaluations to W&B Weave. The callback uses + https://weave-docs.wandb.ai/guides/evaluation/evaluation_logger/ to log traces and evaluations at each evaluation + step. + + Supports two modes based on the `scorers` parameter: + - **Tracing Mode** (when scorers=None): Logs predictions for data exploration and analysis + - **Evaluation Mode** (when scorers provided): Logs predictions with scoring and summary metrics + + Both modes use Weave's EvaluationLogger for structured, consistent data logging. + + The callback logs data during evaluation phases (`on_evaluate`) rather than training steps, making it more + efficient and semantically correct. It gracefully handles missing weave installation by logging warnings and + skipping weave-specific functionality. It also checks for existing weave clients before initializing new ones. + + Usage: + ```python + # Tracing mode (just log predictions) + trainer = DPOTrainer(...) + weave_callback = WeaveTraceCallback(trainer=trainer) # project_name optional + trainer.add_callback(weave_callback) + + # Or specify a project name + weave_callback = WeaveTraceCallback(trainer=trainer, project_name="my-llm-training") + trainer.add_callback(weave_callback) + + + # Evaluation mode (log predictions + scores + summary) + def accuracy_scorer(prompt: str, completion: str) -> float: + # Your scoring logic here (metadata available via eval_attributes) + return score + + + weave_callback = WeaveTraceCallback( + trainer=trainer, + project_name="my-llm-training", # optional and needed only if weave client is not initialized + scorers={"accuracy": accuracy_scorer}, + ) + trainer.add_callback(weave_callback) + ``` + + Args: + trainer (`Trainer`): + Trainer to which the callback will be attached. The trainer's evaluation dataset must include a `"prompt"` + column containing the prompts for generating completions. + project_name (`str`, *optional*): + Name of the Weave project where data will be logged. If not provided, will try to use existing weave client + or fall back to the active wandb run's project name. Raises an error if none of these are available. + scorers (`dict[str, Callable]`, *optional*): + Dictionary mapping scorer names to scorer functions. If `None`, operates in tracing mode (predictions + only). If provided, operates in evaluation mode (predictions + scores + summary). Scorer functions should + have signature: `scorer(prompt: str, completion: str) -> float | int` + generation_config ([`~transformers.GenerationConfig`], *optional*): + Generation config to use for generating completions. + num_prompts (`int` or `None`, *optional*): + Number of prompts to generate completions for. If not provided, defaults to the number of examples in the + evaluation dataset. + dataset_name (`str`, *optional*, defaults to `"eval_dataset"`): + Name for the dataset metadata in Weave. + model_name (`str`, *optional*): + Name for the model metadata in Weave. If not provided, attempts to extract from model config. + """ + + def __init__( + self, + trainer: Trainer, + project_name: str | None = None, + scorers: dict[str, callable] | None = None, + generation_config: GenerationConfig | None = None, + num_prompts: int | None = None, + dataset_name: str = "eval_dataset", + model_name: str | None = None, + ): + self.trainer = trainer + self.project_name = project_name + self.scorers = scorers or {} + self.generation_config = generation_config + self.dataset_name = dataset_name + self.model_name = model_name + self._last_logged_step = -1 + self._weave_initialized = False + self._eval_logger = None + + if self.trainer.eval_dataset is None: + raise ValueError("Trainer must have an evaluation dataset to use the WeaveCallback.") + else: + self.eval_dataset = self.trainer.eval_dataset + + if num_prompts is not None: + self.eval_dataset = self.eval_dataset.select(range(num_prompts)) + + def _initialize_weave(self): + """Initialize Weave and EvaluationLogger if not already initialized.""" + if not self._weave_initialized: + if not is_weave_available(): + logger.warning("Weave is not available. Please install weave to enable logging: `pip install weave`") + return + + if wc := weave_client_context.get_weave_client(): + self._weave_client = wc + else: + if self.project_name is None: + if is_wandb_available(): + if wandb.run is not None: + self.project_name = wandb.run.entity + "/" + wandb.run.project + logger.info(f"Using project name from active wandb run: {self.project_name}") + + if self.project_name is None: + raise ValueError( + "No existing Weave client found and no project_name provided. " + "Please either initialize weave with `weave.init('project-name')`, " + "provide a project_name to the `WeaveTraceCallback`, " + "or ensure an active wandb run exists." + ) + + self._weave_client = weave.init(self.project_name) + logger.info(f"Initialized Weave with project: {self.project_name}") + + if self.model_name is None: + self.model_name = getattr(self.trainer.model_wrapped.config, "_name_or_path", "unknown_model") + + self._EvaluationLogger = EvaluationLogger + + self._weave_initialized = True + + @property + def is_evaluation_mode(self) -> bool: + """True if scorers are provided (evaluation mode), False for tracing mode.""" + return bool(self.scorers) + + def on_train_begin(self, args, state, control, **kwargs): + """Initialize Weave when training begins.""" + self._initialize_weave() + + def on_evaluate(self, args, state, control, **kwargs): + if state.global_step == self._last_logged_step: + return + + self._initialize_weave() + + if not self._weave_initialized: + logger.debug("Weave not initialized, skipping logging") + return + + tokenizer = kwargs["processing_class"] + tokenizer.padding_side = "left" + accelerator = self.trainer.accelerator + model = self.trainer.model_wrapped + + with accelerator.split_between_processes(self.eval_dataset["prompt"]) as prompts: + prompts = [maybe_apply_chat_template({"prompt": prompt}, tokenizer)["prompt"] for prompt in prompts] + + completions = _generate_completions( + prompts=prompts, + model=model, + tokenizer=tokenizer, + accelerator=accelerator, + generation_config=self.generation_config, + batch_size=args.per_device_eval_batch_size, + ) + + all_prompts = gather_object(prompts) + all_completions = gather_object(completions) + + if self.trainer.accelerator.is_main_process: + eval_attributes = { + "training_step": state.global_step, + "model_name": self.model_name, + "generation_config": (self.generation_config.to_dict() if self.generation_config else None), + } + + eval_logger = self._EvaluationLogger( + model=self.model_name, + dataset=self.dataset_name, + eval_attributes=eval_attributes, + ) + + successful_predictions = 0 + total_score_values = {} # For summary statistics + + for prompt, completion in zip(all_prompts, all_completions, strict=True): + try: + pred_logger = eval_logger.log_prediction(inputs={"prompt": prompt}, output=completion) + + if self.is_evaluation_mode: + for scorer_name, scorer_func in self.scorers.items(): + try: + score = scorer_func(prompt, completion) + pred_logger.log_score(scorer=scorer_name, score=score) + + if scorer_name not in total_score_values: + total_score_values[scorer_name] = [] + total_score_values[scorer_name].append(score) + + except Exception as scorer_e: + logger.warning(f"Failed to apply scorer '{scorer_name}': {scorer_e}") + + pred_logger.finish() + successful_predictions += 1 + + except Exception as pred_e: + logger.warning(f"Failed to log prediction for prompt: {pred_e}") + # Continue with other predictions even if one fails + + if self.is_evaluation_mode and total_score_values: + try: + summary_stats = { + "total_predictions": len(all_prompts), + "successful_predictions": successful_predictions, + } + + for scorer_name, scores in total_score_values.items(): + if scores: # Only if we have valid scores + summary_stats[f"avg_{scorer_name}"] = sum(scores) / len(scores) + + eval_logger.log_summary(summary_stats) + + except Exception as summary_e: + logger.warning(f"Failed to log summary: {summary_e}") + else: + try: + eval_logger.finish() + except Exception as finish_e: + logger.warning(f"Failed to finish evaluation logger: {finish_e}") + + self._last_logged_step = state.global_step + + +class BEMACallback(TrainerCallback): + # docstyle-ignore + r""" + A [`~transformers.TrainerCallback`] that implements [BEMA](https://huggingface.co/papers/2508.00180) + (Bias-Corrected Exponential Moving Average) by [Adam Block](https://huggingface.co/abblock) and [Cyril + Zhang](https://huggingface.co/cyrilzhang). Code from https://github.com/abblock/bema under MIT license. + + BEMA computes model weights that scale like: + + $$ + \theta_t' = \alpha_t \cdot (\theta_t - \theta_0) + \text{EMA}_t + $$ + + where \\( \theta_t \\) is the current model weights, \\( \theta_0 \\) is a snapshot of the model weights at the + first `update_after` step, \\( \text{EMA}_t \\) is the exponential moving average of the model weights, and + \\( \alpha_t \\) is a scaling factor that decays with the number of steps \\( t \\) as + + $$ + \alpha_t = (\rho + \gamma \cdot t)^{-\eta}. + $$ + + The EMA is computed as: + + $$ + \text{EMA}_t = (1 - \beta_t) \cdot \text{EMA}_{t-1} + \beta_t \cdot \theta_t + $$ + + where \\( \beta_t \\) is a decay factor that decays with the number of steps \\( t \\) as + + $$ + \beta_t = (\rho + \gamma \cdot t)^{-\kappa}. + $$ + + Args: + update_freq (`int`, *optional*, defaults to `400`): + Update the BEMA weights every X steps. Denoted this as \\( \phi \\) in the paper. + ema_power (`float`, *optional*, defaults to `0.5`): + Power for the EMA decay factor. Denoted \\( \kappa \\) in the paper. To disable EMA, set this to `0.0`. + bias_power (`float`, *optional*, defaults to `0.2`): + Power for the BEMA scaling factor. Denoted \\( \eta \\) in the paper. To disable BEMA, set this to `0.0`. + lag (`int`, *optional*, defaults to `10`): + Initial offset in the weight decay schedule that controls early-stage smoothness by acting as a virtual + starting age for the updates. Denoted as \\( \rho \\) in the paper. + update_after (`int`, *optional*, defaults to `0`): + Burn-in time before starting to update the BEMA weights. Denoted \\( \tau \\) in the paper. + multiplier (`float`, *optional*, defaults to `1.0`): + Initial value for the EMA decay factor. Denoted as \\( \gamma \\) in the paper. + min_ema_multiplier (`float`, *optional*, defaults to `0.0`): + Minimum value for the EMA decay factor. + device (`str`, *optional*, defaults to `"cpu"`): + Device to use for the BEMA buffers, e.g. `"cpu"` or `"cuda"`. Note that in most cases, this device SHOULD + BE DIFFERENT from the device used for training in order to avoid OOM. + + Example: + + ```python + >>> from trl import BEMACallback + + >>> trainer = Trainer(..., callbacks=[BEMACallback()]) + ``` + """ + + def __init__( + self, + update_freq: int = 400, + ema_power: float = 0.5, + bias_power: float = 0.2, + lag: int = 10, + update_after: int = 0, + multiplier: float = 1.0, + min_ema_multiplier: float = 0.0, + device: str = "cpu", + ): + # User-provided hyperparams + self.update_freq = update_freq + self.ema_power = ema_power + self.bias_power = bias_power + self.lag = lag + self.update_after = update_after + self.multiplier = multiplier + self.min_ema_multiplier = min_ema_multiplier + self.device = device + + # Internal state + self.param_names = [] # references to training model param names + self.thetat_params = [] # references to training model params + self.theta0_params = [] # θ₀ buffers (on self.device) + self.ema_params = [] # EMA buffers (on self.device) + self.running_model = None # a copy of the model to run BEMA on + + @staticmethod + def _unwrap_model(model): + """ + Helper function to unwrap model from various wrappers including DataParallel, DistributedDataParallel, + DeepSpeed, and FSDP. + """ + # Handle DeepSpeed + if hasattr(model, "module") and hasattr(model, "engine"): + # DeepSpeed engine + return model.module + + # Handle FSDP + if hasattr(model, "_fsdp_wrapped_module"): + # FSDP wrapped model + return model._fsdp_wrapped_module + + # Handle DataParallel/DistributedDataParallel + if hasattr(model, "module"): + return model.module + + return model + + @torch.no_grad() + def on_train_begin( + self, args: TrainingArguments, state: TrainerState, control: TrainerControl, model: PreTrainedModel, **kwargs + ): + model = self._unwrap_model(model) + + # Create a new instance and load state_dict + self.running_model = type(model)(model.config).to(self.device) + self.running_model.load_state_dict(model.state_dict()) + + # Cache trainable parameters once in a fixed order + for name, param in model.named_parameters(): + if not param.requires_grad: + continue + self.param_names.append(name) + self.thetat_params.append(param) + + # Clone θ₀ and EMA on the same device as model + theta0 = param.detach().clone().to(self.device) + self.theta0_params.append(theta0) + self.ema_params.append(theta0.clone()) # initialize EMA with θ₀ + + def _ema_beta(self, step: int) -> float: + """Compute the EMA decay factor βₜ = (ρ + γ·t)⁻ᵏᵃᵖᵖᵃ.""" + beta = (self.lag + self.multiplier * step) ** (-self.ema_power) + return max(beta, self.min_ema_multiplier) + + def _bema_alpha(self, step: int) -> float: + """Compute the BEMA scaling factor αₜ = (ρ + γ·t)⁻ᵉᵗᵃ.""" + return (self.lag + self.multiplier * step) ** (-self.bias_power) + + def _update_bema_weights(self, step: int): + beta = self._ema_beta(step) + alpha = self._bema_alpha(step) + + # Compute EMA + BEMA in-place and write directly to running_model + for thetat, theta0, ema, run_param in zip( + self.thetat_params, self.theta0_params, self.ema_params, self.running_model.parameters(), strict=True + ): + thetat = thetat.detach().to(self.device) + ema.mul_(1 - beta).add_(thetat, alpha=beta) # EMA update: ema = (1 - beta) * ema + beta * θₜ + run_param.copy_(ema + alpha * (thetat - theta0)) # BEMA update: run_param = ema + alpha * (θₜ - θ₀) + + @torch.no_grad() + def on_step_end( + self, args: TrainingArguments, state: TrainerState, control: TrainerControl, model: PreTrainedModel, **kwargs + ): + step = state.global_step + + # If we haven't reached the update_after step, skip the BEMA update + if step < self.update_after: + return + + # Snapshot θ₀ and EMA at first update + if step == self.update_after: + for thetat_param, theta0_param, ema_param in zip( + self.thetat_params, self.theta0_params, self.ema_params, strict=True + ): + theta0_param.copy_(thetat_param) + ema_param.copy_(thetat_param) + + # Update BEMA weights every `update_freq` steps + elif (step - self.update_after) % self.update_freq == 0: + self._update_bema_weights(step) + logger.info(f"Updated BEMA weights at step {step}") + + @torch.no_grad() + def on_train_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): + if state.is_world_process_zero: + save_directory = f"{args.output_dir}/bema" + self.running_model.save_pretrained(save_directory) + logger.info(f"Saved BEMA model to {save_directory}") diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/dpo_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/dpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..1d22eba6b48dcb8df0b77c78f9f853e3f121cb07 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/dpo_config.py @@ -0,0 +1,354 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass, field +from typing import Any + +from .base_config import _BaseConfig + + +@dataclass +class DPOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`DPOTrainer`]. + + This class includes only the parameters that are specific to DPO training. For a full list of training arguments, + please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may + differ from those in [`~transformers.TrainingArguments`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + > Parameters that control the model + + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model` + argument of the [`DPOTrainer`] is provided as a string. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to + [`~transformers.AutoModelForCausalLM.from_pretrained`] and + [`~transformers.AutoProcessor.from_pretrained`]. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model and reference model. + + > Parameters that control the data preprocessing + + dataset_num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + max_length (`int` or `None`, *optional*, defaults to `1024`): + Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from the left or + right depending on the `truncation_mode`. If `None`, no truncation is applied. + truncation_mode (`str`, *optional*, defaults to `"keep_start"`): + Truncation mode to use when the sequence exceeds `max_length`. The only supported value is + `"keep_start"`. The `"keep_end"` value is deprecated and will be removed in v2.0.0. + padding_free (`bool`, *optional*, defaults to `False`): + Whether to perform forward passes without padding by flattening all sequences in the batch into a single + continuous sequence. This reduces memory usage by eliminating padding overhead. Currently, this is only + supported with the FlashAttention 2 or 3, which can efficiently handle the flattened batch structure. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + precompute_ref_log_probs (`bool`, *optional*, defaults to `False`): + Whether to precompute the reference model log probabilities for the entire training dataset before + training. This allows to save memory during training, as the reference model does not need to be kept in + memory. + precompute_ref_batch_size (`int`, *optional*): + Batch size to use when precomputing reference model log probabilities. This can be set higher than the + training batch size to speed up preprocessing. If `None`, defaults to `per_device_train_batch_size` for + training and `per_device_eval_batch_size` for evaluation. + + > Parameters that control the training + + loss_type (`list[str]`, *optional*, defaults to `["sigmoid"]`): + Type of loss to use. Possible values are: `'sigmoid'`, `'hinge'`, `'ipo'`, `'exo_pair'`, `'nca_pair'`, + `'robust'`, `'bco_pair'`, `'sppo_hard'`, `'aot'`, `'aot_unpaired'`, `'apo_zero'`, `'apo_down'`, + `'discopop'`, `'sft'`, `'sigmoid_norm'`. If multiple loss types are provided, they will be combined using + the weights specified in `loss_weights`. + loss_weights (`list[float]`, *optional*): + List of loss weights for multi-loss combinations. Used when combining multiple loss types. Example: `[0.8, + 0.2, 1.0]` for MPO. If not provided, defaults to equal weights (`1.0`) for all loss types. + ld_alpha (`float`, *optional*): + α parameter from the LD-DPO paper, which controls the weighting of the verbose token log-probabilities in + responses. If `None`, no weighting is applied to the verbose part, and the loss is equivalent to the + standard DPO loss. Must be in [0.0, 1.0]: `ld_alpha=1.0` applies no weighting, and `ld_alpha=0.0` masks + tokens beyond shared lengths. + f_divergence_type (`str`, *optional*, defaults to `"reverse_kl"`): + f-divergence regularizer between policy and reference (f-DPO paper). Possible values are: `reverse_kl` + (default), `forward_kl`, `js_divergence`, `alpha_divergence`. + f_alpha_divergence_coef (`float`, *optional*, defaults to `0.5`): + α coefficient for the α-divergence u^-α regularizer, used only when `f_divergence_type='alpha_divergence'`. + label_smoothing (`float`, *optional*, defaults to `0.0`): + Label smoothing parameter used in Robust DPO and EXO. In Robust DPO, it is interpreted as the probability + that a preference label is flipped and must lie in [0.0, 0.5); a typical value recommended by the Robust + DPO paper is 0.1. In EXO, it corresponds to the ε label smoothing parameter, for which the paper recommends + a typical value of 1e-3. + beta (`float`, *optional*, defaults to `0.1`): + Parameter controlling the deviation from the reference model. Higher β means less deviation from the + reference model. For the IPO loss (`loss_type='ipo'`), this value is the regularization parameter denoted + by τ in the [paper](https://huggingface.co/papers/2310.12036). + use_weighting (`bool`, *optional*, defaults to `False`): + Whether to apply WPO-style weighting (https://huggingface.co/papers/2406.11827) to preference pairs using + the policy's length-normalized sequence probabilities. + discopop_tau (`float`, *optional*, defaults to `0.05`): + τ/temperature parameter from the DiscoPOP paper, which controls the shape of the log-ratio modulated loss + when using `loss_type='discopop'`. The paper recommends the default value `discopop_tau=0.05`. + activation_offloading (`bool`, *optional*, defaults to `False`): + Whether to offload the activations to the CPU. + sync_ref_model (`bool`, *optional*, defaults to `False`): + Whether to synchronize the reference model with the active model every `ref_model_sync_steps` steps, using + the `ref_model_mixup_alpha` parameter. This synchronization originates from the + [TR-DPO](https://huggingface.co/papers/2404.09656) paper. `sync_ref_model=True` is not yet compatible with + PEFT or `precompute_ref_log_probs=True`. + ref_model_mixup_alpha (`float`, *optional*, defaults to `0.6`): + α parameter from the TR-DPO paper, which controls the mix between the current policy and the previous + reference policy during updates. The reference policy is updated according to the equation: `π_ref = α * + π_θ + (1 - α) * π_ref_prev`. To use this parameter, you must set `sync_ref_model=True`. + ref_model_sync_steps (`int`, *optional*, defaults to `512`): + τ parameter from the TR-DPO paper, which determines how frequently the current policy is synchronized with + the reference policy. To use this parameter, you must set `sync_ref_model=True`. + + > Deprecated parameters + + pad_token: + + + + Parameter `pad_token` is deprecated and will be removed in version v2.0.0. Set `tokenizer.pad_token` + directly and pass it as `processing_class` to the trainer instead. + + + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `1e-6` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=1e-6, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + # Parameters that control the model + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of " + "the `DPOTrainer` is provided as a string." + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. " + "Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoProcessor.from_pretrained`." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the model and reference model."}, + ) + + # Parameters that control the data preprocessing + dataset_num_proc: int | None = field( + default=None, + metadata={"help": "Number of processes to use for processing the dataset."}, + ) + max_length: int | None = field( + default=1024, + metadata={ + "help": "Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from " + "the left or right depending on the `truncation_mode`. If `None`, no truncation is applied." + }, + ) + truncation_mode: str = field( + default="keep_start", + metadata={ + "help": "Truncation mode to use when the sequence exceeds `max_length`. The only supported value is " + "`'keep_start'`. The `'keep_end'` value is deprecated and will be removed in v2.0.0.", + "choices": ["keep_end", "keep_start"], + }, + ) + padding_free: bool = field( + default=False, + metadata={ + "help": "Whether to perform forward passes without padding by flattening all sequences in the batch into " + "a single continuous sequence. This reduces memory usage by eliminating padding overhead. Currently, this " + "is only supported with the FlashAttention 2 or 3, which can efficiently handle the flattened batch " + "structure." + }, + ) + pad_to_multiple_of: int | None = field( + default=None, + metadata={"help": "If set, the sequences will be padded to a multiple of this value."}, + ) + precompute_ref_log_probs: bool = field( + default=False, + metadata={ + "help": "Whether to precompute the reference model log probabilities for the entire training dataset " + "before training. This allows to save memory during training, as the reference model does not need to be " + "kept in memory." + }, + ) + precompute_ref_batch_size: int | None = field( + default=None, + metadata={ + "help": "Batch size to use when precomputing reference model log probabilities. This can be set higher " + "than the training batch size to speed up preprocessing. If `None`, defaults to " + "`per_device_train_batch_size` for training and `per_device_eval_batch_size` for evaluation." + }, + ) + + # Parameters that control the training + loss_type: list[str] = field( + default_factory=lambda: ["sigmoid"], + metadata={ + "help": "Type of loss to use. Possible values are: `'sigmoid'`, `'hinge'`, `'ipo'`, `'exo_pair'`, " + "`'nca_pair'`, `'robust'`, `'bco_pair'`, `'sppo_hard'`, `'aot'`, `'aot_unpaired'`, `'apo_zero'`, " + "`'apo_down'`, `'discopop'`, `'sft'`, `'sigmoid_norm'`. If multiple loss types are provided, they will be " + "combined using the weights specified in `loss_weights`.", + }, + ) + loss_weights: list[float] | None = field( + default=None, + metadata={ + "help": "List of loss weights for multi-loss combinations. Used when combining multiple loss types. " + "Example: `[0.8, 0.2, 1.0]` for MPO. If not provided, defaults to equal weights (`1.0`) for all loss " + "types." + }, + ) + ld_alpha: float | None = field( + default=None, + metadata={ + "help": "α parameter from the LD-DPO paper, which controls the weighting of the verbose token " + "log-probabilities in responses. If `None`, no weighting is applied to the verbose part, and the loss is " + "equivalent to the standard DPO loss. Must be in [0.0, 1.0]: `ld_alpha=1.0` applies no weighting, and " + "`ld_alpha=0.0` masks tokens beyond shared lengths.", + }, + ) + f_divergence_type: str = field( + default="reverse_kl", + metadata={ + "help": "f-divergence regularizer between policy and reference (f-DPO paper). Possible values are: " + "`reverse_kl` (default), `forward_kl`, `js_divergence`, `alpha_divergence`.", + }, + ) + f_alpha_divergence_coef: float = field( + default=0.5, + metadata={ + "help": "α coefficient for the α-divergence u^-α regularizer, used only when " + "`f_divergence_type='alpha_divergence'`." + }, + ) + label_smoothing: float = field( + default=0.0, + metadata={ + "help": "Label smoothing parameter used in Robust DPO and EXO. In Robust DPO, it is interpreted as the " + "probability that a preference label is flipped and must lie in [0.0, 0.5); a typical value recommended " + "by the Robust DPO paper is 0.1. In EXO, it corresponds to the ε label smoothing parameter, for which the " + "paper recommends a typical value of 1e-3." + }, + ) + beta: float = field( + default=0.1, + metadata={ + "help": "Parameter controlling the deviation from the reference model. Higher β means less deviation from " + "the reference model. For the IPO loss (`loss_type='ipo'`), this value is the regularization parameter " + "denoted by τ in the [paper](https://huggingface.co/papers/2310.12036)." + }, + ) + use_weighting: bool = field( + default=False, + metadata={ + "help": "Whether to apply WPO-style weighting (https://huggingface.co/papers/2406.11827) to preference " + "pairs using the policy's length-normalized sequence probabilities." + }, + ) + discopop_tau: float = field( + default=0.05, + metadata={ + "help": "τ/temperature parameter from the DiscoPOP paper, which controls the shape of the log-ratio " + "modulated loss when using `loss_type='discopop'`. The paper recommends the default value " + "`discopop_tau=0.05`." + }, + ) + activation_offloading: bool = field( + default=False, + metadata={"help": "Whether to offload the activations to the CPU."}, + ) + sync_ref_model: bool = field( + default=False, + metadata={ + "help": "Whether to synchronize the reference model with the active model every `ref_model_sync_steps` " + "steps, using the `ref_model_mixup_alpha` parameter. This synchronization originates from the " + "[TR-DPO](https://huggingface.co/papers/2404.09656) paper. `sync_ref_model=True` is not yet compatible " + "with PEFT or `precompute_ref_log_probs=True`." + }, + ) + ref_model_mixup_alpha: float = field( + default=0.6, + metadata={ + "help": "α parameter from the TR-DPO paper, which controls the mix between the current policy and the " + "previous reference policy during updates. The reference policy is updated according to the equation: " + "`π_ref = α * π_θ + (1 - α) * π_ref_prev`. To use this parameter, you must set `sync_ref_model=True`." + }, + ) + ref_model_sync_steps: int = field( + default=512, + metadata={ + "help": "τ parameter from the TR-DPO paper, which determines how frequently the current policy is " + "synchronized with the reference policy. To use this parameter, you must set `sync_ref_model=True`." + }, + ) + + # Deprecated parameters + pad_token: str | None = field( + default=None, + metadata={ + "help": "Deprecated. Set `tokenizer.pad_token` directly and pass it as `processing_class` to the trainer instead." + }, + ) + + def __post_init__(self): + if isinstance(self.loss_type, str): + self.loss_type = [self.loss_type] + if self.loss_weights is not None and len(self.loss_weights) != len(self.loss_type): + raise ValueError( + "`loss_weights` must have the same length as `loss_type` when combining multiple losses. " + f"Got {len(self.loss_weights)} weights for {len(self.loss_type)} loss types." + ) + if self.pad_token is not None: + warnings.warn( + "`pad_token` is deprecated and will be removed in v2.0.0. " + "Set `tokenizer.pad_token` directly and pass it as `processing_class` to the trainer instead.", + FutureWarning, + stacklevel=3, + ) + if self.truncation_mode == "keep_end": + warnings.warn( + "The `'keep_end'` truncation mode is deprecated and will be removed in v2.0.0. " + "Use `truncation_mode='keep_start'` (the default) instead.", + FutureWarning, + stacklevel=3, + ) + + super().__post_init__() diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/dpo_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/dpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..cd91d913e0183118540d623155da20a23a51b215 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/dpo_trainer.py @@ -0,0 +1,1621 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import contextlib +import json +import os +import textwrap +from collections import defaultdict +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import torch +import torch.nn.functional as F +import transformers +from accelerate import PartialState +from accelerate.logging import get_logger +from accelerate.utils import is_peft_model, tqdm +from datasets import Dataset, IterableDataset, IterableDatasetDict, concatenate_datasets +from datasets.fingerprint import Hasher +from packaging.version import Version +from torch.utils.data import DataLoader +from transformers import ( + AutoProcessor, + DataCollator, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, +) +from transformers.data.data_collator import DataCollatorMixin +from transformers.trainer_callback import TrainerCallback +from transformers.trainer_utils import EvalPrediction +from transformers.utils import is_liger_kernel_available, is_peft_available + +from ..data_utils import apply_chat_template, extract_prompt, is_conversational, prepare_multimodal_messages +from ..models import get_act_offloading_ctx_manager, prepare_deepspeed, prepare_fsdp +from ..models.utils import disable_gradient_checkpointing +from .base_trainer import _BaseTrainer +from .callbacks import SyncRefModelCallback +from .dpo_config import DPOConfig +from .utils import ( + create_model_from_path, + disable_dropout_in_model, + entropy_from_logits, + flush_left, + get_config_model_id, + hash_module, + pad, + selective_log_softmax, + use_adapter, +) + + +if is_peft_available(): + import peft + from peft import LoraConfig, PeftConfig, PeftModel, get_peft_model + + +if is_liger_kernel_available(): + from liger_kernel.chunked_loss import LigerFusedLinearDPOLoss + + +logger = get_logger(__name__) + + +FLASH_ATTENTION_VARIANTS = { + "flash_attention_2", + "flash_attention_3", + "kernels-community/flash-attn2", + "kernels-community/flash-attn3", + "kernels-community/vllm-flash-attn3", +} + + +def get_dataset_column_names(dataset: Dataset | IterableDataset) -> list[str]: + return list(next(iter(dataset)).keys()) if dataset.column_names is None else dataset.column_names + + +@dataclass +class DataCollatorForPreference(DataCollatorMixin): + """ + Data collator used for preference data. Inputs are dynamically padded to the maximum length of a batch. + + This collator expects each example in the input list to be a dictionary containing the keys `"prompt_ids"`, + `"chosen_ids"` and `"rejected_ids"`. The collator returns a dictionary containing the following keys: + - `"input_ids"`: Tensor of input IDs, padded to the maximum length of the batch. The first half of the batch + corresponds to the `"chosen_ids"` and the second half to the `"rejected_ids"`. + - `"attention_mask"`: Tensor of attention mask, padded to the maximum length of the batch. + - `"completion_mask"`: Tensor indicating the positions of the completion tokens, padded to the maximum length of + the batch. + + Optionally, the examples can contain a `"ref_chosen_logps"` and `"ref_rejected_logps"` keys, in which case the + returned dictionary will also contain these keys with the corresponding tensors. + + Args: + pad_token_id (`int`): + Token ID to use for padding. + max_length (`int`, *optional*): + Maximum length of the sequences after concatenation. Sequences longer than `max_length` are truncated + before padding, which avoids allocating oversized tensors for batches containing very long sequences. + truncation_mode (`str`, *optional*, defaults to `"keep_start"`): + Truncation mode when a concatenated sequence exceeds `max_length`. Possible values are `"keep_end"` and + `"keep_start"`. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + return_tensors (`str`, *optional*, defaults to `"pt"`): + Type of Tensor to return. Only `"pt"` is currently supported. + + Examples: + ```python + >>> from trl.trainer.dpo_trainer import DataCollatorForPreference + + >>> collator = DataCollatorForPreference(pad_token_id=0) + >>> examples = [ + ... {"prompt_ids": [1, 2, 3], "chosen_ids": [4, 5], "rejected_ids": [6]}, + ... {"prompt_ids": [7, 8], "chosen_ids": [9], "rejected_ids": [10, 11]}, + ... ] + >>> collator(examples) + {'input_ids': tensor([[ 1, 2, 3, 4, 5], + [ 7, 8, 9, 0, 0], + [ 1, 2, 3, 6, 0], + [ 7, 8, 10, 11, 0]]), + 'attention_mask': tensor([[1, 1, 1, 1, 1], + [1, 1, 1, 0, 0], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 0]]), + 'completion_mask': tensor([[0, 0, 0, 1, 1], + [0, 0, 1, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 1, 1, 0]])} + ``` + """ + + pad_token_id: int + max_length: int | None = None + truncation_mode: str = "keep_start" + pad_to_multiple_of: int | None = None + return_tensors: str = "pt" + + def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + prompt_chosen_ids = [example["prompt_ids"] + example["chosen_ids"] for example in examples] + prompt_rejected_ids = [example["prompt_ids"] + example["rejected_ids"] for example in examples] + chosen_mask = [[0] * len(example["prompt_ids"]) + [1] * len(example["chosen_ids"]) for example in examples] + rejected_mask = [[0] * len(example["prompt_ids"]) + [1] * len(example["rejected_ids"]) for example in examples] + + if self.max_length is not None: + if self.truncation_mode == "keep_start": + sl = slice(None, self.max_length) + elif self.truncation_mode == "keep_end": + sl = slice(-self.max_length, None) + else: + raise ValueError( + f"Unsupported truncation mode: {self.truncation_mode}, expected 'keep_start' or 'keep_end'" + ) + prompt_chosen_ids = [ids[sl] for ids in prompt_chosen_ids] + prompt_rejected_ids = [ids[sl] for ids in prompt_rejected_ids] + chosen_mask = [m[sl] for m in chosen_mask] + rejected_mask = [m[sl] for m in rejected_mask] + + chosen_attention_mask = [[1] * len(ids) for ids in prompt_chosen_ids] + rejected_attention_mask = [[1] * len(ids) for ids in prompt_rejected_ids] + input_ids = prompt_chosen_ids + prompt_rejected_ids + attention_mask = chosen_attention_mask + rejected_attention_mask + completion_mask = chosen_mask + rejected_mask + + # Convert to tensor + input_ids = [torch.tensor(ids) for ids in input_ids] + attention_mask = [torch.tensor(m, dtype=torch.long) for m in attention_mask] + completion_mask = [torch.tensor(m, dtype=torch.long) for m in completion_mask] + if "ref_chosen_logps" in examples[0]: + ref_chosen_logps = torch.tensor([example["ref_chosen_logps"] for example in examples]) + if "ref_rejected_logps" in examples[0]: + ref_rejected_logps = torch.tensor([example["ref_rejected_logps"] for example in examples]) + + # Pad + output = {} + output["input_ids"] = pad( + input_ids, + padding_value=self.pad_token_id, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + output["attention_mask"] = pad( + attention_mask, + padding_value=0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + output["completion_mask"] = pad( + completion_mask, + padding_value=0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + if "ref_chosen_logps" in examples[0]: + output["ref_chosen_logps"] = ref_chosen_logps + if "ref_rejected_logps" in examples[0]: + output["ref_rejected_logps"] = ref_rejected_logps + return output + + +@dataclass +class DataCollatorForVisionPreference(DataCollatorMixin): + """ + Data collator for vision-preference tasks. + + Unlike text-only datasets, where the collator typically receives pre-tokenized inputs ready for batching, + vision-language data processing involves converting images into pixel values. This conversion is disk-intensive, + making upfront preprocessing of the entire dataset impractical. Therefore, this collator performs tokenization and + image processing on-the-fly to efficiently prepare batches. + + Each input example should be a dictionary containing at least: + - An `"images"` key holding a list of images, or an `"image"` key holding a single image. + - Keys `"prompt"` `"chosen"` and `"rejected"` for the prompt and preference responses. + + The collator outputs a dictionary including: + - `"input_ids"`: Tensor of token IDs. + - `"attention_mask"`: Tensor indicating attention mask. + - `"completion_mask"`: Tensor indicating which tokens correspond to completions. + - `"pixel_values"`: Tensor representing image pixel values. + + Additional keys may be present depending on the processor, such as `"image_grid_thw"` or `"image_position_ids"`. + + Args: + processor ([`~transformers.ProcessorMixin`]): + The processor used to tokenize text and process images. It must be a subclass of + [`~transformers.ProcessorMixin`] and include a `tokenizer` with a defined `pad_token_id`. + max_length (`int`, *optional*): + Maximum sequence length. Sequences longer than `max_length` are truncated before padding, which avoids + allocating oversized tensors for batches containing very long sequences. Only `"keep_start"` truncation + applies to vision datasets; `"keep_end"` is rejected upstream. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + return_tensors (`str`, *optional*, defaults to `"pt"`): + The tensor type to return. Currently, only `"pt"` (PyTorch tensors) is supported. + + Example: + ```python + >>> from trl.trainer.dpo_trainer import DataCollatorForVisionPreference + >>> from transformers import AutoProcessor + + >>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct") + >>> collator = DataCollatorForVisionPreference(processor) + >>> examples = [ + ... { + ... "images": [Image.open("image_0.png")], + ... "prompt": [{"role": "user", "content": "What is this?"}], + ... "chosen": [{"role": "assistant", "content": "This is a cat."}], + ... "rejected": [{"role": "assistant", "content": "This is a dog."}], + ... }, + ... { + ... "images": [Image.open("image_1.png")], + ... "prompt": [{"role": "user", "content": "Describe this image."}], + ... "chosen": [{"role": "assistant", "content": "A beautiful landscape."}], + ... "rejected": [{"role": "assistant", "content": "An urban cityscape."}], + ... }, + ... ] + >>> collator(examples) + {'input_ids': tensor([[151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, 151644, 872, 198, 151652, 151655, 151655, 151655, 151655, 151653, 3838, 374, 419, 30, 151645, 198, 151644, 77091, 198, 1986, 374, 264, 8251, 13, 151645, 198], + [151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, 151644, 872, 198, 151652, 151655, 151655, 151655, 151655, 151653, 74785, 419, 2168, 13, 151645, 198, 151644, 77091, 198, 32, 6233, 18414, 13, 151645, 198, 151643], + [151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, 151644, 872, 198, 151652, 151655, 151655, 151655, 151655, 151653, 3838, 374, 419, 30, 151645, 198, 151644, 77091, 198, 1986, 374, 264, 5562, 13, 151645, 198], + [151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, 151644, 872, 198, 151652, 151655, 151655, 151655, 151655, 151653, 74785, 419, 2168, 13, 151645, 198, 151644, 77091, 198, 2082, 15662, 3283, 57518, 13, 151645, 198]]), + 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), + 'pixel_values': tensor([[-1.3251, 0.1347, -0.4784, ..., 0.4537, -0.0156, 1.2358], + [ 0.5727, 0.4997, -0.9164, ..., -0.5701, 0.7950, -0.7123], + [-0.0550, -0.8288, 1.0690, ..., -0.1293, -0.1151, 1.6055], + ..., + [ 0.2953, 0.5581, 0.1785, ..., -0.7123, -0.7977, 0.1693], + [-0.7558, 1.0398, 1.3464, ..., -0.5417, -0.5417, 0.4395], + [ 0.8063, 0.6895, 0.4267, ..., -0.4422, 1.3354, 0.1266]]), + 'image_grid_thw': tensor([[1, 4, 4], + [1, 4, 4], + [1, 4, 4], + [1, 4, 4]]), + 'completion_mask': tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]])} + ``` + """ + + processor: ProcessorMixin + max_length: int | None = None + pad_to_multiple_of: int | None = None + return_tensors: str = "pt" + + def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + if self.pad_to_multiple_of is not None: + raise NotImplementedError( + "Padding to a multiple of a value is not yet implemented for vision-language modeling and " + "prompt-completion data." + ) + if "image" in examples[0]: + for example in examples: + example["images"] = [example.pop("image")] + images = [example["images"] for example in examples] * 2 # repeat for chosen and rejected + # Transformers requires at least one image in the batch, otherwise it throws an error + if all(img_list == [] for img_list in images): + images = None + if is_conversational(examples[0]): # conversational case + for example in examples: + example["prompt"] = prepare_multimodal_messages(example["prompt"], images=example["images"]) + example["chosen"] = prepare_multimodal_messages(example["chosen"]) + example["rejected"] = prepare_multimodal_messages(example["rejected"]) + examples = [apply_chat_template(example, self.processor) for example in examples] + + prompts = [example["prompt"] for example in examples] * 2 # repeat for chosen and rejected + chosens = [example["chosen"] for example in examples] + rejecteds = [example["rejected"] for example in examples] + + processed_prompts = self.processor( + images=images, + text=prompts, + padding=True, + padding_side="left", + return_tensors=self.return_tensors, + add_special_tokens=False, # to avoid adding the BOS, twice see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens + ) + processed_chosens = self.processor( + text=chosens, + padding=True, + padding_side="right", + return_tensors=self.return_tensors, + add_special_tokens=False, # to avoid adding the BOS, twice see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens + ) + processed_rejecteds = self.processor( + text=rejecteds, + padding=True, + padding_side="right", + return_tensors=self.return_tensors, + add_special_tokens=False, # to avoid adding the BOS, twice see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens + ) + + # Concatenate prompts and completions + prompt_ids, prompt_mask = processed_prompts["input_ids"], processed_prompts["attention_mask"] + chosen_ids, chosen_mask = processed_chosens["input_ids"], processed_chosens["attention_mask"] + rejected_ids, rejected_mask = processed_rejecteds["input_ids"], processed_rejecteds["attention_mask"] + pad_token_id = self.processor.tokenizer.pad_token_id or self.processor.tokenizer.eos_token_id + completion_ids = torch.cat(tuple(pad([chosen_ids, rejected_ids], padding_value=pad_token_id))) + completion_mask = torch.cat(tuple(pad([chosen_mask, rejected_mask], padding_value=0))) + input_ids = torch.cat((prompt_ids, completion_ids), dim=1) + attention_mask = torch.cat((prompt_mask, completion_mask), dim=1) + completion_mask = torch.cat((torch.zeros_like(prompt_mask), completion_mask), dim=1) + if "token_type_ids" in processed_prompts: # special case for Gemma + prompt_token_type_ids = processed_prompts["token_type_ids"] + chosen_type_ids = processed_chosens["token_type_ids"] + rejected_type_ids = processed_rejecteds["token_type_ids"] + completion_token_type_ids = torch.cat(tuple(pad([chosen_type_ids, rejected_type_ids], padding_value=0))) + token_type_ids = torch.cat((prompt_token_type_ids, completion_token_type_ids), dim=1) + if "mm_token_type_ids" in processed_prompts: # special case for Qwen2.5-VL + prompt_mm_token_type_ids = processed_prompts["mm_token_type_ids"] + mm_token_type_ids = torch.cat((prompt_mm_token_type_ids, torch.zeros_like(completion_ids)), dim=1) + + # Flush left to reduce padding + if "token_type_ids" in processed_prompts and "mm_token_type_ids" in processed_prompts: + attention_mask, input_ids, completion_mask, token_type_ids, mm_token_type_ids = flush_left( + attention_mask, input_ids, completion_mask, token_type_ids, mm_token_type_ids + ) + elif "token_type_ids" in processed_prompts: + attention_mask, input_ids, completion_mask, token_type_ids = flush_left( + attention_mask, input_ids, completion_mask, token_type_ids + ) + elif "mm_token_type_ids" in processed_prompts: + attention_mask, input_ids, completion_mask, mm_token_type_ids = flush_left( + attention_mask, input_ids, completion_mask, mm_token_type_ids + ) + else: + attention_mask, input_ids, completion_mask = flush_left(attention_mask, input_ids, completion_mask) + + if self.max_length is not None: + input_ids = input_ids[:, : self.max_length] + attention_mask = attention_mask[:, : self.max_length] + completion_mask = completion_mask[:, : self.max_length] + if "token_type_ids" in processed_prompts: + token_type_ids = token_type_ids[:, : self.max_length] + if "mm_token_type_ids" in processed_prompts: + mm_token_type_ids = mm_token_type_ids[:, : self.max_length] + + # Build the output dictionary + output = processed_prompts # we take processed_prompts because it contains the images + output["input_ids"] = input_ids + output["attention_mask"] = attention_mask + output["completion_mask"] = completion_mask + if "token_type_ids" in processed_prompts: + output["token_type_ids"] = token_type_ids + if "mm_token_type_ids" in processed_prompts: + output["mm_token_type_ids"] = mm_token_type_ids + return output + + +class DPOTrainer(_BaseTrainer): + """ + Trainer for Direct Preference Optimization (DPO) method. This algorithm was initially proposed in the paper [Direct + Preference Optimization: Your Language Model is Secretly a Reward Model](https://huggingface.co/papers/2305.18290). + This class is a wrapper around the [`~transformers.Trainer`] class and inherits all of its attributes and methods. + + Example: + + ```python + >>> from trl import DPOTrainer + >>> from datasets import load_dataset + + >>> dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") + + >>> trainer = DPOTrainer( + ... model="Qwen/Qwen2.5-0.5B-Instruct", + ... train_dataset=dataset, + ... ) + >>> trainer.train() + ``` + + Args: + model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]): + Model to be trained. Can be either: + + - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using `.from_pretrained` (where `` is derived from the model + config) with the keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported. + - A [`~peft.PeftModel`] object. Only causal language models are supported. + ref_model ([`~transformers.PreTrainedModel`], *optional*): + Reference model used to compute the reference log probabilities. + + - If provided, this model is used directly as the reference policy. + - If `None`, the trainer will automatically use the initial policy corresponding to `model`, i.e. the model + state before DPO training starts. + args ([`DPOConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + data_collator ([`~transformers.DataCollator`], *optional*): + Function to use to form a batch from a list of elements of the processed `train_dataset` or `eval_dataset`. + Will default to [`~trainer.dpo_trainer.DataCollatorForPreference`] if the model is a language model and + [`~trainer.dpo_trainer.DataCollatorForVisionPreference`] if the model is a vision-language model. Custom + collators must truncate sequences before padding; the trainer does not apply post-collation truncation. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + Dataset to use for training. This trainer supports both [language modeling](#language-modeling) type and + [prompt-completion](#prompt-completion) type. The format of the samples can be either: + + - [Standard](dataset_formats#standard): Each sample contains plain text. + - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role + and content). + eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`): + Dataset to use for evaluation. It must meet the same requirements as `train_dataset`. + processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. The padding side must be set to "left". If `None`, the + processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A + padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token, + `tokenizer.eos_token` will be used as the default. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function that will be used to compute metrics at evaluation. Must take a + [`~transformers.EvalPrediction`] and return a dictionary string to metric values. When passing + [`SFTConfig`] with `batch_eval_metrics` set to `True`, your `compute_metrics` function must take a boolean + `compute_result` argument. This will be triggered after the last eval batch to signal that the function + needs to calculate and return the global summary statistics rather than accumulating the batch-level + statistics. + callbacks (list of [`~transformers.TrainerCallback`], *optional*): + List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed + in [here](https://huggingface.co/docs/transformers/main_classes/callback). + + If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`] + method. + optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`): + A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your + model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration used to wrap the model. If `None`, the model is not wrapped. + """ + + _tag_names = ["trl", "dpo"] + _name = "DPO" + _paper = { + "title": "Direct Preference Optimization: Your Language Model is Secretly a Reward Model", + "id": "2305.18290", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @inproceedings{rafailov2023direct, + title = {{Direct Preference Optimization: Your Language Model is Secretly a Reward Model}}, + author = {Rafael Rafailov and Archit Sharma and Eric Mitchell and Christopher D. Manning and Stefano Ermon and Chelsea Finn}, + year = 2023, + booktitle = {Advances in Neural Information Processing Systems 36: Annual Conference on Neural Information Processing Systems 2023, NeurIPS 2023, New Orleans, LA, USA, December 10 - 16, 2023}, + url = {http://papers.nips.cc/paper_files/paper/2023/hash/a85b405ed65c6477a4fe8302b5e06ce7-Abstract-Conference.html}, + editor = {Alice Oh and Tristan Naumann and Amir Globerson and Kate Saenko and Moritz Hardt and Sergey Levine}, + }"""), + } + + def __init__( + self, + model: "str | PreTrainedModel | PeftModel", + ref_model: PreTrainedModel | None = None, + args: DPOConfig | None = None, + data_collator: DataCollator | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + peft_config: "PeftConfig | None" = None, + ): + # Args + if args is None: + model_name = model if isinstance(model, str) else get_config_model_id(model.config) + model_name = model_name.split("/")[-1] + args = DPOConfig(f"{model_name}-DPO") + + if train_dataset is None: + raise ValueError("`train_dataset` is required") + elif isinstance(train_dataset, IterableDataset): + # IterableDataset requires dispatch_batches=False because Accelerate's dispatch mode may try to concatenate + # batches from multiple processes, leading to mismatch errors. + if args.accelerator_config.dispatch_batches is True: + logger.warning( + "You are using an `IterableDataset` for training with `dispatch_batches=True`. `dispatch_batches` " + "is forced to `False` when using an `IterableDataset`. To remove this warning, unset " + "`dispatch_batches` in `DPOConfig` or set it to `False`." + ) + args.accelerator_config.dispatch_batches = False + + # Model + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + model = create_model_from_path(model, **model_init_kwargs) + else: + if args.model_init_kwargs is not None: + logger.warning( + "You passed `model_init_kwargs` to the `DPOConfig`, but your model is already instantiated. " + "The `model_init_kwargs` will be ignored." + ) + # Non-quantized models do not have the `is_loaded_in_{8,4}bit` attributes, whereas quantized models do + _is_quantized_model = getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False) + if ref_model is model: + raise ValueError( + "`model` and `ref_model` cannot be the same object. In most cases you should omit `ref_model` and " + "we'll initialize it to a copy of `model` for you." + ) + + # Processing class + if processing_class is None: + processing_class = AutoProcessor.from_pretrained( + get_config_model_id(model.config), trust_remote_code=args.trust_remote_code + ) + + # Handle pad token for processors or tokenizers + if isinstance(processing_class, ProcessorMixin): + self._tokenizer = processing_class.tokenizer + self._is_vlm = True + elif isinstance(processing_class, PreTrainedTokenizerBase): + self._tokenizer = processing_class + self._is_vlm = False + else: + raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`") + + if self._tokenizer.pad_token is None: + self._tokenizer.pad_token = self._tokenizer.eos_token + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge " + "and unload the existing adapter, save the resulting base model, and then pass that base model along " + "with the new `peft_config` to the trainer." + ) + # Create PEFT model + # ZeRO-3 + PEFT for non-quantized models: + # - PEFT's default autocast_adapter_dtype=True upcasts LoRA adapter params to fp32 even when the base model is bf16. + # - ZeRO-3's _allgather_params_coalesced allocates output buffers using the dtype of the first persistent parameter, + # so mixed-dtype persistent_parameters (bf16 base + fp32 LoRA) cause a TypeError on the first optimizer step. + # - Passing autocast_adapter_dtype=False keeps adapter params in the base model dtype (bf16), fixing the mismatch. + # - This is safe: the fp32 upcast is a QLoRA-specific concern (low-bit quantized base models), not needed for + # non-quantized bf16 training. + # - See: + # - TRL issue: https://github.com/huggingface/trl/issues/6089 + # - Upstream issue: https://github.com/deepspeedai/DeepSpeed/issues/8072 + # - autocast_adapter_dtype was introduced in PEFT 0.12.0; before, no upcast existed: no need to pass the kwarg + get_peft_model_kwargs = {} + if ( + args.deepspeed_plugin is not None + and args.deepspeed_plugin.zero_stage == 3 + and not _is_quantized_model + and Version(peft.__version__) >= Version("0.12.0") + ): + get_peft_model_kwargs["autocast_adapter_dtype"] = False + model = get_peft_model(model, peft_config, **get_peft_model_kwargs) + + elif is_peft_model(model) and ref_model is None: + # If the model is a PEFT model with a pretrained adapter, we need to create a "ref" adapter that is a copy + # of the "default" adapter, so that we can use it as the reference model during DPO training. PEFT only + # supports one adapter per model when the LoRA config uses `target_parameters` (see peft#3340), so in that + # case we skip the "ref" adapter and compute the reference log probs with adapters disabled, i.e. with the + # base model. + default_config = model.peft_config["default"] + if isinstance(default_config, LoraConfig) and default_config.target_parameters: + logger.warning( + "PEFT can't add a frozen reference adapter alongside one that uses `target_parameters` " + "(peft#3340), so the reference log probs are computed from the base model (adapters disabled). " + "If you wrapped the model only to apply LoRA, pass a `peft_config` to the trainer instead; if you " + "wrapped it deliberately (pretrained adapter or custom init), note that the base model matches " + "your adapter only when it's freshly zero-initialized. If it is, this warning is safe to ignore." + ) + else: + model.add_adapter("ref", default_config) + for name, param in model.named_parameters(): + if ".default." in name: + ref_name = name.replace(".default.", ".ref.") + ref_param = model.get_parameter(ref_name) + ref_param.data.copy_(param.data) + + # When using gradient checkpointing with PEFT, we need to enable input gradients. transformers.Trainer normally + # handles this, but a bug currently prevents it; see https://github.com/huggingface/transformers/issues/42489 + if is_peft_model(model) and args.gradient_checkpointing: + model.enable_input_require_grads() + + # When using QLoRA, the PEFT adapter weights are converted to bf16 to follow the recommendations from the + # original paper (see https://huggingface.co/papers/2305.14314, paragraph 3). Normally, this can be done by + # passing `autocast_adapter_dtype=False` to `get_peft_model`, but this option is not yet supported for + # quantized models. See: https://github.com/huggingface/peft/issues/2889 + if _is_quantized_model: + for param in model.parameters(): + if param.requires_grad: + param.data = param.data.to(torch.bfloat16) + + # Data collator + self.padding_free = args.padding_free + if self.padding_free: + logger.warning( + "`padding_free=True` is temporarily unavailable after a refactor and is currently disabled. Falling " + "back to standard padding (`padding_free=False`). This feature is planned to return in a future " + "update; for now, please set `padding_free=False` explicitly." + ) + self.padding_free = False + dataset_sample = next(iter(train_dataset)) + self._is_vision_dataset = "image" in dataset_sample or "images" in dataset_sample + if self._is_vision_dataset and not self._is_vlm: + raise ValueError( + "The dataset appears to be vision-related (contains 'image' or 'images' keys), but the provided " + "model does not seem to be a vision-language model. Please check your model and dataset." + ) + if self._is_vision_dataset and args.max_length is not None and args.truncation_mode == "keep_end": + raise ValueError( + "truncation_mode='keep_end' is not supported for vision-language models. Image tokens reside " + "inside the prompt portion of the sequence; depending on the example, keep_end may silently " + "drop them, causing pixel_values to be forwarded to the model with no corresponding visual " + "tokens in input_ids. Use truncation_mode='keep_start' (the default) or set max_length=None." + ) + if self._is_vision_dataset and args.precompute_ref_log_probs: + raise ValueError( + "`precompute_ref_log_probs=True` is not supported for vision datasets. For vision-language " + "models, all data processing is performed on the fly rather than upfront, and running a full " + "forward pass of the reference model over the entire dataset is not supported for large " + "multimodal models. Set `precompute_ref_log_probs=False`." + ) + if data_collator is None and not self._is_vision_dataset: + # Get the pad token: if not provided, use the one from the processing class or the eos token + # if the processing class does not have a pad token. + pad_token = args.pad_token or self._tokenizer.pad_token or self._tokenizer.eos_token + if pad_token not in self._tokenizer.get_vocab(): + raise ValueError( + f"The specified `pad_token` ('{pad_token}') is not found in the vocabulary of the given " + f"`processing_class` ({processing_class.__class__.__name__}). Ensure that the `pad_token` exists " + "in the vocabulary before using it as a padding token." + ) + self._tokenizer.pad_token = pad_token + data_collator = DataCollatorForPreference( + pad_token_id=self._tokenizer.pad_token_id, + max_length=args.max_length, + truncation_mode=args.truncation_mode, + pad_to_multiple_of=args.pad_to_multiple_of, + ) + elif data_collator is None and self._is_vision_dataset: + data_collator = DataCollatorForVisionPreference( + processor=processing_class, + max_length=args.max_length, + pad_to_multiple_of=args.pad_to_multiple_of, + ) + + # Training arguments + self.beta = args.beta + self.precompute_ref_logps = args.precompute_ref_log_probs + self.loss_types = args.loss_type # args.loss_type is already a list + self.loss_weights = args.loss_weights or [1.0] * len(self.loss_types) + self.ld_alpha = args.ld_alpha + self.f_divergence_type = args.f_divergence_type + self.f_alpha_divergence_coef = args.f_alpha_divergence_coef + self.label_smoothing = args.label_smoothing + self.use_weighting = args.use_weighting + if self.use_weighting and any(loss_type in {"aot", "aot_unpaired"} for loss_type in self.loss_types): + raise NotImplementedError( + "WPO-style weighting is not implemented for 'aot' or 'aot_unpaired' because those losses sort " + "samples, which would misalign per-pair weights." + ) + if "robust" in self.loss_types and not (0.0 <= self.label_smoothing < 0.5): + logger.warning( + "The `label_smoothing` parameter should lie in [0.0, 0.5) for the 'robust' loss. You provided " + f"{self.label_smoothing}." + ) + if "exo_pair" in self.loss_types and self.label_smoothing == 0.0: + raise ValueError( + "Label smoothing must be greater than 0.0 when using 'exo_pair' loss. The EXO paper recommends a " + "value of 1e-3." + ) + self.use_liger_kernel = args.use_liger_kernel + if args.use_liger_kernel: + if not is_liger_kernel_available(): + raise ImportError( + "You set `use_liger_kernel=True` but the liger kernel is not available. " + "Please install liger-kernel first: `pip install liger-kernel`" + ) + if len(self.loss_types) != 1: + raise NotImplementedError( + "Multiple loss types are not yet supported when using Liger kernel. If you need this feature, " + "please open a feature request at https://github.com/huggingface/trl/issues." + ) + self.liger_loss_fn = LigerFusedLinearDPOLoss(beta=args.beta, loss_type=self.loss_types[0]) + if compute_metrics is not None: + raise ValueError( + "compute_metrics is not supported with the Liger kernel. compute_metrics requires to be able to " + "recover the logits from the forward pass, but Liger kernel does not materialize logits." + ) + if self.precompute_ref_logps: + raise ValueError( + "Liger DPO loss does not support precomputing reference log probabilities. Either disable " + "`precompute_ref_log_probs` or set `use_liger_kernel` to False." + ) + if is_peft_model(model): + raise NotImplementedError("Liger DPO loss is not implemented for PEFT models.") + + # Dataset + # Skip dataset preparation if it's a VLM, where preprocessing (e.g., image-to-pixel conversion) is too costly + # and done on the fly instead. + skip_prepare_dataset = self._is_vision_dataset + if not skip_prepare_dataset: + train_dataset = self._prepare_dataset(train_dataset, processing_class, args, "train") + if eval_dataset is not None: + if isinstance(eval_dataset, dict): + eval_dataset = { + key: self._prepare_dataset(dataset, processing_class, args, key) + for key, dataset in eval_dataset.items() + } + else: + eval_dataset = self._prepare_dataset(eval_dataset, processing_class, args, "eval") + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + ) + + # Initialize activation offloading context + if self.args.activation_offloading: + self.maybe_activation_offload_context = get_act_offloading_ctx_manager(model=self.model) + else: + self.maybe_activation_offload_context = contextlib.nullcontext() + + # Reference model + if ref_model is None: + if is_peft_model(self.model) or args.precompute_ref_log_probs: + # If PEFT is used, the reference model is not needed since the adapter can be disabled to revert to the + # initial model. If precompute_ref_log_probs is True, the reference model does not need to be kept in + # memory during training. + self.ref_model = None + else: + ref_model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if self.args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + ref_model_init_kwargs["device_map"] = None + ref_model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + ref_model_path = get_config_model_id(self.model.config) + self.ref_model = create_model_from_path(ref_model_path, **ref_model_init_kwargs) + else: + self.ref_model = ref_model + + # Disable dropout in the models + if args.disable_dropout: + disable_dropout_in_model(model) + if self.ref_model is not None: + disable_dropout_in_model(self.ref_model) + + # Initialize the metrics + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + self._total_train_tokens = 0 + + # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the + # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set + # self.model_accepts_loss_kwargs to False to enable scaling. + self.model_accepts_loss_kwargs = False + + # Add tags to the model + self.model.add_model_tags(self._tag_names) + + if self.ref_model is not None: + if self.is_deepspeed_enabled: + self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator) + elif self.is_fsdp_enabled: + self.ref_model = prepare_fsdp(self.ref_model, self.accelerator) + else: + self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True) + + if args.sync_ref_model: + if is_peft_model(self.model): + raise NotImplementedError( + "You passed `sync_ref_model=True` while using a PEFT model, which is currently not supported. " + "With PEFT, DPOTrainer does not keep a separate reference model in memory; instead, it recovers " + "reference behavior by temporarily disabling the adapter. As a result, there is no standalone " + "`ref_model` instance to synchronize. Use `sync_ref_model=False`, or opt for full fine-tuning if " + "you need a synced reference model. If you need `sync_ref_model` to work with PEFT, please open a " + "feature request at https://github.com/huggingface/trl/issues." + ) + if args.precompute_ref_log_probs: + raise ValueError( + "You cannot use `sync_ref_model=True` together with `precompute_ref_log_probs=True`. " + "`precompute_ref_log_probs=True` assumes a fixed reference model, but with `sync_ref_model=True` " + "the reference model is periodically updated during training, making any precomputed reference " + "log-probs stale. Set `precompute_ref_log_probs=False` or disable `sync_ref_model`." + ) + self.add_callback(SyncRefModelCallback(ref_model=self.ref_model, accelerator=self.accelerator)) + + if args.precompute_ref_log_probs: + if isinstance(self.train_dataset, IterableDataset) or isinstance( + self.eval_dataset, (IterableDataset, IterableDatasetDict) + ): + raise ValueError( + "`precompute_ref_log_probs=True` is not supported with IterableDataset. Please use a map-style " + "Dataset or set `precompute_ref_log_probs=False`." + ) + + self.train_dataset = self._precompute_ref_logps( + self.train_dataset, + "train", + self.args.precompute_ref_batch_size or self.args.per_device_train_batch_size, + ) + if self.eval_dataset is not None: + if isinstance(self.eval_dataset, dict): + self.eval_dataset = { + name: self._precompute_ref_logps( + dataset, name, self.args.precompute_ref_batch_size or self.args.per_device_eval_batch_size + ) + for name, dataset in self.eval_dataset.items() + } + else: + self.eval_dataset = self._precompute_ref_logps( + self.eval_dataset, + "eval", + self.args.precompute_ref_batch_size or self.args.per_device_eval_batch_size, + ) + + def _tokenize( + self, + processing_class: PreTrainedTokenizerBase | ProcessorMixin, + input: str | list, + **kwargs, + ) -> dict[str, list]: + """Tokenize a single example for dataset preprocessing. + + Dispatches to `apply_chat_template` for conversational input (list of message dicts) and to `__call__` for + non-conversational input (str). For VLMs, normalizes the batch dimension that processors emit even for single + examples. + + Args: + processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`]): + The tokenizer or processor to use. + input (`str` or `list`): + A string for non-conversational input, or a list of message dicts for conversational input. + **kwargs: + Forwarded to `apply_chat_template` (e.g. `add_generation_prompt`, `return_assistant_tokens_mask`). + + Returns: + `dict` with at least an `"input_ids"` key mapping to a flat `list[int]`. + """ + if isinstance(input, list): # conversational: list of message dicts + if self._is_vlm: + input = prepare_multimodal_messages(input) + result = processing_class.apply_chat_template(input, tokenize=True, return_dict=True, **kwargs) + else: # non-conversational: plain text string + result = processing_class(text=input) + # VLMs emit a batch dimension even for single examples; unwrap it + if self._is_vlm: + return {k: v[0] for k, v in result.items()} + return result + + def _prepare_dataset( + self, + dataset: Dataset | IterableDataset, + processing_class: PreTrainedTokenizerBase | ProcessorMixin, + args: DPOConfig, + dataset_name: str, + ) -> Dataset | IterableDataset: + # Build the kwargs for the `map` function + map_kwargs = {} + if isinstance(dataset, Dataset): # IterableDataset does not support num_proc + map_kwargs["num_proc"] = args.dataset_num_proc + + with PartialState().main_process_first(): + # Extract the prompt if needed + first_example = next(iter(dataset)) + if "prompt" not in first_example: + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Extracting prompt from {dataset_name} dataset" + dataset = dataset.map(extract_prompt, **map_kwargs) + + # Add EOS token if needed: non-conversational only + first_example = next(iter(dataset)) + if not is_conversational(first_example): + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Adding EOS to {dataset_name} dataset" + + def add_eos(example, eos_token): + if not example["chosen"].endswith(eos_token): + example["chosen"] = example["chosen"] + eos_token + if not example["rejected"].endswith(eos_token): + example["rejected"] = example["rejected"] + eos_token + return example + + dataset = dataset.map(add_eos, fn_kwargs={"eos_token": self._tokenizer.eos_token}, **map_kwargs) + + # Tokenize the dataset + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Tokenizing {dataset_name} dataset" + + def tokenize_fn(example, processing_class): + tools = example.get("tools") + tools = json.loads(tools) if isinstance(tools, str) else tools + output = {} + if is_conversational(example): + prompt_ids = self._tokenize( + processing_class, + example["prompt"], + tools=tools, + add_generation_prompt=True, + **example.get("chat_template_kwargs", {}), + )["input_ids"] + prompt_chosen_ids = self._tokenize( + processing_class, + example["prompt"] + example["chosen"], + tools=tools, + **example.get("chat_template_kwargs", {}), + )["input_ids"] + prompt_rejected_ids = self._tokenize( + processing_class, + example["prompt"] + example["rejected"], + tools=tools, + **example.get("chat_template_kwargs", {}), + )["input_ids"] + else: + prompt_ids = self._tokenize(processing_class, example["prompt"])["input_ids"] + prompt_chosen_ids = self._tokenize(processing_class, example["prompt"] + example["chosen"])[ + "input_ids" + ] + prompt_rejected_ids = self._tokenize(processing_class, example["prompt"] + example["rejected"])[ + "input_ids" + ] + + # Check if the tokenized prompt starts with the tokenized prompt+completion + if not prompt_chosen_ids[: len(prompt_ids)] == prompt_ids: + logger.warning( + "Mismatch between tokenized prompt and the start of tokenized prompt+chosen. " + "This may be due to unexpected tokenizer behavior, whitespace issues, or special " + "token handling. Verify that the tokenizer is processing text consistently." + ) + if not prompt_rejected_ids[: len(prompt_ids)] == prompt_ids: + logger.warning( + "Mismatch between tokenized prompt and the start of tokenized prompt+rejected. " + "This may be due to unexpected tokenizer behavior, whitespace issues, or special " + "token handling. Verify that the tokenizer is processing text consistently." + ) + + output["prompt_ids"] = prompt_ids + output["chosen_ids"] = prompt_chosen_ids[len(prompt_ids) :] + output["rejected_ids"] = prompt_rejected_ids[len(prompt_ids) :] + return output + + dataset = dataset.map(tokenize_fn, fn_kwargs={"processing_class": processing_class}, **map_kwargs) + + return dataset + + def _set_signature_columns_if_needed(self): + # If `self.args.remove_unused_columns` is True, non-signature columns are removed. + # By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids" + # and "attention_mask"). + if self._signature_columns is None: + if self._is_vision_dataset: + self._signature_columns = [ + "prompt", + "chosen", + "rejected", + "image", + "images", + "tools", + "chat_template_kwargs", + ] + else: + self._signature_columns = [ + "prompt_ids", + "chosen_ids", + "rejected_ids", + "ref_chosen_logps", + "ref_rejected_logps", + ] + + def _precompute_ref_logps(self, dataset: Dataset, name: str, batch_size: int) -> Dataset: + model_hash = hash_module(self.ref_model or self.model) + fingerprint = Hasher.hash((dataset._fingerprint, model_hash)) + cache_file = dataset._get_cache_file_path(fingerprint) + + if os.path.exists(cache_file): + return concatenate_datasets([dataset, Dataset.from_file(cache_file)], axis=1) + + dataloader = DataLoader( + dataset, + batch_size=batch_size, + collate_fn=self.data_collator, + num_workers=self.args.dataloader_num_workers, + pin_memory=self.args.dataloader_pin_memory, + shuffle=False, + ) + data_loader = self.accelerator.prepare(dataloader) + ref_chosen_logps = [] + ref_rejected_logps = [] + for padded_batch in tqdm(iterable=data_loader, desc=f"Computing reference log probs for {name} dataset"): + ref_chosen_logp, ref_rejected_logp = self.compute_ref_log_probs(padded_batch) + ref_chosen_logp, ref_rejected_logp = self.accelerator.gather_for_metrics( + (ref_chosen_logp, ref_rejected_logp) + ) + ref_chosen_logps.append(ref_chosen_logp.cpu()) + ref_rejected_logps.append(ref_rejected_logp.cpu()) + + ref_chosen_logps = torch.cat(ref_chosen_logps) + ref_rejected_logps = torch.cat(ref_rejected_logps) + + if self.accelerator.is_main_process: + + def add_ref_logps(batch, indices): + return { + "ref_chosen_logps": ref_chosen_logps[indices], + "ref_rejected_logps": ref_rejected_logps[indices], + } + + dataset.map( + add_ref_logps, + with_indices=True, + batched=True, + remove_columns=dataset.column_names, + new_fingerprint=fingerprint, + desc=f"Caching reference log probs for {name} dataset", + ) + self.accelerator.wait_for_everyone() + + return concatenate_datasets([dataset, Dataset.from_file(cache_file)], axis=1) + + def compute_ref_log_probs(self, inputs): + """Computes reference log probabilities for a single padded batch.""" + device = self.accelerator.device + + _non_model_keys = {"completion_mask", "ref_chosen_logps", "ref_rejected_logps"} + model_kwargs = {k: v for k, v in inputs.items() if k not in _non_model_keys} + model_kwargs["use_cache"] = False + + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + if self.ref_model is None: + if is_peft_model(self.model): + model = self.accelerator.unwrap_model(self.model) + with use_adapter(model, adapter_name="ref" if "ref" in model.peft_config else None): + ref_outputs = self.model(**model_kwargs) + else: + ref_outputs = self.model(**model_kwargs) + else: + ref_outputs = self.ref_model(**model_kwargs) + + input_ids = inputs["input_ids"] + completion_mask = inputs["completion_mask"] + shift_labels = input_ids[..., 1:] + shift_completion_mask = completion_mask[..., 1:] + ref_shift_logits = ref_outputs.logits[..., :-1, :] + ref_per_token_logps = selective_log_softmax(ref_shift_logits, shift_labels) + ref_per_token_logps[shift_completion_mask == 0] = 0.0 + + if self.ld_alpha is None: + ref_logps = ref_per_token_logps.sum(dim=1) + else: + comp_pos = shift_completion_mask.cumsum(dim=1) + comp_lens = shift_completion_mask.sum(dim=1).long() + chosen_lens, rejected_lens = comp_lens.chunk(2, dim=0) + shared_lens = torch.minimum(chosen_lens, rejected_lens) + shared_lens = torch.cat([shared_lens, shared_lens], dim=0).to(device) + shared_mask = (comp_pos > 0) & (comp_pos <= shared_lens.unsqueeze(1)) + tail_mask = comp_pos > shared_lens.unsqueeze(1) + shared_logps = (ref_per_token_logps * shared_mask).sum(dim=1) + tail_logps = (ref_per_token_logps * tail_mask).sum(dim=1) + ref_logps = shared_logps + self.ld_alpha * tail_logps + + ref_chosen_logps, ref_rejected_logps = ref_logps.chunk(2, dim=0) + return ref_chosen_logps, ref_rejected_logps + + def _compute_loss_liger(self, model, inputs, return_outputs): + if return_outputs: + raise RuntimeError( + "return_outputs=True is not supported with the Liger DPO loss. The Liger loss computes the loss " + "without materializing logits, so outputs cannot be returned." + ) + + mode = "train" if self.model.training else "eval" + + _non_model_keys = {"completion_mask", "ref_chosen_logps", "ref_rejected_logps"} + model_kwargs = {k: v for k, v in inputs.items() if k not in _non_model_keys} + model_kwargs["use_cache"] = False + + # `base_model` gives the backbone model (skipping `lm_head`) — text decoder for LMs, multimodal wrapper for + # VLMs (so vision-token injection runs before the text decoder). `get_decoder()` won't do: on VLMs it + # returns just the text stack and feeds image-placeholder IDs through it. + # Pre-5.0 transformers VLMs set `base_model_prefix = ""` so `base_model is self` (re-runs `lm_head`). + # Fall back to `.model` there. + if self._is_vlm and Version(transformers.__version__) < Version("5.0.0"): + backbone, ref_backbone = model.model, self.ref_model.model + else: + backbone, ref_backbone = model.base_model, self.ref_model.base_model + + outputs = backbone(**model_kwargs) + hidden_states = outputs.last_hidden_state[:, :-1].contiguous() + lm_head = model.get_output_embeddings() + weight = lm_head.weight + bias = lm_head.bias + + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + ref_outputs = ref_backbone(**model_kwargs) + ref_lm_head = self.ref_model.get_output_embeddings() + ref_hidden_states = ref_outputs.last_hidden_state[:, :-1].contiguous() + ref_weight = ref_lm_head.weight + ref_bias = ref_lm_head.bias + + input_ids = model_kwargs["input_ids"] + completion_mask = inputs["completion_mask"] + shift_completion_mask = completion_mask[:, 1:] + labels = input_ids[:, 1:].clone() + labels[shift_completion_mask == 0] = -100 + + loss, metrics = self.liger_loss_fn( + weight, hidden_states, labels, bias, ref_hidden_states, ref_weight, ref_bias + ) + + ( + chosen_logps, + rejected_logps, + chosen_logits_mean, + rejected_logits_mean, + nll_loss, + chosen_rewards, + rejected_rewards, + ) = metrics + + if mode == "train": + num_tokens_in_batch = self.accelerator.gather_for_metrics(inputs["attention_mask"].sum()).sum().item() + self._total_train_tokens += num_tokens_in_batch + self._metrics[mode]["num_tokens"] = [self._total_train_tokens] + + avg_chosen_logits = self.accelerator.gather_for_metrics(chosen_logits_mean).mean().item() + avg_rejected_logits = self.accelerator.gather_for_metrics(rejected_logits_mean).mean().item() + self._metrics[mode]["logits/chosen"].append(avg_chosen_logits) + self._metrics[mode]["logits/rejected"].append(avg_rejected_logits) + + agg_chosen_rewards = self.accelerator.gather(chosen_rewards) + agg_rejected_rewards = self.accelerator.gather(rejected_rewards) + self._metrics[mode]["rewards/chosen"].append(agg_chosen_rewards.mean().item()) + self._metrics[mode]["rewards/rejected"].append(agg_rejected_rewards.mean().item()) + + reward_accuracies = (chosen_rewards > rejected_rewards).float() + agg_reward_accuracies = self.accelerator.gather(reward_accuracies) + self._metrics[mode]["rewards/accuracies"].append(agg_reward_accuracies.mean().item()) + + margins = chosen_rewards - rejected_rewards + agg_margins = self.accelerator.gather(margins) + self._metrics[mode]["rewards/margins"].append(agg_margins.mean().item()) + + self._metrics[mode]["logps/chosen"].append(self.accelerator.gather(chosen_logps).mean().item()) + self._metrics[mode]["logps/rejected"].append(self.accelerator.gather(rejected_logps).mean().item()) + + return loss + + def _compute_loss(self, model, inputs, return_outputs): + mode = "train" if self.model.training else "eval" + device = self.accelerator.device + + _non_model_keys = {"completion_mask", "ref_chosen_logps", "ref_rejected_logps"} + model_kwargs = {k: v for k, v in inputs.items() if k not in _non_model_keys} + model_kwargs["use_cache"] = False + outputs = model(**model_kwargs) + + input_ids = inputs["input_ids"] + completion_mask = inputs["completion_mask"] + shift_logits = outputs.logits[..., :-1, :] + shift_labels = input_ids[..., 1:] + shift_completion_mask = completion_mask[..., 1:] + per_token_logps = selective_log_softmax(shift_logits, shift_labels) + per_token_logps[shift_completion_mask == 0] = 0.0 # mask out non-completion tokens + if self.ld_alpha is None: + logps = per_token_logps.sum(dim=1) # sum over sequence length + else: + comp_pos = shift_completion_mask.cumsum(dim=1) + comp_lens = shift_completion_mask.sum(dim=1).long() + chosen_lens, rejected_lens = comp_lens.chunk(2, dim=0) + shared_lens = torch.minimum(chosen_lens, rejected_lens) + shared_lens = torch.cat([shared_lens, shared_lens], dim=0).to(device) + shared_mask = (comp_pos > 0) & (comp_pos <= shared_lens.unsqueeze(1)) # shared: 1 <= pos <= shared_len + tail_mask = comp_pos > shared_lens.unsqueeze(1) # tail: pos > shared_len + shared_logps = (per_token_logps * shared_mask).sum(dim=1) + tail_logps = (per_token_logps * tail_mask).sum(dim=1) + logps = shared_logps + self.ld_alpha * tail_logps + chosen_logps, rejected_logps = logps.chunk(2, dim=0) # batch is [chosen, rejected] + + if self.precompute_ref_logps: + ref_chosen_logps, ref_rejected_logps = inputs["ref_chosen_logps"], inputs["ref_rejected_logps"] + else: + # When gradient checkpointing is enabled with use_reentrant=True (default), calling the model inside a + # torch.no_grad() block triggers a harmless PyTorch warning ("None of the inputs have requires_grad=True"). + # Temporarily disable checkpointing to avoid this warning during inference. + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + if is_peft_model(model) and self.ref_model is None: + # When training a PEFT adapter, how we obtain the reference depends on the setup: + # - New adapter: disabling adapters yields the base model. + # - Re-training an existing adapter: an initial copy is loaded under the name "ref". + model = self.accelerator.unwrap_model(model) + with use_adapter(model, adapter_name="ref" if "ref" in model.peft_config else None): + ref_outputs = self.model(**model_kwargs) + else: + ref_outputs = self.ref_model(**model_kwargs) + + ref_shift_logits = ref_outputs.logits[..., :-1, :] + ref_per_token_logps = selective_log_softmax(ref_shift_logits, shift_labels) + ref_per_token_logps[shift_completion_mask == 0] = 0.0 # mask out non-completion tokens + if self.ld_alpha is None: + ref_logps = ref_per_token_logps.sum(dim=1) # sum over sequence length + else: + # reuse comp_pos/shared_mask/tail_mask computed above (they depend only on completion_mask) + ref_shared_logps = (ref_per_token_logps * shared_mask).sum(dim=1) + ref_tail_logps = (ref_per_token_logps * tail_mask).sum(dim=1) + ref_logps = ref_shared_logps + self.ld_alpha * ref_tail_logps + ref_chosen_logps, ref_rejected_logps = ref_logps.chunk(2, dim=0) # batch is [chosen, rejected] + + # Get the log ratios for the chosen and rejected responses + chosen_logratios = chosen_logps - ref_chosen_logps + rejected_logratios = rejected_logps - ref_rejected_logps + + if self.f_divergence_type == "reverse_kl": # standard DPO + chosen_scores = chosen_logratios + rejected_scores = rejected_logratios + elif self.f_divergence_type == "forward_kl": + # f'(t) = 1 - 1/t -> drop constant -> -exp(-logratio) + chosen_scores = -torch.exp(-chosen_logratios) + rejected_scores = -torch.exp(-rejected_logratios) + elif self.f_divergence_type == "js_divergence": + # f'(t) = log(2t/(t+1)) -> drop log 2 + chosen_scores = F.logsigmoid(chosen_logratios) + rejected_scores = F.logsigmoid(rejected_logratios) + elif self.f_divergence_type == "alpha_divergence": + # alpha-divergence: f'(t) = (t^(α-1) - 1)/(α-1) + if abs(self.f_alpha_divergence_coef - 1.0) < 1e-6: # limit case f'(t) -> log(t), fall back to reverse_kl + chosen_scores = chosen_logratios + rejected_scores = rejected_logratios + else: + coef = 1.0 / (self.f_alpha_divergence_coef - 1.0) + t_chosen = (self.f_alpha_divergence_coef - 1.0) * chosen_logratios + t_rejected = (self.f_alpha_divergence_coef - 1.0) * rejected_logratios + dtype = t_chosen.dtype + # Clamp max so exp(.) stays representable after casting back + clamp_max = {torch.float16: 11.0, torch.bfloat16: 80.0, torch.float32: 80.0}[dtype] + t_chosen_float = torch.clamp(t_chosen.float(), max=clamp_max) + t_rejected_float = torch.clamp(t_rejected.float(), max=clamp_max) + chosen_scores = torch.exp(t_chosen_float).to(dtype) * coef + rejected_scores = torch.exp(t_rejected_float).to(dtype) * coef + else: + raise ValueError(f"Unknown f_divergence_type: {self.f_divergence_type}") + + delta_score = chosen_scores - rejected_scores + + loss = 0.0 + for loss_type, loss_weight in zip(self.loss_types, self.loss_weights, strict=True): + if loss_type == "sigmoid": + per_sequence_loss = -F.logsigmoid(self.beta * delta_score) + + elif loss_type == "hinge": + per_sequence_loss = torch.relu(1 - self.beta * delta_score) + + elif loss_type == "ipo": + # IPO uses sequence-level log-prob differences; in code these are token-summed over the completion, + # which makes the squared loss scale with completion length. We therefore normalize by the number of + # completion tokens (average per token) to make β/loss comparable across variable lengths. This length + # normalization is not explicitly discussed in the IPO paper; we confirmed this choice with the IPO + # authors, and the results reported in the paper correspond to this normalized form. + chosen_mask, rejected_mask = completion_mask.chunk(2, dim=0) + chosen_avg_score = chosen_scores / chosen_mask.sum(dim=1).clamp(min=1.0) + rejected_avg_score = rejected_scores / rejected_mask.sum(dim=1).clamp(min=1.0) + ipo_delta = chosen_avg_score - rejected_avg_score + # (Eq. 17) of the paper where beta is the regularization parameter for the IPO loss, denoted by τ. + per_sequence_loss = (ipo_delta - 1 / (2 * self.beta)) ** 2 + + elif loss_type == "exo_pair": + # Implements EXO-pref from the paper https://huggingface.co/papers/2402.00856, (Eq. 16) + # Minimize KL(p_fθ || p_rh) for K=2; p_fθ = softmax(βπ * (log πθ − log π_ref)) over {chosen, rejected} + # p_rh = [(1−ε), ε]; expanded KL gives the weighted logsigmoid form below + epsilon = torch.tensor(self.label_smoothing, device=device) + qw = torch.sigmoid(self.beta * delta_score) + log_qw = F.logsigmoid(self.beta * delta_score) + log_pw = torch.log1p(-epsilon) + ql = torch.sigmoid(-self.beta * delta_score) + log_ql = F.logsigmoid(-self.beta * delta_score) + log_pl = torch.log(epsilon) + per_sequence_loss = qw * (log_qw - log_pw) + ql * (log_ql - log_pl) + + elif loss_type == "nca_pair": + chosen_rewards = self.beta * chosen_scores + rejected_rewards = self.beta * rejected_scores + per_sequence_loss = ( + -F.logsigmoid(chosen_rewards) + - 0.5 * F.logsigmoid(-chosen_rewards) + - 0.5 * F.logsigmoid(-rejected_rewards) + ) + + elif loss_type == "robust": + clean_loss_term = -(1 - self.label_smoothing) * F.logsigmoid(self.beta * delta_score) + flipped_loss_term = -self.label_smoothing * F.logsigmoid(-self.beta * delta_score) + per_sequence_loss = (clean_loss_term - flipped_loss_term) / (1 - 2 * self.label_smoothing) + + elif loss_type == "bco_pair": + chosen_rewards = self.beta * chosen_scores + rejected_rewards = self.beta * rejected_scores + per_sequence_loss = -F.logsigmoid(chosen_rewards) - F.logsigmoid(-rejected_rewards) + + elif loss_type == "sppo_hard": + # In the paper (https://huggingface.co/papers/2405.00675), SPPO employs a soft probability approach, + # estimated using the PairRM score. The probability calculation is conducted outside of the trainer + # class. The version described here is the hard probability version, where P in Equation (4.7) of + # Algorithm 1 is set to 1 for the winner and 0 for the loser. + winner_margin_error = (chosen_scores - 0.5 / self.beta) ** 2 + loser_margin_error = (rejected_scores + 0.5 / self.beta) ** 2 + per_sequence_loss = winner_margin_error + loser_margin_error + + elif loss_type == "aot": + logratios = chosen_logps - rejected_logps + ref_logratios = ref_chosen_logps - ref_rejected_logps + logratios_sorted, _ = torch.sort(logratios, dim=0) + ref_logratios_sorted, _ = torch.sort(ref_logratios, dim=0) + delta = logratios_sorted - ref_logratios_sorted + per_sequence_loss = ( + -F.logsigmoid(self.beta * delta) * (1 - self.label_smoothing) + - F.logsigmoid(-self.beta * delta) * self.label_smoothing + ) + + elif loss_type == "aot_unpaired": + chosen_logratios_sorted, _ = torch.sort(chosen_logratios, dim=0) + rejected_logratios_sorted, _ = torch.sort(rejected_logratios, dim=0) + delta = chosen_logratios_sorted - rejected_logratios_sorted + per_sequence_loss = ( + -F.logsigmoid(self.beta * delta) * (1 - self.label_smoothing) + - F.logsigmoid(-self.beta * delta) * self.label_smoothing + ) + + elif loss_type == "apo_zero": + # Eqn (7) of the APO paper (https://huggingface.co/papers/2408.06266) + # Use this loss when you believe the chosen outputs are better than your model's default output + # Increase chosen likelihood and decrease rejected likelihood + losses_chosen = 1 - torch.sigmoid(self.beta * chosen_logratios) + losses_rejected = torch.sigmoid(self.beta * rejected_logratios) + per_sequence_loss = losses_chosen + losses_rejected + + elif loss_type == "apo_down": + # Eqn (8) of the APO paper (https://huggingface.co/papers/2408.06266) + # Use this loss when you believe the chosen outputs are worse than your model's default output. + # Decrease chosen likelihood and decrease rejected likelihood more + losses_chosen = torch.sigmoid(self.beta * chosen_logratios) + losses_rejected = 1 - torch.sigmoid(self.beta * delta_score) + per_sequence_loss = losses_chosen + losses_rejected + + elif loss_type == "discopop": + # Eqn (5) of the DiscoPOP paper (https://huggingface.co/papers/2406.08414) + logits = delta_score * self.beta + # Modulate the mixing coefficient based on the log ratio magnitudes + log_ratio_modulation = torch.sigmoid(logits / self.args.discopop_tau) + logistic_component = -F.logsigmoid(logits) + exp_component = torch.exp(-logits) + # Blend between logistic and exponential component based on log ratio modulation + per_sequence_loss = ( + logistic_component * (1 - log_ratio_modulation) + exp_component * log_ratio_modulation + ) + + elif loss_type == "sft": + chosen_logits, _ = shift_logits.chunk(2, dim=0) + chosen_labels, _ = shift_labels.chunk(2, dim=0) + chosen_mask, _ = shift_completion_mask.chunk(2, dim=0) + batch_loss = F.cross_entropy(chosen_logits[chosen_mask.bool()], chosen_labels[chosen_mask.bool()]) + # Implementation convenience: expand the scalar SFT loss to a per-sequence tensor so it matches the + # shape of other losses; only the mean is used, so this is a no-op numerically. + per_sequence_loss = batch_loss.expand(chosen_logits.size(0)) + + elif loss_type == "sigmoid_norm": + chosen_mask, rejected_mask = completion_mask.chunk(2, dim=0) + chosen_avg_score = chosen_scores / chosen_mask.sum(dim=1).clamp(min=1.0) + rejected_avg_score = rejected_scores / rejected_mask.sum(dim=1).clamp(min=1.0) + delta = chosen_avg_score - rejected_avg_score + per_sequence_loss = -F.logsigmoid(self.beta * delta) + + else: + raise ValueError( + f"Unknown loss type: {loss_type}. Should be one of ['sigmoid', 'hinge', 'ipo', 'exo_pair', " + "'nca_pair', 'robust', 'bco_pair', 'sppo_hard', 'aot', 'aot_unpaired', 'apo_zero', 'apo_down', " + "'discopop', 'sft', 'sigmoid_norm']" + ) + + if self.use_weighting: + # Eq (2) of the WPO paper: https://huggingface.co/papers/2406.11827 + completion_lengths = shift_completion_mask.sum(dim=1).clamp_min(1) + with torch.no_grad(): + lse1 = torch.logsumexp(shift_logits, dim=-1) + lse2 = torch.logsumexp(2.0 * shift_logits, dim=-1) + log_denom = lse2 - 2.0 * lse1 + aligned_logps = (per_token_logps - log_denom) * shift_completion_mask + mean_logps = aligned_logps.sum(dim=1) / completion_lengths + weights = torch.exp(mean_logps) + chosen_weights, rejected_weights = weights.chunk(2, dim=0) + per_sequence_loss *= chosen_weights * rejected_weights + + loss += per_sequence_loss.mean() * loss_weight + + # Log the metrics + # Entropy + per_token_entropy = entropy_from_logits(shift_logits.detach()) + mask = shift_completion_mask + entropy_sum = (per_token_entropy * mask).sum() + total_tokens = mask.sum() + + # Gather counts across ranks and weight-average + entropy_sum = self.accelerator.gather_for_metrics(entropy_sum).sum() + total_tokens = self.accelerator.gather_for_metrics(total_tokens).sum() + entropy = (entropy_sum / total_tokens).item() if total_tokens > 0 else 0.0 + self._metrics[mode]["entropy"].append(entropy) + + # Number of tokens + if mode == "train": + num_tokens_in_batch = self.accelerator.gather_for_metrics(inputs["attention_mask"].sum()).sum().item() + self._total_train_tokens += num_tokens_in_batch + self._metrics[mode]["num_tokens"] = [self._total_train_tokens] + + # Average logits for chosen and rejected completions + chosen_logits, rejected_logits = shift_logits.detach().chunk(2, dim=0) + chosen_mask, rejected_mask = shift_completion_mask.chunk(2, dim=0) + total_chosen_logits = chosen_logits[chosen_mask.bool()].mean(-1).sum() + total_chosen_tokens = chosen_mask.sum() + total_rejected_logits = rejected_logits[rejected_mask.bool()].mean(-1).sum() + total_rejected_tokens = rejected_mask.sum() + total_chosen_logits = self.accelerator.gather_for_metrics(total_chosen_logits).sum().item() + total_chosen_tokens = self.accelerator.gather_for_metrics(total_chosen_tokens).sum().item() + total_rejected_logits = self.accelerator.gather_for_metrics(total_rejected_logits).sum().item() + total_rejected_tokens = self.accelerator.gather_for_metrics(total_rejected_tokens).sum().item() + avg_chosen_logits = total_chosen_logits / total_chosen_tokens if total_chosen_tokens > 0 else 0.0 + avg_rejected_logits = total_rejected_logits / total_rejected_tokens if total_rejected_tokens > 0 else 0.0 + self._metrics[mode]["logits/chosen"].append(avg_chosen_logits) + self._metrics[mode]["logits/rejected"].append(avg_rejected_logits) + + # Token accuracy for the chosen completions + predictions = chosen_logits.argmax(dim=-1) + chosen_mask = shift_completion_mask[: len(shift_completion_mask) // 2].bool() + chosen_labels = shift_labels[: len(shift_labels) // 2] + correct_predictions = (predictions == chosen_labels) & chosen_mask + total_tokens = chosen_mask.sum() + correct_tokens = correct_predictions.sum() + correct_tokens = self.accelerator.gather_for_metrics(correct_tokens) + total_tokens = self.accelerator.gather_for_metrics(total_tokens) + total_sum = total_tokens.sum() + accuracy = (correct_tokens.sum() / total_sum).item() if total_sum > 0 else 0.0 + self._metrics[mode]["mean_token_accuracy"].append(accuracy) + + # Rewards for chosen and rejected completions + chosen_rewards = self.beta * chosen_logratios.detach() + rejected_rewards = self.beta * rejected_logratios.detach() + agg_chosen_rewards = self.accelerator.gather(chosen_rewards) + agg_rejected_rewards = self.accelerator.gather(rejected_rewards) + self._metrics[mode]["rewards/chosen"].append(agg_chosen_rewards.mean().item()) + self._metrics[mode]["rewards/rejected"].append(agg_rejected_rewards.mean().item()) + + # Reward accuracy + reward_accuracies = (chosen_rewards > rejected_rewards).float() + agg_reward_accuracies = self.accelerator.gather(reward_accuracies) + self._metrics[mode]["rewards/accuracies"].append(agg_reward_accuracies.mean().item()) + + # Reward margins + margins = chosen_rewards - rejected_rewards + agg_margins = self.accelerator.gather(margins) + self._metrics[mode]["rewards/margins"].append(agg_margins.mean().item()) + + # Average log probabilities for chosen and rejected completions + self._metrics[mode]["logps/chosen"].append(self.accelerator.gather(chosen_logps).mean().item()) + self._metrics[mode]["logps/rejected"].append(self.accelerator.gather(rejected_logps).mean().item()) + + return (loss, outputs) if return_outputs else loss + + def evaluate( + self, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + ignore_keys: list[str] | None = None, + metric_key_prefix: str = "eval", + ) -> dict[str, float]: + # When a dataset is passed directly to `evaluate` (e.g. a held-out test set), preprocess it the same way + # `__init__` does, so that `evaluate` accepts the same dataset types as the trainer. `_prepare_dataset` is + # idempotent: it skips datasets that are already tokenized. A `str` selects a dataset that was already prepared + # at init time, so it's left untouched. + if not self._is_vision_dataset and eval_dataset is not None and not isinstance(eval_dataset, str): + if isinstance(eval_dataset, dict): + eval_dataset = { + key: self._prepare_dataset(dataset, self.processing_class, self.args, key) + for key, dataset in eval_dataset.items() + } + else: + eval_dataset = self._prepare_dataset(eval_dataset, self.processing_class, self.args, "eval") + # With `precompute_ref_log_probs`, `_compute_loss` reads the reference log-probs from the batch, so they + # must be precomputed here as well, mirroring `__init__`. + if self.precompute_ref_logps: + batch_size = self.args.precompute_ref_batch_size or self.args.per_device_eval_batch_size + if isinstance(eval_dataset, dict): + eval_dataset = { + name: self._precompute_ref_logps(dataset, name, batch_size) + for name, dataset in eval_dataset.items() + } + else: + eval_dataset = self._precompute_ref_logps(eval_dataset, "eval", batch_size) + return super().evaluate( + eval_dataset=eval_dataset, ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix + ) + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + try: + if self.use_liger_kernel: + return self._compute_loss_liger(model, inputs, return_outputs) + return self._compute_loss(model, inputs, return_outputs) + except ValueError as e: + if "Image features and image tokens do not match" in str(e) and self.args.max_length is not None: + raise ValueError( + f"The current `max_length` ({self.args.max_length}) is too short and causes image placeholder " + f"tokens in `input_ids` to be truncated, while the corresponding image features remain intact. " + f"Please increase `max_length` or set it to `None` to disable truncation." + ) from e + raise + + # Override training step to add activation offloading context. + def training_step(self, *args, **kwargs): + with self.maybe_activation_offload_context: + return super().training_step(*args, **kwargs) + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} # average the metrics + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + # During eval, Trainer calls prediction_step. If no labels are present in the inputs, it only runs forward and + # returns logits. We override prediction_step to force compute_loss, because this trainer doesn't involve labels. + def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys: list[str] | None = None): + inputs = self._prepare_inputs(inputs) + with torch.no_grad(), self.compute_loss_context_manager(): + if prediction_loss_only: + loss = self.compute_loss(model, inputs, return_outputs=False) # logits aren't materialized with liger + logits, labels = None, None + else: + loss, outputs = self.compute_loss(model, inputs, return_outputs=True) + logits, labels = outputs.logits, inputs["input_ids"] + return loss, logits, labels + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/grpo_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/grpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..5736b6c0ddcd1816a26de16f09dd91f70cb57c00 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/grpo_config.py @@ -0,0 +1,1061 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass, field +from typing import Any + +from .base_config import _BaseConfig + + +@dataclass +class GRPOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`GRPOTrainer`]. + + This class includes only the parameters that are specific to GRPO training. For a full list of training arguments, + please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may + differ from those in [`~transformers.TrainingArguments`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + > Parameters that control the model and reference model + + model_init_kwargs (`str`, `dict[str, Any]`, *optional*): + Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model` + argument of the [`GRPOTrainer`] is provided as a string. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to + [`~transformers.AutoModelForCausalLM.from_pretrained`] and + [`~transformers.AutoProcessor.from_pretrained`]. Also applied to reward-model and reward-tokenizer loads. + router_aux_loss_coef (`float`, *optional*, defaults to `0.001`): + Coefficient of the load-balancing auxiliary loss. Only has an effect when training a Mixture-of-Experts + (MoE) model; for other models it does nothing. The auxiliary loss is added to the training loss with this + weight. Set to `0.0` to disable it. + disable_dropout (`bool`, *optional*, defaults to `False`): + Whether to disable dropout in the model. This is useful for training with a reference model, as it prevents + the model from generating different logprobs for the same input. + cast_lm_head_to_fp32 (`bool`, *optional*, defaults to `False`): + Whether to cast the language modeling head of the policy and reference models to float32. As recommended by + the [ScaleRL](https://huggingface.co/papers/2510.13786) recipe. This flag is only supported when the model + has untied word embedding and language modeling head layers i.e. `tie_word_embeddings` in the model config + is False. + + > Parameters that control the data preprocessing + + remove_unused_columns (`bool`, *optional*, defaults to `False`): + Whether to only keep the column `"prompt"` in the dataset. If you use a custom reward function that + requires any column other than `"prompts"` and `"completions"`, you should keep this to `False`. + num_generations (`int`, *optional*, defaults to `8`): + Number of generations per prompt to sample. The effective batch size (num_processes * per_device_batch_size + * gradient_accumulation_steps) must be evenly divisible by this value. + num_generations_eval (`int` or `None`, *optional*): + Number of generations to sample during evaluation. This allows using fewer generations during evaluation to + save computation. If `None`, uses the value of `num_generations`. + max_completion_length (`int` or `None`, *optional*, defaults to `256`): + Maximum length of the generated completion. + ds3_gather_for_generation (`bool`, *optional*, defaults to `True`): + This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation, + improving generation speed. However, disabling this option allows training models that exceed the VRAM + capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible + with vLLM generation. + shuffle_dataset (`bool`, *optional*, defaults to `True`): + Whether to shuffle the training dataset. + pad_to_multiple_of (`int`, *optional*): + If set, the prompts ids and completions ids will be padded to a multiple of this value. + + > Parameters that control generation + + generation_batch_size (`int`, *optional*): + Batch size to use for generation. If `None`, it defaults to the effective training batch size: + `per_device_train_batch_size * num_processes * steps_per_generation`. In other words, there is one + generation batch processed per optimization step. Mutually exclusive with `steps_per_generation`. + steps_per_generation (`int`, *optional*): + Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`. Mutually exclusive + with `generation_batch_size`. + temperature (`float`, defaults to `1.0`): + Temperature for sampling. The higher the temperature, the more random the completions. + top_p (`float`, *optional*, defaults to `1.0`): + Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to + `1.0` to consider all tokens. + top_k (`int`, *optional*, defaults to `0`): + Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is + disabled and all tokens are considered. + min_p (`float`, *optional*): + Minimum token probability, which will be scaled by the probability of the most likely token. It must be a + value between `0.0` and `1.0`. Typical values are in the `0.01-0.2` range. + generation_kwargs (`dict[str, Any]`, *optional*): + Additional keyword arguments to pass to [`~transformers.GenerationConfig`] (if using transformers) or + `SamplingParams` (if using vLLM) when sampling completions. This can be used to further customize the + generation behavior, such as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that conflict + with the other generation parameters (like `min_p`, `top_p`, etc.), they will override them. + chat_template_kwargs (`dict[str, Any]`, *optional*): + Additional keyword arguments to pass to the `apply_chat_template` function when generating completions. + repetition_penalty (`float`, *optional*, defaults to `1.0`): + Float that penalizes new tokens based on whether they appear in the prompt and the generated text so far. + Values > `1.0` encourage the model to use new tokens, while values < `1.0` encourage the model to repeat + tokens. + cache_implementation (`str`, *optional*): + Implementation of the cache method for faster generation when `use_vllm` is set to `False`. + + > Parameters that control generation acceleration powered by vLLM + + use_vllm (`bool`, *optional*, defaults to `False`): + Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for generation + instead of the default model.generate(). Requires `vllm` to be installed. + vllm_mode (`str`, *optional*, defaults to `"colocate"`): + Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `"server"` or + `"colocate"`. + + - `"server"`: The trainer will send generation requests to a separate vLLM server. Make sure a TRL vLLM + server is running (start with `trl vllm-serve`). + - `"colocate"`: vLLM will run in the same process and share the training GPUs. This avoids the need for a + separate server but may cause resource contention with training. + vllm_model_impl (`str`, *optional*, defaults to `"vllm"`): + Model implementation to use for vLLM. Must be one of `"transformers"` or `"vllm"`. `"transformers"`: Use + the `transformers` backend for model implementation. `"vllm"`: Use the `vllm` library for model + implementation. + vllm_structured_outputs_regex (`str`, *optional*): + Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled. + + > Parameters that control the vLLM server (only used when `vllm_mode` is `"server"`) + + vllm_server_base_url (`str`, *optional*): + Base URL for the vLLM server (e.g., `"http://localhost:8000"`). If provided, `vllm_server_host` and + `vllm_server_port` are ignored. + vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`): + Host of the vLLM server to connect to. Ignored if `vllm_server_base_url` is provided. + vllm_server_port (`int`, *optional*, defaults to `8000`): + Port of the vLLM server to connect to. Ignored if `vllm_server_base_url` is provided. + vllm_server_timeout (`float`, *optional*, defaults to `240.0`): + Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up after the + timeout, a `ConnectionError` is raised. + vllm_group_port (`int`, *optional*, defaults to `51216`): + Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port + is occupied, there is no need to change it. + + > Parameters that control colocated vLLM execution (only used when `vllm_mode` is `"colocate"`) + + vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.3`): + Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set to + `"colocate"`. If you are using `vllm_mode="server"`, this parameter must be passed separately when + launching the vLLM server via the `--vllm_gpu_memory_utilization` flag. + vllm_max_model_length (`int`, *optional*): + Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus + `max_completion_length`; if omitted, it is inferred from the model config. + vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`): + Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set to + `"colocate"`. If you are using `vllm_mode="server"`, this parameter must be passed separately when + launching the vLLM server via the `--vllm_tensor_parallel_size` flag. + vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`): + Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but + waking the engine adds host–device transfer latency. + + > Parameters that control generation acceleration powered by transformers continuous batching + + use_transformers_continuous_batching (`bool`, *optional*, defaults to `False`): + Whether to use transformers' continuous batching engine for generating completions. Requires + `transformers>=5.8.0`. + transformers_continuous_batching_config (`dict`, *optional*): + Keyword arguments for [`~transformers.generation.ContinuousBatchingConfig`]. + + > Parameters that control the training + + beta (`float`, *optional*, defaults to `0.0`): + KL coefficient. If `0.0` (default), the reference model is not loaded, reducing memory usage and improving + training speed. [DeepSeek-R1 incentivizes reasoning in LLMs through reinforcement + learning](https://huggingface.co/papers/2501.12948) use a value of `0.001`. + num_iterations (`int`, *optional*, defaults to `1`): + Number of iterations per batch (denoted as μ in the algorithm). + epsilon (`float`, *optional*, defaults to `0.2`): + Epsilon value for clipping. + delta (`float`, *optional*): + Enables the upper clipping bound in two-sided GRPO loss when set to a float. If `None` (default), standard + GRPO clipping is used. Recommended to be greater than `1 + ε` when enabled. This method is introduced in + the [INTELLECT-2 tech report](https://huggingface.co/papers/2505.07291). + epsilon_high (`float`, *optional*): + Upper-bound epsilon value for clipping. If not specified, it defaults to the same value as the lower-bound + specified in argument `epsilon`. Paper [DAPO](https://huggingface.co/papers/2503.14476) recommends `0.28`. + When used with `loss_type='cispo'`, this corresponds to the ε_max param specified in the [ScaleRL + paper](https://huggingface.co/papers/2510.13786) and the recommended value is `5.0`. + sapo_temperature_neg (`float`, *optional*, defaults to `1.05`): + Temperature for tokens with non-positive advantage scores used in the `sapo` loss function. This parameter + is introduced in the [Soft Adaptive Policy Optimization paper](https://huggingface.co/papers/2511.20347). + sapo_temperature_pos (`float`, *optional*, defaults to `1.0`): + Temperature for tokens with positive advantage scores used in the `sapo` loss function. This parameter is + introduced in the [Soft Adaptive Policy Optimization paper](https://huggingface.co/papers/2511.20347). + vespo_k_pos (`float`, *optional*, defaults to `2.0`): + k parameter for positive advantages, it is the power exponent in the VESPO loss. Controls how aggressively + we down-weight samples with low importance weights (when the importance sampling ratio < 1). + vespo_lambda_pos (`float`, *optional*, defaults to `3.0`): + lambda parameter for positive advantages, it is the decay factor in the VESPO loss. Controls how + aggressively we down-weight samples with high importance weights (when the importance sampling ratio > 1). + vespo_k_neg (`float`, *optional*, defaults to `3.0`): + k parameter for negative advantages, it is the power exponent in the VESPO loss. Controls how aggressively + we down-weight samples with low importance weights (when the importance sampling ratio < 1). + vespo_lambda_neg (`float`, *optional*, defaults to `2.0`): + lambda parameter for negative advantages, it is the exponential decay factor in the VESPO loss. Controls + how aggressively we down-weight samples with high importance weights (when the importance sampling ratio > + 1). + importance_sampling_level (`str`, *optional*, defaults to `"token"`): + Controls whether importance sampling ratios are computed at the `"token"` or `"sequence"` level. `"token"` + keeps the raw per-token log-probability ratios (one weight per token). `"sequence"` averages the + log-probability ratios across valid tokens to produce a single ratio per sequence. The [GSPO + paper](https://huggingface.co/papers/2507.18071) shows that sequence-level sampling often yields more + stable training and better alignment with sequence-level rewards. + reward_weights (`list[float]`, *optional*): + Weights for each reward function. Must match the number of reward functions. If `None`, all rewards are + weighted equally with weight `1.0`. + multi_objective_aggregation (`str`, *optional*, defaults to `"sum_then_normalize"`): + Method to aggregate multiple reward functions. Supported values are: + + - `"sum_then_normalize"` (default): First sums the weighted rewards from each reward function, then applies + reward scaling/normalization as specified by `scale_rewards` (see `scale_rewards` for details). + - `"normalize_then_sum"`: First normalizes/scales each reward function across generations (within each + group), then sums the normalized rewards using the specified weights. The aggregated reward is then + normalized at the batch level when forming advantages. This is the suggested approach from the paper + [GDPO: Group reward-Decoupled Normalization Policy Optimization for Multi-reward RL + Optimization](https://huggingface.co/papers/2601.05242). + scale_rewards (`str` or `bool`, *optional*, defaults to `"group"`): + Specifies the scaling strategy for rewards. Supported values are: + + - `True` or `"group"` (default): rewards are scaled by the standard deviation within each group, ensuring + unit variance within a group. + - `"batch"`: rewards are scaled by the standard deviation across the entire batch, as recommended in the + [PPO Lite paper](https://huggingface.co/papers/2508.08221). + - `False` or `"none"`: no scaling is applied. The [Dr. GRPO + paper](https://huggingface.co/papers/2503.20783) recommends not scaling rewards, as scaling by the + standard deviation introduces a question-level difficulty bias. + loss_type (`str`, *optional*, defaults to `"dapo"`): + Specifies the loss formulation to use. Supported values are: + + - `"grpo"`: Aggregates token-level losses by normalizing over sequence length. Not recommended due to + length bias—this approach tends to prefer shorter completions with positive advantages and longer ones + with negative advantages. + - `"dr_grpo"`: Aggregates token-level losses by normalizing with a global constant. This method was + introduced in the [Dr. GRPO paper](https://huggingface.co/papers/2503.20783) to eliminate length bias. + The value of the constant corresponds to `max_completion_length`. + - `"dapo"` (default): Aggregates token-level losses by normalizing with the number of active token in the + global accumulated batch. This method was introduced in the [DAPO + paper](https://huggingface.co/papers/2503.14476) to eliminate length bias. + - `"bnpo"`: Aggregates token-level losses by normalizing with the number of active token in the local + batch. Note that normalization is performed over the local batch only, so results may slightly vary + depending on the local batch size, despite a constant effective batch size. When using + `per_device_train_batch_size==1`, the loss is equivalent to the GRPO loss. + - `"cispo"`: Clips the importance sampling weights instead of the advantage scaled importance weights. The + clipped weights are then multiplied with the advantages and policy model's log probs. Individual token + losses are aggregated by normalizing with the number of active tokens in the global accumulated batch. + This method was introduced in the [MiniMax-M1 paper](https://huggingface.co/papers/2506.13585). + - `"sapo"`: Soft Adaptive Policy Optimization loss, as introduced in the [Soft Adaptive Policy Optimization + paper](https://huggingface.co/papers/2511.20347). Replaces hard clipping with a smooth, + temperature-controlled gate that adaptively attenuates off-policy updates while preserving useful + learning signals. + - `"luspo"`: Length-Unbiased Sequence Policy Optimization loss. A sequence-level loss that scales each + sequence's loss by its length. This is a modification of GSPO and requires + `importance_sampling_level="sequence"`. Introduced in the [LUSPO + paper](https://huggingface.co/papers/2602.05261). + - `"vespo"`: Variational Sequence-Level Soft Policy Optimization. Replaces hard clipping with a smooth, + asymmetric Gamma weighting function applied directly to sequence-level importance weights. Introduced in + the [VESPO paper](https://huggingface.co/papers/2602.10693). + mask_truncated_completions (`bool`, *optional*, defaults to `False`): + When enabled, truncated completions are excluded from the loss calculation, preventing them from being + incorrectly penalized and introducing noise during training. According to the + [DAPO](https://huggingface.co/papers/2503.14476) paper, this is a good practice for training stability. + sync_ref_model (`bool`, *optional*, defaults to `False`): + Whether to synchronize the reference model with the active model every `ref_model_sync_steps` steps, using + the `ref_model_mixup_alpha` parameter. This synchronization originates from the + [TR-DPO](https://huggingface.co/papers/2404.09656) paper. + ref_model_mixup_alpha (`float`, *optional*, defaults to `0.6`): + α parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which controls the mix + between the current policy and the previous reference policy during updates. The reference policy is + updated according to the equation: `π_ref = α * π_θ + (1 - α) * π_ref_prev`. To use this parameter, you + must set `sync_ref_model=True`. + ref_model_sync_steps (`int`, *optional*, defaults to `512`): + τ parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which determines how + frequently the current policy is synchronized with the reference policy. To use this parameter, you must + set `sync_ref_model=True`. + top_entropy_quantile (`float`, *optional*, defaults to `1.0`): + ρ parameter from [Beyond the 80/20 Rule](https://huggingface.co/papers/2506.01939). Keeps in the policy + loss term only the top-ρ quantile of tokens by entropy of the probability distribution at each sequence + position, improving results. Range: `[0.0-1.0]`. A value of `0.0` masks all but the highest entropy token; + `1.0` keeps all tokens. The paper recommends a value of `0.2`. If used with + `mask_truncated_completions=True`, only tokens from non-truncated completions are considered. + max_tool_calling_iterations (`int`, *optional*): + Maximum number of tool-calling turns when training an agent. If `None`, there is no limit and generation + stops when the model generates a response turn with no tool calls or when the total response length reaches + `max_model_length`. + vllm_importance_sampling_correction (`bool`, *optional*, defaults to `True`): + Whether to apply Importance Sampling (IS) to correct for the mismatch between vLLM completion logprobs and + recomputed training logprobs. If set to `False`, no IS is applied regardless of + `vllm_importance_sampling_mode`. When `True`, the selected mode determines how the IS ratios are computed + and constrained. + vllm_importance_sampling_mode (`str`, *optional*, defaults to `"sequence_mask"`): + Specifies how Importance Sampling is performed when `vllm_importance_sampling_correction=True`. Possible + values are: + + - `"token_truncate"`: Token-level truncated IS (default). Per-token ratios are clipped to + [C_min, C_max]. + - `"token_mask"`: Token-level masked IS. Per-token ratios outside [C_min, C_max] are set to zero. + - `"sequence_truncate"`: Sequence-level truncated IS. A single sequence ratio is clipped to + [C_min, C_max] and applied to all tokens in the sequence. + - `"sequence_mask"`: Sequence-level masked IS. Sequences with ratios outside [C_min, C_max] are masked + out. + vllm_importance_sampling_clip_max (`float`, *optional*, defaults to `3.0`): + Importance sampling upper bound C_max used by `vllm_importance_sampling_mode`. For `*_truncate` modes, + importance ratios are clipped from above at C_max. For `*_mask` modes, ratios larger than C_max are set to + zero. + vllm_importance_sampling_clip_min (`float`, *optional*): + Importance sampling lower bound C_min used by `vllm_importance_sampling_mode`. For `*_truncate` modes, + ratios are clipped from below at C_min. For `*_mask` modes, ratios below C_min are set to zero. To strictly + mask ratios below C_min without upper bound, set `vllm_importance_sampling_clip_max=None`. + off_policy_mask_threshold (`float`, *optional*): + Threshold for off-policy sequence masking. If `None`, off-policy sequence masking is disabled. When set, + sequences with negative advantages and high KL divergence are masked out to stabilize training. This + parameter corresponds to the `delta` threshold in Equation 9 of the [DeepSeek-V3.2 + paper](https://huggingface.co/papers/2512.02556). It expects a positive value (e.g., 0.5). + use_bias_correction_kl (`bool`, *optional*, defaults to `False`): + Whether to use the unbiased KL divergence estimator with importance sampling correction. This corrects the + KL divergence estimate by multiplying it with the importance sampling ratio. This is described in the + [DeepSeek-V3.2 paper](https://huggingface.co/papers/2512.02556). + + > Parameters that control the logging + + log_completions (`bool`, *optional*, defaults to `False`): + Whether to log a sample of (prompt, completion) pairs every `logging_steps` steps. If `rich` is installed, + it prints the sample. If `wandb` and/or `trackio` logging is enabled, it logs it to `wandb` and/or + `trackio`. + num_completions_to_print (`int`, *optional*): + Number of completions to print with `rich`. If `None`, all completions are logged. + log_unique_prompts (`bool`, *optional*, defaults to `False`): + Whether to log unique prompts. If `True`, only unique prompts are logged. If `False`, all prompts are + logged. + log_completions_hub_repo (`str`, *optional*): + Hugging Face Hub repository to save the completions. Should be a complete repository name like + `'username/reponame'` or `'orgname/reponame'`, or just `'reponame'` in which case the repository will be + created in the currently-logged-in Hugging Face user's namespace. Note that this repository will be public + unless you set `hub_private_repo=True` or your organization's default is to create private repositories." + + > Deprecated parameters + + use_transformers_paged: + + + + Parameter `use_transformers_paged` is deprecated and will be removed in version v2.0.0. Use + `use_transformers_continuous_batching` instead. + + + + vllm_importance_sampling_cap: + + + + Parameter `vllm_importance_sampling_cap` is deprecated and will be removed in v2.0.0. Use + `vllm_importance_sampling_clip_max` instead. + + + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `1e-6` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + [ + "model_init_kwargs", + "transformers_continuous_batching_config", + ] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=1e-6, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + # Parameters that control the model and reference model + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `transformers.AutoModelForCausalLM.from_pretrained`, used when the `model` " + "argument of the `GRPOTrainer` is provided as a string." + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. " + "Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoProcessor.from_pretrained`. Also applied to " + "reward-model and reward-tokenizer loads." + }, + ) + router_aux_loss_coef: float = field( + default=0.001, + metadata={ + "help": "Coefficient of the load-balancing auxiliary loss. Only has an effect when training a " + "Mixture-of-Experts (MoE) model; for other models it does nothing. The auxiliary loss is added to the " + "training loss with this weight. Set to `0.0` to disable it." + }, + ) + disable_dropout: bool = field( + default=False, + metadata={ + "help": "Whether to disable dropout in the model. This is useful for training with a reference model, as " + "it prevents the model from generating different logprobs for the same input." + }, + ) + cast_lm_head_to_fp32: bool = field( + default=False, + metadata={ + "help": "Whether to cast the language modeling head of the policy and reference, models to float32." + "As recommended by the [ScaleRL](https://huggingface.co/papers/2510.13786) recipe. This flag is only " + "supported when the model has untied word embedding and language modeling head layers i.e. " + "`tie_word_embeddings` in the model config is False." + }, + ) + + # Parameters that control the data preprocessing + # The default value remove_unused_columns is overwritten from the parent class, because in GRPO we usually rely on + # additional columns to compute the reward + remove_unused_columns: bool | None = field( + default=False, + metadata={ + "help": "Whether to only keep the column 'prompt' in the dataset. If you use a custom reward function " + "that requires any column other than 'prompts' and 'completions', you should keep this to `False`." + }, + ) + num_generations: int | None = field( + default=8, + metadata={ + "help": "Number of generations to sample. The effective batch size (num_processes * per_device_batch_size " + "* gradient_accumulation_steps) must be evenly divisible by this value." + }, + ) + num_generations_eval: int | None = field( + default=None, + metadata={ + "help": "Number of generations to sample during evaluation. This allows using fewer generations during " + "evaluation to save computation. If `None`, uses the value of `num_generations`." + }, + ) + max_completion_length: int | None = field( + default=256, + metadata={"help": "Maximum length of the generated completion."}, + ) + ds3_gather_for_generation: bool = field( + default=True, + metadata={ + "help": "This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for " + "generation, improving generation speed. However, disabling this option allows training models that " + "exceed the VRAM capacity of a single GPU, albeit at the cost of slower generation. Disabling this option " + "is not compatible with vLLM generation." + }, + ) + shuffle_dataset: bool | None = field( + default=True, + metadata={"help": "Whether to shuffle the training dataset."}, + ) + pad_to_multiple_of: int | None = field( + default=None, + metadata={"help": "If set, the prompts ids and completions ids will be padded to a multiple of this value."}, + ) + + # Parameters that control generation + generation_batch_size: int | None = field( + default=None, + metadata={ + "help": "Batch size to use for generation. If `None`, it defaults to the effective training batch size: " + "`per_device_train_batch_size * num_processes * steps_per_generation`." + }, + ) + steps_per_generation: int | None = field( + default=None, + metadata={"help": "Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`."}, + ) + temperature: float = field( + default=1.0, + metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."}, + ) + top_p: float = field( + default=1.0, + metadata={ + "help": "Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. " + "Set to 1.0 to consider all tokens." + }, + ) + top_k: int = field( + default=0, + metadata={ + "help": "Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, " + "top-k-filtering is disabled and all tokens are considered." + }, + ) + min_p: float | None = field( + default=None, + metadata={ + "help": "Minimum token probability, which will be scaled by the probability of the most likely token. It " + "must be a value between 0.0 and 1.0. Typical values are in the 0.01-0.2 range." + }, + ) + generation_kwargs: dict | None = field( + default=None, + metadata={ + "help": "Additional keyword arguments to pass to `GenerationConfig` (if using transformers) or " + "`SamplingParams` (if using vLLM) when sampling completions. This can be used to further customize the " + "generation behavior, such as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that " + "conflict with the other generation parameters (like `min_p`, `top_p`, etc.), they will override them." + }, + ) + chat_template_kwargs: dict | None = field( + default=None, + metadata={ + "help": "Additional keyword arguments to pass to the `apply_chat_template` function when generating " + "completions." + }, + ) + repetition_penalty: float = field( + default=1.0, + metadata={ + "help": "Float that penalizes new tokens based on whether they appear in the prompt and the generated " + "text so far. Values > 1.0 encourage the model to use new tokens, while values < 1.0 encourage the model " + "to repeat tokens." + }, + ) + cache_implementation: str | None = field( + default=None, + metadata={"help": "Implementation of the cache method for faster generation when use_vllm is set to False."}, + ) + + # Parameters that control generation acceleration powered by vLLM + use_vllm: bool = field( + default=False, + metadata={ + "help": "Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for " + "generation instead of the default model.generate(). Requires `vllm` to be installed." + }, + ) + vllm_mode: str = field( + default="colocate", + metadata={ + "help": "Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `'server'` or " + "`'colocate'`. `'server'`: The trainer will send generation requests to a separate vLLM server. Make sure " + "a TRL vLLM server is running (start with `trl vllm-serve`). `'colocate'`: vLLM will run in the same " + "process and share the training GPUs. This avoids the need for a separate server but may cause resource " + "contention with training." + }, + ) + vllm_model_impl: str = field( + default="vllm", + metadata={ + "help": "Model implementation to use for vLLM. Must be one of `transformers` or `vllm`. `transformers`: " + "Use the `transformers` backend for model implementation. `vllm`: Use the `vllm` library for " + "model implementation." + }, + ) + vllm_enable_sleep_mode: bool = field( + default=False, + metadata={ + "help": "Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory " + "usage low, but waking the engine adds host–device transfer latency." + }, + ) + vllm_structured_outputs_regex: str | None = field( + default=None, + metadata={"help": "Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled."}, + ) + + # Parameters that control the vLLM server (only used when `vllm_mode` is `"server"`) + vllm_server_base_url: str | None = field( + default=None, + metadata={ + "help": "Base URL for the vLLM server (e.g., 'http://localhost:8000'). If provided, `vllm_server_host` " + "and `vllm_server_port` are ignored." + }, + ) + vllm_server_host: str = field( + default="0.0.0.0", + metadata={"help": "Host of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."}, + ) + vllm_server_port: int = field( + default=8000, + metadata={"help": "Port of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."}, + ) + vllm_server_timeout: float = field( + default=240.0, + metadata={ + "help": "Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up " + "after the timeout, a `ConnectionError` is raised." + }, + ) + vllm_group_port: int = field( + default=51216, + metadata={ + "help": "Port number for the weight update group. This is used to communicate with the vLLM server. " + "Unless the port is occupied, there is no need to change it.", + }, + ) + + # Parameters that control colocated vLLM execution (only used when `vllm_mode` is `"colocate"`) + vllm_gpu_memory_utilization: float = field( + default=0.3, + metadata={ + "help": "Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set " + "to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when " + "launching the vLLM server via the `--vllm_gpu_memory_utilization` flag." + }, + ) + vllm_max_model_length: int | None = field( + default=None, + metadata={ + "help": "Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus " + "`max_completion_length`; if omitted, it is inferred from the model config." + }, + ) + vllm_tensor_parallel_size: int = field( + default=1, + metadata={ + "help": "Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set " + "to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when " + "launching the vLLM server via the `--vllm_tensor_parallel_size` flag." + }, + ) + + # Parameters that control the training + beta: float = field( + default=0.0, + metadata={ + "help": "KL coefficient. If `0.0` (default), the reference model is not loaded, reducing memory usage and " + "improving training speed. [DeepSeek-R1 incentivizes reasoning in LLMs through reinforcement " + "learning](https://huggingface.co/papers/2501.12948) use a value of `0.001`." + }, + ) + num_iterations: int = field( + default=1, + metadata={"help": "Number of iterations per batch (denoted as μ in the algorithm)."}, + ) + epsilon: float = field( + default=0.2, + metadata={"help": "Epsilon value for clipping."}, + ) + delta: float | None = field( + default=None, + metadata={ + "help": "Enables the upper clipping bound in two-sided GRPO loss when set to a float. If `None` " + "(default), standard GRPO clipping is used. Recommended to be greater than `1 + ε` when enabled. This " + "method is introduced in the [INTELLECT-2 tech report](https://huggingface.co/papers/2505.07291)." + }, + ) + epsilon_high: float | None = field( + default=None, + metadata={ + "help": "Upper-bound epsilon value for clipping. If not specified, it defaults to the same value as the " + "lower-bound specified in argument `epsilon`. Paper DAPO recommends `0.28`. " + "When used with `loss_type='cispo'`, this corresponds to the ε_max param specified in the " + "[ScaleRL paper](https://huggingface.co/papers/2510.13786) and the recommended value is `5.0`." + }, + ) + sapo_temperature_neg: float = field( + default=1.05, + metadata={ + "help": "Temperature for tokens with non-positive advantage scores used in the `sapo` loss function. " + "This parameter is introduced in the [Soft Adaptive Policy Optimization " + "paper](https://huggingface.co/papers/2511.20347)." + }, + ) + sapo_temperature_pos: float = field( + default=1.0, + metadata={ + "help": "Temperature for tokens with positive advantage scores used in the `sapo` loss function. " + "This parameter is introduced in the [Soft Adaptive Policy Optimization " + "paper](https://huggingface.co/papers/2511.20347)." + }, + ) + vespo_k_pos: float = field( + default=2.0, + metadata={ + "help": "k parameter for positive advantages, it is the power exponent in the VESPO loss. Controls how " + "aggressively we down-weight samples with low importance weights (when the importance sampling ratio < 1)." + }, + ) + vespo_lambda_pos: float = field( + default=3.0, + metadata={ + "help": "lambda parameter for positive advantages, it is the decay factor in the VESPO loss. Controls " + "how aggressively we down-weight samples with high importance weights (when the importance sampling ratio " + "> 1)." + }, + ) + vespo_k_neg: float = field( + default=3.0, + metadata={ + "help": "k parameter for negative advantages, it is the power exponent in the VESPO loss. Controls how " + "aggressively we down-weight samples with low importance weights (when the importance sampling ratio < 1)." + }, + ) + vespo_lambda_neg: float = field( + default=2.0, + metadata={ + "help": "lambda parameter for negative advantages, it is the exponential decay factor in the VESPO loss. " + "Controls how aggressively we down-weight samples with high importance weights (when the importance " + "sampling ratio > 1)." + }, + ) + importance_sampling_level: str = field( + default="token", + metadata={ + "help": "Controls whether importance sampling ratios are computed at the `'token'` or `'sequence'` level. " + "`'token'` keeps the raw per-token log-probability ratios (one weight per token). `'sequence'` averages " + "the log-probability ratios across valid tokens to produce a single ratio per sequence. The GSPO paper " + "shows that sequence-level sampling often yields more stable training and better alignment with " + "sequence-level rewards." + }, + ) + reward_weights: list[float] | None = field( + default=None, + metadata={ + "help": "Weights for each reward function. Must match the number of reward functions. If `None`, all " + "rewards are weighted equally with weight `1.0`." + }, + ) + multi_objective_aggregation: str = field( + default="sum_then_normalize", + metadata={ + "help": "Method to aggregate multiple reward functions. Supported values are: " + "`'sum_then_normalize'` (default): First sums the weighted rewards from each reward function, then " + "applies reward scaling/normalization as specified by `scale_rewards` (see `scale_rewards` for details). " + "`'normalize_then_sum'`: First normalizes/scales each reward function across generations (within each " + "group), then sums the normalized rewards using the specified weights. The aggregated reward is then " + "normalized at the batch level when forming advantages. This is the suggested approach from the paper " + "GDPO: Group reward-Decoupled Normalization Policy Optimization for Multi-reward RL Optimization." + }, + ) + scale_rewards: str = field( + default="group", + metadata={ + "help": "Specifies the scaling strategy for rewards. Supported values are: " + "`True` or `group'` (default): rewards are scaled by the standard deviation within each group, ensuring " + "unit variance within a group. " + "`'batch'`: rewards are scaled by the standard deviation across the entire batch, as recommended in the " + "PPO Lite paper. " + "`False` or `'none'`: no scaling is applied. The Dr. GRPO paper recommends not scaling rewards, as " + "scaling by the standard deviation introduces a question-level difficulty bias." + }, + ) + loss_type: str = field( + default="dapo", + metadata={ + "help": "Specifies the loss formulation to use. Supported values are 'grpo', 'dapo', 'bnpo', and " + "'dr_grpo'. " + "'grpo': Aggregates token-level losses by normalizing over sequence length. Not recommended due to length " + "bias—this approach tends to prefer shorter completions with positive advantages and longer ones with " + "negative advantages. " + "'dapo' (default): Aggregates token-level losses by normalizing with the number of active token in the " + "global accumulated batch. This method was introduced in the DAPO paper to eliminate length bias. " + "'dr_grpo': Aggregates token-level losses by normalizing with a global constant. This method was " + "introduced in the Dr. GRPO paper to eliminate length bias. The value of the constant corresponds to " + "`max_completion_length`. " + "'bnpo': Aggregates token-level losses by normalizing with the number of active token in the local batch. " + "Note that normalization is performed over the local batch only, so results may slightly vary depending " + "on the local batch size, despite a constant effective batch size. When using " + "`per_device_train_batch_size==1`, the loss is equivalent to the GRPO loss." + "'cispo': Clips the importance sampling weights instead of the advantage scaled importance weights. " + "The clipped weights are then multiplied with the advantages and policy model's log probs. " + "Individual token losses are aggregated by normalizing with the number of active tokens in " + "the global accumulated batch. This method was introduced in the " + "[MiniMax-M1 paper](https://huggingface.co/papers/2506.13585). " + "'sapo': Soft Adaptive Policy Optimization loss, as introduced in the " + "[Soft Adaptive Policy Optimization paper](https://huggingface.co/papers/2511.20347). " + "Replaces hard clipping with a smooth, temperature-controlled gate that adaptively attenuates " + "off-policy updates while preserving useful learning signals." + "'luspo': Length-Unbiased Sequence Policy Optimization loss. A sequence-level loss that scales each " + "sequence's loss by its length. This is a modification of GSPO and requires " + "`importance_sampling_level='sequence'`. Introduced in the [LUSPO " + "paper](https://huggingface.co/papers/2602.05261)." + "'vespo': Variational Sequence-Level Soft Policy Optimization. Replaces hard clipping with a smooth, " + "asymmetric Gamma weighting function applied directly to sequence-level importance weights. Introduced in " + "the [VESPO paper](https://huggingface.co/papers/2602.10693)." + }, + ) + mask_truncated_completions: bool = field( + default=False, + metadata={ + "help": "When enabled, truncated completions are excluded from the loss calculation, preventing them from " + "being incorrectly penalized and introducing noise during training. According to the DAPO paper, this is " + "a good practice for training stability." + }, + ) + sync_ref_model: bool = field( + default=False, + metadata={ + "help": "Whether to synchronize the reference model with the active model every `ref_model_sync_steps` " + "steps, using the `ref_model_mixup_alpha` parameter." + }, + ) + ref_model_mixup_alpha: float = field( + default=0.6, + metadata={ + "help": "α parameter from the TR-DPO paper, which controls the mix between the current policy and the " + "previous reference policy during updates. The reference policy is updated according to the equation: " + "`π_ref = α * π_θ + (1 - α) * π_ref_prev`. To use this parameter, you must set `sync_ref_model=True`." + }, + ) + ref_model_sync_steps: int = field( + default=512, + metadata={ + "help": "τ parameter from the TR-DPO paper, which determines how frequently the current policy is " + "synchronized with the reference policy. To use this parameter, you must set `sync_ref_model=True`." + }, + ) + top_entropy_quantile: float = field( + default=1.0, + metadata={ + "help": "ρ parameter from Beyond the 80/20 Rule. Keeps in the policy loss term only the top-ρ quantile of " + "tokens by entropy of the probability distribution at each sequence position, improving results. Range: " + "[0.0-1.0]. A value of `0.0` masks all but the highest entropy token; `1.0` keeps all tokens. The paper " + "recommends a value of `0.2`. If used with `mask_truncated_completions=True`, only tokens from " + "non-truncated completions are considered." + }, + ) + max_tool_calling_iterations: int | None = field( + default=None, + metadata={ + "help": "Maximum number of tool-calling turns when training an agent. If `None`, there is no limit and " + "generation stops when the model generates a response turn with no tool calls or when the total " + "response length reaches `max_model_length`." + }, + ) + vllm_importance_sampling_correction: bool = field( + default=True, + metadata={ + "help": "Whether to apply Importance Sampling (IS) to correct for the mismatch between vLLM " + "completion logprobs and recomputed training logprobs. If set to `False`, no IS is applied " + "regardless of `vllm_importance_sampling_mode`. When `True`, the selected mode determines how " + "IS ratios are computed and constrained." + }, + ) + vllm_importance_sampling_mode: str = field( + default="sequence_mask", + metadata={ + "help": "Specifies how Importance Sampling (IS) is performed when " + "vllm_importance_sampling_correction=True. Modes are defined along two orthogonal " + "dimensions: (1) constraint, which determines how to handle ratios outside the bounds " + "[C_min, C_max]—either truncation (clip to range, ρ ← clamp(ρ, C_min, C_max)) or " + "masking (set ratios above C_max or below C_min to zero); and (2) granularity, which determines whether " + "ratios are computed per token or as a single sequence-level ratio applied to all tokens. " + "Supported options are: 'token_truncate', 'token_mask', 'sequence_truncate', and " + "'sequence_mask'." + }, + ) + vllm_importance_sampling_clip_max: float | None = field( + default=3.0, + metadata={ + "help": "Importance sampling upper bound C_max used by `vllm_importance_sampling_mode`. For '*_truncate' " + "modes, ratios are clipped from above at C_max. For '*_mask' modes, ratios larger than C_max are set to " + "zero." + }, + ) + vllm_importance_sampling_clip_min: float | None = field( + default=None, + metadata={ + "help": "Importance sampling lower bound C_min used by `vllm_importance_sampling_mode`. For `*_truncate` " + "modes, ratios are clipped from below at C_min. For `*_mask` modes, ratios below C_min are set to " + "zero. To strictly mask ratios below C_min without upper bound, set `vllm_importance_sampling_clip_max=None`." + }, + ) + off_policy_mask_threshold: float | None = field( + default=None, + metadata={ + "help": "Threshold for off-policy sequence masking. If `None`, off-policy sequence masking is disabled. " + "When set, sequences with negative advantages and high KL divergence are masked out to stabilize " + "training. This parameter corresponds to the `delta` threshold in Equation 9 of the [DeepSeek-V3.2 " + "paper](https://huggingface.co/papers/2512.02556). It expects a positive value (e.g., 0.5)." + }, + ) + use_bias_correction_kl: bool = field( + default=False, + metadata={ + "help": "Whether to use the unbiased KL divergence estimator with importance sampling correction. This " + "corrects the KL divergence estimate by multiplying it with the importance sampling ratio. " + "This is described in the [DeepSeek-V3.2 paper](https://huggingface.co/papers/2512.02556)." + }, + ) + + # Parameters that control the logging + log_completions: bool = field( + default=False, + metadata={ + "help": "Whether to log a sample of (prompt, completion) pairs every `logging_steps` steps. If `rich` is " + "installed, it prints the sample. If `wandb` logging is enabled, it logs it to `wandb`." + }, + ) + num_completions_to_print: int | None = field( + default=None, + metadata={"help": "Number of completions to print with `rich`. If `None`, all completions are logged."}, + ) + log_unique_prompts: bool = field( + default=False, + metadata={ + "help": "Whether to log unique prompts. If `True`, only unique prompts are logged. If `False`, all " + "prompts are logged." + }, + ) + log_completions_hub_repo: str | None = field( + default=None, + metadata={ + "help": "Hugging Face Hub repository to save the completions. Should be a complete repository name like " + "`'username/reponame'` or `'orgname/reponame'`, or just `'reponame'` in which case the repository will " + "be created in the currently-logged-in Hugging Face user's namespace. Note that this repository will be " + "public unless you set `hub_private_repo=True` or your organization's default is to create private " + "repositories." + }, + ) + + # Parameters that control generation acceleration powered by transformers continuous batching + use_transformers_continuous_batching: bool = field( + default=False, + metadata={ + "help": "Whether to use transformers' continuous batching engine for generating completions. Requires " + "transformers>=5.8.0." + }, + ) + transformers_continuous_batching_config: dict | None = field( + default=None, + metadata={"help": "Keyword arguments for `transformers.generation.ContinuousBatchingConfig`."}, + ) + + # Deprecated parameters + use_transformers_paged: bool = field( + default=False, + metadata={"help": "Deprecated. Use `use_transformers_continuous_batching` instead."}, + ) + vllm_importance_sampling_cap: float | None = field( + default=None, + metadata={ + "help": "Deprecated, use `vllm_importance_sampling_clip_max` instead. " + "Importance sampling cap C used by `vllm_importance_sampling_mode`. For '*_truncate' modes, " + "ratios are clipped from above at C. For '*_mask' modes, ratios larger than C are set to zero." + }, + ) + + def __post_init__(self): + super().__post_init__() + + if self.use_transformers_paged: + warnings.warn( + "`use_transformers_paged` is deprecated and will be removed in v2.0.0. Use " + "`use_transformers_continuous_batching` instead.", + FutureWarning, + stacklevel=3, + ) + self.use_transformers_continuous_batching = True + + if self.parallelism_config is not None and ( + self.parallelism_config.cp_enabled or self.parallelism_config.sp_enabled + ): + raise ValueError( + "GRPOTrainer does not support sequence-dim parallelism (`parallelism_config.cp_size > 1` or " + "`parallelism_config.sp_size > 1`) yet. GRPO builds model inputs after generation inside the trainer, " + "so Transformers' context-parallel / Ulysses sequence-parallel input sharding cannot be applied to the " + "raw generation batch. Set both `cp_size=1` and `sp_size=1`, or disable `parallelism_config`." + ) + + self.scale_rewards = {True: "group", False: "none"}.get(self.scale_rewards, self.scale_rewards) + + if self.log_completions_hub_repo is not None and not self.log_completions: + raise ValueError( + "log_completions_hub_repo is set, but log_completions is False. Enable log_completions to upload " + "completions to the Hub, or unset log_completions_hub_repo." + ) + + num_processes = self.world_size + # The current default effective batch size + if self.generation_batch_size is None and self.steps_per_generation is None: + self.steps_per_generation = self.gradient_accumulation_steps + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + elif self.generation_batch_size is not None and self.steps_per_generation is None: + # Just ensure the value is divisible by the global batch size + if self.generation_batch_size % (self.per_device_train_batch_size * num_processes) != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by the global batch size " + f"({self.per_device_train_batch_size * num_processes})." + ) + self.steps_per_generation = self.generation_batch_size // ( + self.per_device_train_batch_size * num_processes + ) + elif self.generation_batch_size is None and self.steps_per_generation is not None: + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + else: + raise ValueError( + "'generation_batch_size' and 'steps_per_generation' can not be both configured at the same time" + ) + + if self.do_eval and self.eval_strategy != "no": + # Determine the number of generations to use for evaluation + num_generations = self.num_generations_eval or self.num_generations + + # Just ensure the value is divisible by the global batch size + if (self.per_device_eval_batch_size * num_processes) % num_generations != 0: + raise ValueError( + f"The global eval batch size ({self.per_device_eval_batch_size} * {num_processes}) must be " + f"divisible by the number of generations used for evaluation ({num_generations})." + ) + + # The generation batch must contain full prompt groups (no partials), so it must be divisible by + # num_generations. + if self.generation_batch_size % self.num_generations != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by num_generations " + f"({self.num_generations})." + ) + + if self.num_generations < 2: + raise ValueError( + "GRPO requires at least 2 generations per prompt to calculate the advantages. You provided " + f"{self.num_generations}, which is less than the minimum required." + ) + + if self.vllm_importance_sampling_cap is not None: + warnings.warn( + "The `vllm_importance_sampling_cap` argument is deprecated and will be removed in v2.0.0. " + "Use `vllm_importance_sampling_clip_max` instead.", + FutureWarning, + stacklevel=2, + ) + self.vllm_importance_sampling_clip_max = self.vllm_importance_sampling_cap + + if ( + self.vllm_importance_sampling_clip_min is not None + and self.vllm_importance_sampling_clip_max is not None + and self.vllm_importance_sampling_clip_min >= self.vllm_importance_sampling_clip_max + ): + raise ValueError( + f"vllm_importance_sampling_clip_min ({self.vllm_importance_sampling_clip_min}) must be less than " + f"vllm_importance_sampling_clip_max ({self.vllm_importance_sampling_clip_max})." + ) + + if ( + self.vllm_importance_sampling_correction + and self.vllm_importance_sampling_mode in ("token_truncate", "sequence_truncate") + and self.vllm_importance_sampling_clip_min is None + and self.vllm_importance_sampling_clip_max is None + ): + raise ValueError( + "At least one of `vllm_importance_sampling_clip_min` or `vllm_importance_sampling_clip_max` " + "must be set when `vllm_importance_sampling_mode` is a `*_truncate` mode." + ) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/grpo_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/grpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..ea4f85d3ae147f313bf6c2a4c41063fabf7b17ad --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/grpo_trainer.py @@ -0,0 +1,2931 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import asyncio +import atexit +import copy +import importlib.resources as pkg_resources +import inspect +import math +import os +import sys +import textwrap +import time +import warnings +from collections import defaultdict, deque +from collections.abc import Callable +from contextlib import nullcontext +from pathlib import Path +from typing import Any, Protocol + +import numpy as np +import pandas as pd +import torch +import torch.utils.data +import transformers +from accelerate.logging import get_logger +from accelerate.utils import gather, gather_object, is_peft_model, set_seed +from datasets import Dataset, IterableDataset +from huggingface_hub import CommitScheduler, DatasetCard, DatasetCardData, create_repo +from packaging.version import Version +from torch import nn +from torch.utils.data import Sampler +from transformers import ( + AutoModelForSequenceClassification, + AutoProcessor, + AutoTokenizer, + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, + is_trackio_available, + is_wandb_available, +) +from transformers.utils import is_peft_available, is_rich_available + +from ..chat_template_utils import ( + add_response_schema, + get_training_chat_template, + is_chat_template_prefix_preserving, + parse_response, + supports_tool_calling, +) +from ..data_utils import apply_chat_template, is_conversational, prepare_multimodal_messages +from ..distributed import DistributedBackend +from ..extras.profiling import profiling_context, profiling_decorator +from ..generation.vllm_generation import VLLMGeneration +from ..import_utils import is_jmespath_available, is_liger_kernel_available +from ..models import prepare_deepspeed, prepare_fsdp, unwrap_model_for_generation +from ..models.utils import _ForwardRedirection, disable_gradient_checkpointing +from .base_trainer import _BaseTrainer +from .callbacks import SyncRefModelCallback +from .grpo_config import GRPOConfig +from .utils import ( + RepeatSampler, + create_model_from_path, + disable_dropout_in_model, + entropy_from_logits, + get_config_model_id, + identity, + nanmax, + nanmin, + nanstd, + pad, + print_prompt_completions_sample, + selective_log_softmax, + shuffle_sequence_dict, + shutdown_event_loop_in_daemon, + split_pixel_values_by_grid, + split_tensor_dict, + start_event_loop_in_daemon, + unsplit_pixel_values_by_grid, + use_adapter, +) + + +if is_peft_available(): + import peft + from peft import LoraConfig, PeftConfig, PeftModel, get_peft_model + from peft.tuners.tuners_utils import BaseTunerLayer + +if is_liger_kernel_available(): + from liger_kernel.chunked_loss import LigerFusedLinearGRPOLoss + + +if is_wandb_available(): + import wandb + +if is_trackio_available(): + import trackio + + +logger = get_logger(__name__) + +# A reward function can be a string, interpreted as a model ID and loaded as a pretrained model, a pretrained model, or +# a callable that returns a list of floats (the rewards). The callable receives prompts, completions, and additional +# arguments from the trainer (refer to the trainer's source for details). To ensure forward compatibility, it should +# accept **kwargs. +RewardFunc = str | PreTrainedModel | Callable[..., list[float | None]] + +# What we call a rollout function is a callable that takes prompts (list) and the trainer instance as parameters and +# returns a dict of generation results. Those results must include "prompt_ids", "completion_ids", and "logprobs" +# fields. Any extra fields (per-completion) are forwarded to the reward functions. +RolloutFunc = Callable[[list[str], "GRPOTrainer"], dict[str, Any]] + + +class _SupportsReset(Protocol): + def reset(self, **kwargs) -> str | None: ... + + +EnvironmentFactory = Callable[[], _SupportsReset] + + +class GRPOTrainer(_BaseTrainer): + """ + Trainer for the Group Relative Policy Optimization (GRPO) method. This algorithm was initially proposed in the + paper [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language + Models](https://huggingface.co/papers/2402.03300). + + Example: + + ```python + >>> from trl import GRPOTrainer + >>> from trl.rewards import accuracy_reward + >>> from datasets import load_dataset + + >>> dataset = load_dataset("trl-lib/DeepMath-103K", split="train") + + >>> trainer = GRPOTrainer( + ... model="Qwen/Qwen2.5-0.5B-Instruct", + ... reward_funcs=accuracy_reward, + ... train_dataset=dataset, + ... ) + >>> trainer.train() + ``` + + Args: + model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]): + Model to be trained. Can be either: + + - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using `.from_pretrained` (where `` is derived from the model + config) with the keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported. + - A [`~peft.PeftModel`] object. Only causal language models are supported. + reward_funcs (`RewardFunc | list[RewardFunc]`): + Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward + functions with the prompts and completions and sum the rewards. Can be either: + + - A single reward function, such as: + - A string: The *model ID* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using [`~transformers.AutoModelForSequenceClassification.from_pretrained`] with `num_labels=1` and the + keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object: Only sequence classification models are supported. + - A custom reward function: The function is provided with the prompts and the generated completions, + plus any additional columns in the dataset. It should return a list of rewards. Custom reward + functions can be either synchronous or asynchronous and can also return `None` when the reward is + not applicable to those samples. This is useful for multi-task training where different reward + functions apply to different types of samples. When a reward function returns `None` for a sample, + that reward function is excluded from the reward calculation for that sample. For more details, see + [Using a custom reward + function](#using-a-custom-reward-function). + + The trainer's state is also passed to the reward function. The trainer's state is an instance of + [`~transformers.TrainerState`] and can be accessed by accessing the `trainer_state` argument to the + reward function's signature. + - A list of reward functions, where each item can independently be any of the above types. Mixing different + types within the list (e.g., a string model ID and a custom reward function) is allowed. + args ([`GRPOConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset is + ignored. The format of the samples can be either: + + - [Standard](dataset_formats#standard): Each sample contains plain text. + - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role + and content). + eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`): + Dataset to use for evaluation. It must meet the same requirements as `train_dataset`. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. The padding side must be set to "left". If `None`, the + processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A + padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token, + `tokenizer.eos_token` will be used as the default. + reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*): + Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either: + + - A single processing class: Used when `reward_funcs` contains only one reward function. + - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`. + If set to `None`, or if an element of the list corresponding to a [`~transformers.PreTrainedModel`] is + `None`, the tokenizer for the model is automatically loaded using + [`~transformers.AutoTokenizer.from_pretrained`]. For elements in `reward_funcs` that are custom reward + functions (not [`~transformers.PreTrainedModel`]), the corresponding entries in `reward_processing_classes` + are ignored. + callbacks (list of [`~transformers.TrainerCallback`], *optional*): + List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed + in [here](https://huggingface.co/docs/transformers/main_classes/callback). + + If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`] + method. + optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`): + A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your + model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration used to wrap the model. If `None`, the model is not wrapped. + tools (list of `Callable`, *optional*): + A list of callable tool functions (sync or async) that the model can invoke during generation. Each tool + should be a standard Python function with properly type-hinted arguments and return values, and a + Google-style docstring describing its purpose, arguments, and return value. For more details, see: + https://huggingface.co/docs/transformers/en/chat_extras#passing-tools. The model uses the function's name, + type hints, and docstring to determine how to call it. Ensure that the model's chat template supports tool + use and that it has been fine-tuned for tool calling. + rollout_func (`RolloutFunc`, *optional*): + Function to use for generating completions. It receives the list of prompts allocated to the current + process and the trainer instance. It must return a dict with `"prompt_ids"`, `"completion_ids"`, and + `"logprobs"` fields, and can optionally return `"logprob_token_ids"` (same shape as `"logprobs"`). Any + other fields are forwarded to the reward functions. The function receives the raw per-process prompt slice + with no duplication; it is responsible for returning the correct number of completions per prompt (see + `num_generations` / `num_generations_eval` on the trainer). This feature is experimental and may change or + be removed at any time without prior notice. + environment_factory (`EnvironmentFactory`, *optional*): + A callable that creates and returns an environment instance. The environment class should define methods + that can be invoked as tools during generation. Each method should comply with the same requirements as the + `tools` described above. If `environment_factory` is provided, an instance of the environment is created + for each generation in the batch, allowing for parallel and independent interactions. The environment must + also implement a callable `reset` method that can be used to reset state between generations. The `reset` + method should return either `None` or a string: when it returns a string, that string is appended to the + last user message before generation. This feature is experimental and may change or be removed at any time + without prior notice. + """ + + _tag_names = ["trl", "grpo"] + _name = "GRPO" + _paper = { + "title": "DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models", + "id": "2402.03300", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{shao2024deepseekmath, + title = {{DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models}}, + author = {Zhihong Shao and Peiyi Wang and Qihao Zhu and Runxin Xu and Junxiao Song and Mingchuan Zhang and Y. K. Li and Y. Wu and Daya Guo}, + year = 2024, + eprint = {arXiv:2402.03300}, + }"""), + } + + def __init__( + self, + model: "str | PreTrainedModel | PeftModel", + reward_funcs: RewardFunc | list[RewardFunc], + args: GRPOConfig | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + peft_config: "PeftConfig | None" = None, + tools: list[Callable] | None = None, + rollout_func: RolloutFunc | None = None, + environment_factory: EnvironmentFactory | None = None, + ): + # Args + if args is None: + model_name = model if isinstance(model, str) else get_config_model_id(model.config) + model_name = model_name.split("/")[-1] + args = GRPOConfig(f"{model_name}-GRPO") + + # Model + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + model = create_model_from_path(model, **model_init_kwargs) + else: + if args.model_init_kwargs is not None: + logger.warning( + "You passed `model_init_kwargs` to the `GRPOConfig`, but your model is already instantiated. " + "The `model_init_kwargs` will be ignored." + ) + # Non-quantized models do not have the `is_loaded_in_{8,4}bit` attributes, whereas quantized models do + _is_quantized_model = getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False) + + # Some models (SmolVLM/Idefics3) don't support `logits_to_keep` argument and error out if we pass it + # Inspect the forward method before we wrap the model with PEFT + self.model_kwarg_keys = ( + inspect.signature(model.forward).parameters.keys() + if not hasattr(model, "get_base_model") + else inspect.signature(model.get_base_model().forward).parameters.keys() + ) + + # Processing class + if processing_class is None: + processing_class = AutoProcessor.from_pretrained( + get_config_model_id(model.config), + truncation_side="left", + padding_side="left", + trust_remote_code=args.trust_remote_code, + ) + + if args.use_transformers_continuous_batching and isinstance(processing_class, ProcessorMixin): + raise ValueError( + "`use_transformers_continuous_batching` does not support multimodal models. Use `use_vllm` instead." + ) + + # Handle pad token for processors or tokenizers + if isinstance(processing_class, ProcessorMixin): + self._tokenizer = processing_class.tokenizer + self._is_vlm = True + elif isinstance(processing_class, PreTrainedTokenizerBase): + self._tokenizer = processing_class + self._is_vlm = False + else: + raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`") + + if self._tokenizer.pad_token is None: + self._tokenizer.pad_token = self._tokenizer.eos_token + + # Resolve vision placeholder token IDs once. Used by the forward pass to rebuild mm_token_type_ids + # when tool responses inject images into the completion (see _generate forward_kwargs block). + self._image_pad_token_id = None + self._video_pad_token_id = None + if self._is_vlm: + for candidate in ("<|image_pad|>", "<|image|>"): + tid = self._tokenizer.convert_tokens_to_ids(candidate) + if tid != self._tokenizer.unk_token_id: + self._image_pad_token_id = tid + break + tid = self._tokenizer.convert_tokens_to_ids("<|video_pad|>") + if tid != self._tokenizer.unk_token_id: + self._video_pad_token_id = tid + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge " + "and unload the existing adapter, save the resulting base model, and then pass that base model along " + "with the new `peft_config` to the trainer." + ) + # Create PEFT model + # ZeRO-3 + PEFT for non-quantized models: + # - PEFT's default autocast_adapter_dtype=True upcasts LoRA adapter params to fp32 even when the base model is bf16. + # - ZeRO-3's _allgather_params_coalesced allocates output buffers using the dtype of the first persistent parameter, + # so mixed-dtype persistent_parameters (bf16 base + fp32 LoRA) cause a TypeError on the first optimizer step. + # - Passing autocast_adapter_dtype=False keeps adapter params in the base model dtype (bf16), fixing the mismatch. + # - This is safe: the fp32 upcast is a QLoRA-specific concern (low-bit quantized base models), not needed for + # non-quantized bf16 training. + # - See: + # - TRL issue: https://github.com/huggingface/trl/issues/6089 + # - Upstream issue: https://github.com/deepspeedai/DeepSpeed/issues/8072 + # - autocast_adapter_dtype was introduced in PEFT 0.12.0; before, no upcast existed: no need to pass the kwarg + get_peft_model_kwargs = {} + if ( + args.deepspeed_plugin is not None + and args.deepspeed_plugin.zero_stage == 3 + and not _is_quantized_model + and Version(peft.__version__) >= Version("0.12.0") + ): + get_peft_model_kwargs["autocast_adapter_dtype"] = False + model = get_peft_model(model, peft_config, **get_peft_model_kwargs) + + elif is_peft_model(model) and args.beta != 0.0: + # If the model is a PEFT model with a pretrained adapter, we need to create a "ref" adapter that is a copy + # of the "default" adapter, so that we can use it as the reference model during GRPO training. PEFT only + # supports one adapter per model when the LoRA config uses `target_parameters` (see peft#3340), so in that + # case we skip the "ref" adapter and compute the reference log probs with adapters disabled, i.e. with the + # base model. + default_config = model.peft_config["default"] + if isinstance(default_config, LoraConfig) and default_config.target_parameters: + logger.warning( + "PEFT can't add a frozen reference adapter alongside one that uses `target_parameters` " + "(peft#3340), so the reference log probs are computed from the base model (adapters disabled). " + "If you wrapped the model only to apply LoRA, pass a `peft_config` to the trainer instead; if you " + "wrapped it deliberately (pretrained adapter or custom init), note that the base model matches " + "your adapter only when it's freshly zero-initialized. If it is, this warning is safe to ignore." + ) + else: + model.add_adapter("ref", default_config) + for name, param in model.named_parameters(): + if ".default." in name: + ref_name = name.replace(".default.", ".ref.") + ref_param = model.get_parameter(ref_name) + ref_param.data.copy_(param.data) + + # When using gradient checkpointing with PEFT, we need to enable input gradients. transformers.Trainer normally + # handles this, but a bug currently prevents it; see https://github.com/huggingface/transformers/issues/42489 + if is_peft_model(model) and args.gradient_checkpointing: + model.enable_input_require_grads() + + # When using QLoRA, the PEFT adapter weights are converted to bf16 to follow the recommendations from the + # original paper (see https://huggingface.co/papers/2305.14314, paragraph 3). Normally, this can be done by + # passing `autocast_adapter_dtype=False` to `get_peft_model`, but this option is not yet supported for + # quantized models. See: https://github.com/huggingface/peft/issues/2889 + if _is_quantized_model: + for param in model.parameters(): + if param.requires_grad: + param.data = param.data.to(torch.bfloat16) + + # Reward functions + if not isinstance(reward_funcs, list): + reward_funcs = [reward_funcs] + self.reward_func_names = [] + for i, reward_func in enumerate(reward_funcs): + if isinstance(reward_func, str): + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + reward_funcs[i] = AutoModelForSequenceClassification.from_pretrained( + reward_func, num_labels=1, **model_init_kwargs + ) + if isinstance(reward_funcs[i], nn.Module): # Use Module over PretrainedModel for compat w/ compiled models + self.reward_func_names.append(get_config_model_id(reward_funcs[i].config).split("/")[-1]) + else: + self.reward_func_names.append(reward_funcs[i].__name__) + self.reward_funcs = reward_funcs + + # Reward weights + if args.reward_weights is not None: + if len(args.reward_weights) != len(reward_funcs): + raise ValueError( + f"Number of reward weights ({len(args.reward_weights)}) must match number of reward " + f"functions ({len(reward_funcs)})" + ) + self.reward_weights = torch.tensor(args.reward_weights, dtype=torch.float32) + else: + self.reward_weights = torch.ones(len(reward_funcs), dtype=torch.float32) + + # Reward processing class + if reward_processing_classes is None: + reward_processing_classes = [None] * len(reward_funcs) + elif not isinstance(reward_processing_classes, list): + reward_processing_classes = [reward_processing_classes] + if len(reward_processing_classes) != len(reward_funcs): + raise ValueError( + f"The number of reward processing classes ({len(reward_processing_classes)}) must match the number of " + f"reward functions ({len(reward_funcs)})." + ) + + for i, (reward_processing_class, reward_func) in enumerate( + zip(reward_processing_classes, reward_funcs, strict=True) + ): + if isinstance(reward_func, PreTrainedModel): + if reward_processing_class is None: + reward_processing_class = AutoTokenizer.from_pretrained( + get_config_model_id(reward_func.config), trust_remote_code=args.trust_remote_code + ) + if reward_processing_class.pad_token_id is None: + reward_processing_class.pad_token = reward_processing_class.eos_token + # The reward model computes the reward for the latest non-padded token in the input sequence. + # So it's important to set the pad token ID to the padding token ID of the processing class. + reward_func.config.pad_token_id = reward_processing_class.pad_token_id + reward_processing_classes[i] = reward_processing_class + + self.reward_processing_classes = reward_processing_classes + + # Rollout function + if rollout_func is not None and os.environ.get("TRL_EXPERIMENTAL_SILENCE", "0") != "1": + warnings.warn( + "You are using 'rollout_func', which is an experimental feature. This API may change or be removed at " + "any time without prior notice. Silence this warning by setting environment variable " + "TRL_EXPERIMENTAL_SILENCE=1.", + UserWarning, + stacklevel=2, + ) + self.rollout_func = rollout_func + if environment_factory is not None and os.environ.get("TRL_EXPERIMENTAL_SILENCE", "0") != "1": + warnings.warn( + "You are using 'environment_factory', which is an experimental feature. This API may change or be " + "removed at any time without prior notice. Silence this warning by setting environment variable " + "TRL_EXPERIMENTAL_SILENCE=1.", + UserWarning, + stacklevel=2, + ) + + # Tools + if tools: + if not Version(transformers.__version__) >= Version("5.0.0"): + raise ImportError( + "Using tools with GRPOTrainer requires transformers version 5.0.0 or higher. Please upgrade " + "transformers with `pip install --upgrade transformers` to use this feature." + ) + if environment_factory: + if not Version(transformers.__version__) >= Version("5.2.0"): + raise ImportError( + "Using `environment_factory` with GRPOTrainer requires transformers version 5.2.0 or higher. " + "Please install transformers from the main branch with `pip install " + "git+https://github.com/huggingface/transformers.git@main` to use this feature." + ) + if tools or environment_factory: + if not is_jmespath_available(): + raise ImportError( + "Using tools with GRPOTrainer requires the jmespath library for response parsing. Please install " + "it with `pip install jmespath` to use this feature." + ) + if not supports_tool_calling(processing_class): + raise ValueError( + "The provided chat template does not support tool calling. The template must be able to render a " + "full tool-calling conversation (user -> assistant with tool_calls -> tool)." + ) + + # Create the environments and extract their methods to be used as tools. We create one environment per rollout + generation_batch_size = args.per_device_train_batch_size * args.steps_per_generation + if environment_factory is not None: + self.environments = [environment_factory() for _ in range(generation_batch_size)] + environment_methods = [[] for _ in range(generation_batch_size)] + for i, environment in enumerate(self.environments): + has_reset = False + for name, member in inspect.getmembers(environment, predicate=inspect.ismethod): + if name == "reset": + has_reset = True + elif not name.startswith("_"): + environment_methods[i].append(member) + if not has_reset: + raise ValueError( + "Each environment instance returned by `environment_factory` must define a callable `reset` " + ) + else: + self.environments = None + + tools = tools or [] + self._sync_tool_dicts = [{} for _ in range(generation_batch_size)] + self._async_tool_dicts = [{} for _ in range(generation_batch_size)] + for i in range(generation_batch_size): + for tool in tools + (environment_methods[i] if self.environments is not None else []): + if inspect.iscoroutinefunction(tool): + self._async_tool_dicts[i][tool.__name__] = tool + else: + self._sync_tool_dicts[i][tool.__name__] = tool + + self.tools = tools + (environment_methods[0] if self.environments is not None else []) + + # Check for async functions to start an event loop on a daemon thread + self._has_async_funcs = any(inspect.iscoroutinefunction(func) for func in self.reward_funcs + self.tools) + + if self._has_async_funcs: + self.async_loop_thread, self.async_loop, self.async_loop_ready_event = start_event_loop_in_daemon( + name="GRPOTrainer-AsyncLoop" + ) + # wait until the event loop is running in the daemon thread + self.async_loop_ready_event.wait() + atexit.register(shutdown_event_loop_in_daemon, self.async_loop_thread, self.async_loop) + + # At the time of initial implementation, most tokenizers do not have built-in support for response schemas. + # While waiting for broader adoption, we provide this utility function to manually set the response schema for + # known chat templates. `response_schema` lives on the (inner) tokenizer, since `parse_response` is a tokenizer + # method that reads `self.response_schema`. + if self.tools and getattr(self._tokenizer, "response_schema", None) is None: + processing_class = add_response_schema(processing_class) + # In multi-turn training, the chat template *must* be prefix-preserving. If the tokenizer's original template + # isn't, we replace it at initialization with a training-safe, prefix-preserving template. + if self.tools and not is_chat_template_prefix_preserving(processing_class): + self.chat_template = get_training_chat_template(processing_class) + else: + self.chat_template = None + + # Training arguments + self.max_completion_length = args.max_completion_length # = |o_i| in the GRPO paper + self.num_generations = args.num_generations # = G in the GRPO paper + self.max_tool_calling_iterations = args.max_tool_calling_iterations or sys.maxsize + self.num_generations_eval = args.num_generations_eval or self.num_generations + self.chat_template_kwargs = args.chat_template_kwargs or {} + self.temperature = args.temperature + self.top_p = args.top_p + self.top_k = args.top_k + self.min_p = args.min_p + self.repetition_penalty = args.repetition_penalty + self.use_transformers_continuous_batching = args.use_transformers_continuous_batching + if self.use_transformers_continuous_batching: + if not Version(transformers.__version__) >= Version("5.8.0"): + raise ImportError( + "Using `use_transformers_continuous_batching` requires transformers>=5.8.0. " + "Please upgrade with `pip install --upgrade transformers`." + ) + from transformers.generation import ContinuousBatchingConfig + + cb_kwargs = dict(args.transformers_continuous_batching_config or {}) + # The transformers default (0.9) leaves almost no VRAM for the training backward pass; + # use a training-aware default unless the user has set it explicitly. + cb_kwargs.setdefault("max_memory_percent", 0.5) + self.continuous_batching_config = ContinuousBatchingConfig(**cb_kwargs) + else: + self.continuous_batching_config = None + self.pad_to_multiple_of = args.pad_to_multiple_of + self.use_vllm = args.use_vllm + self.vllm_mode = args.vllm_mode + self.vllm_gpu_memory_utilization = args.vllm_gpu_memory_utilization # only applies to colocation mode + self.vllm_tensor_parallel_size = args.vllm_tensor_parallel_size # only applies to colocation mode + self.vllm_importance_sampling_correction = args.vllm_importance_sampling_correction + self.vllm_importance_sampling_mode = args.vllm_importance_sampling_mode + self.vllm_importance_sampling_clip_max = args.vllm_importance_sampling_clip_max + self.vllm_importance_sampling_clip_min = args.vllm_importance_sampling_clip_min + self.use_liger_kernel = args.use_liger_kernel + self.loss_type = args.loss_type + self.multi_objective_aggregation = args.multi_objective_aggregation + + # MoE load-balancing auxiliary loss, applied to Mixture-of-Experts models (no effect otherwise) + text_config = model.config.get_text_config() + is_moe = getattr(text_config, "output_router_logits", None) is not None + self.aux_loss_enabled = is_moe and args.router_aux_loss_coef != 0.0 + self.router_aux_loss_coef = args.router_aux_loss_coef + self.scale_rewards = args.scale_rewards + self.importance_sampling_level = args.importance_sampling_level + self.off_policy_mask_threshold = args.off_policy_mask_threshold + if self.use_liger_kernel and self.off_policy_mask_threshold is not None: + raise ValueError("Liger kernel does not support off-policy sequence masking yet.") + if self.use_liger_kernel and is_peft_model(model): + # The Liger fused GRPO loss multiplies the hidden states by `lm_head.weight` directly. When the LM head is + # targeted by a PEFT adapter (`"lm_head"` in `target_modules`), `lm_head.weight` is the frozen base weight + # and the trainable adapter parameters live in separate submodules that Liger never sees. The head adapter + # would silently receive no gradient, so the model trains as if `lm_head` were frozen. Fail loudly rather + # than train a silently-frozen head. + output_embeddings = model.get_output_embeddings() + if isinstance(output_embeddings, BaseTunerLayer): + raise ValueError( + "`use_liger_kernel=True` is incompatible with applying a PEFT adapter to `lm_head`. The Liger " + "fused GRPO loss reads `lm_head.weight` directly, so the adapter on the head is ignored and never " + "trained. Either remove `'lm_head'` from your `target_modules`, or set `use_liger_kernel=False`." + ) + self.mask_truncated_completions = args.mask_truncated_completions + self.top_entropy_quantile = args.top_entropy_quantile + if self.use_liger_kernel and self.top_entropy_quantile < 1.0: + raise NotImplementedError( + "Liger Kernels don't currently support masking token positions based on entropy." + ) + if self.use_liger_kernel and self.importance_sampling_level not in ("token", "sequence"): + raise ValueError( + f"Unknown importance sampling level: {self.importance_sampling_level}. " + "Possible values are 'token' and 'sequence'." + ) + + # Datasets + self.shuffle_dataset = args.shuffle_dataset + + if train_dataset is None: + raise ValueError("`train_dataset` is required") + elif ( + isinstance(train_dataset, IterableDataset) + or isinstance(eval_dataset, IterableDataset) + or ( + isinstance(eval_dataset, dict) and any(isinstance(ds, IterableDataset) for ds in eval_dataset.values()) + ) + ): + # See https://github.com/huggingface/trl/issues/3213 + raise NotImplementedError( + "Iterable datasets are not yet supported in GRPOTrainer. Please use a standard dataset instead." + ) + + if args.loss_type == "luspo" and args.importance_sampling_level != "sequence": + logger.warning( + "When using `'luspo'` loss, `importance_sampling_level` should be set to `'sequence'` to mirror the " + "paper's setup." + ) + + if args.loss_type == "vespo" and args.importance_sampling_level != "token": + logger.warning( + "VESPO computes sequence-level importance weights internally. `importance_sampling_level` should be " + "set to `'token'` (the default)." + ) + + if args.importance_sampling_level == "sequence" and args.loss_type in ["bnpo", "dr_grpo", "dapo", "cispo"]: + logger.warning( + f"When using `importance_sampling_level='sequence'`, the `'{args.loss_type}'` loss sums per-token " + "contributions, which effectively weights each sequence by its completion length instead of " + "optimizing the per-sequence objective. To reproduce the GSPO paper's setup, set `loss_type='grpo'` " + "(see https://huggingface.co/docs/trl/main/en/paper_index#group-sequence-policy-optimization)." + ) + + if self.loss_type == "vespo" and self.use_vllm and self.vllm_importance_sampling_correction: + if self.vllm_importance_sampling_mode not in ["token_truncate", "token_mask"]: + raise ValueError( + f"VESPO loss requires `vllm_importance_sampling_mode` to be either 'token_truncate' or " + f"'token_mask'. Got: {self.vllm_importance_sampling_mode}." + ) + + # Multi-step + self.num_iterations = args.num_iterations # = 𝜇 in the GRPO paper + self.epsilon_low = args.epsilon + self.epsilon_high = args.epsilon_high if args.epsilon_high is not None else args.epsilon + # Tracks the number of iterations (forward + backward passes), including those within a grad accum cycle + self._step = 0 + # Buffer the batch to reuse generated outputs across multiple updates. For more details, see + # `_get_train_sampler` and `_prepare_inputs`. + self._buffered_inputs = None + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=identity, # No data collation is needed in GRPO + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + callbacks=callbacks, + optimizers=optimizers, + # In Trainer, `training_step` scales the loss by `gradient_accumulation_steps` only if `compute_loss_func` + # is None. For DAPO, loss scaling instead depends on the total number of completions tokens across the + # global accumulated batch. To control scaling ourselves, we must disable Trainer’s built-in scaling. The + # simplest (though a bit hacky) way is to set `compute_loss_func` to any non-None value, which bypasses + # that behavior without rewriting `training_step`. + compute_loss_func="non-None value to disable scaling", + ) + + # Reference model + self.beta = args.beta + if self.beta == 0.0: + # If beta is 0.0, the reference model is not needed + self.ref_model = None + elif is_peft_model(model): + # If PEFT is used, the reference model is not needed since the adapter can be disabled + # to revert to the initial model. + self.ref_model = None + else: + # For deepspeed, fsdp or non-distributed models, create a reference model from scratch + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if self.args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + self.ref_model = create_model_from_path(get_config_model_id(self.model.config), **model_init_kwargs) + + # Disable dropout in the models + if args.disable_dropout: + disable_dropout_in_model(model) + if self.ref_model is not None: + disable_dropout_in_model(self.ref_model) + + # Cast LM Head To FP32 + if args.cast_lm_head_to_fp32: + + def _cast_lm_head_to_fp32(target_model: PreTrainedModel): + """Cast lm_head to fp32 while preserving embedding output dtype if tied.""" + + def cast_inputs_to_fp32(module, inputs): + # Preserve other positional args and kwargs untouched + if not inputs: + return inputs + return (inputs[0].to(torch.float32),) + inputs[1:] + + original_dtype_local = target_model.lm_head.weight.dtype + target_model.lm_head = target_model.lm_head.float() + target_model.lm_head.register_forward_pre_hook(cast_inputs_to_fp32) + + if target_model.config.tie_word_embeddings: + + def cast_outputs_to_original_dtype(module, args, output): + return output.to(original_dtype_local) + + # Only cast activations; weights are now fp32 (intentional for numerical stability of logits) + target_model.model.embed_tokens.register_forward_hook(cast_outputs_to_original_dtype) + + _cast_lm_head_to_fp32(model) + if self.ref_model is not None: + _cast_lm_head_to_fp32(self.ref_model) + + # Liger loss + if self.use_liger_kernel: + if not is_liger_kernel_available(): + raise ImportError( + "Liger is required to use `use_liger_kernel` as the GRPO loss. Run `pip install liger-kernel`." + ) + # redirect the model.module forward to the model forward to ensure pre-forward hooks are called + self._forward_redirection = _ForwardRedirection() + + self.liger_grpo_loss = LigerFusedLinearGRPOLoss( + beta=self.beta, + epsilon_low=self.epsilon_low, + epsilon_high=self.epsilon_high, + temperature=self.temperature, + use_ref_model=self.beta != 0.0, + loss_type=self.loss_type, + max_completion_length=self.max_completion_length, + importance_sampling_level=self.importance_sampling_level, + delta=args.delta, + use_bias_correction_kl=args.use_bias_correction_kl, + sapo_temperature_pos=args.sapo_temperature_pos, + sapo_temperature_neg=args.sapo_temperature_neg, + vespo_k_pos=args.vespo_k_pos, + vespo_lambda_pos=args.vespo_lambda_pos, + vespo_k_neg=args.vespo_k_neg, + vespo_lambda_neg=args.vespo_lambda_neg, + ) + + # Initialize the metrics + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + self._total_train_tokens = 0 + self._current_train_step_time = 0.0 + self.log_completions = args.log_completions + self.log_unique_prompts = args.log_unique_prompts + self.num_completions_to_print = args.num_completions_to_print + # Keep logs sized to the generation batch to record only outputs from the latest model update. + self._logs = { + "images": deque(maxlen=args.generation_batch_size), + "prompt": deque(maxlen=args.generation_batch_size), + "completion": deque(maxlen=args.generation_batch_size), + "rewards": defaultdict(lambda: deque(maxlen=args.generation_batch_size)), + "advantages": deque(maxlen=args.generation_batch_size), + "extra": defaultdict(lambda: deque(maxlen=args.generation_batch_size)), + } + # Buffers for user-logged data from reward functions, flushed after gathering + self._pending_extra_logs = defaultdict(list) + self._pending_metrics = defaultdict(list) + + # Ensure each process receives a unique seed to prevent duplicate completions when generating with + # transformers if num_generations exceeds per_device_train_batch_size. We could skip it if we use vLLM, but + # it's safer to set it in all cases. + set_seed(args.seed, device_specific=True) + + if self.use_vllm: + # Initialize vLLM generation backend + self.vllm_generation = VLLMGeneration( + model=self.model, + accelerator=self.accelerator, + processing_class=self.processing_class, + # vLLM configuration + mode=args.vllm_mode, + structured_outputs_regex=args.vllm_structured_outputs_regex, + # Server mode configuration + server_base_url=args.vllm_server_base_url, + server_host=args.vllm_server_host, + server_port=args.vllm_server_port, + group_port=args.vllm_group_port, + server_timeout=args.vllm_server_timeout, + # Colocate mode configuration + tensor_parallel_size=args.vllm_tensor_parallel_size, + gpu_memory_utilization=args.vllm_gpu_memory_utilization, + max_model_length=args.vllm_max_model_length, + max_num_seqs=args.per_device_train_batch_size + * args.vllm_tensor_parallel_size + * args.steps_per_generation, + enable_sleep_mode=args.vllm_enable_sleep_mode, + model_impl=args.vllm_model_impl, + # Generation configuration + repetition_penalty=self.repetition_penalty, + temperature=self.temperature, + top_p=self.top_p, + top_k=self.top_k, + min_p=self.min_p, + max_completion_length=self.max_completion_length, + logprobs=0, # we only need the generated token logprobs for the importance sampling correction + generation_kwargs=args.generation_kwargs, + ) + self._last_loaded_step = -1 # tag to avoid useless loading during grad accumulation + else: + generation_kwargs = { + "max_new_tokens": self.max_completion_length, + "do_sample": True, + "pad_token_id": self._tokenizer.pad_token_id, + "bos_token_id": self._tokenizer.bos_token_id, + "eos_token_id": self._tokenizer.eos_token_id, + "temperature": self.temperature, + "top_p": self.top_p, + "top_k": self.top_k, + "min_p": self.min_p, + "repetition_penalty": self.repetition_penalty, + "cache_implementation": args.cache_implementation, + } + if args.generation_kwargs is not None: + generation_kwargs.update(args.generation_kwargs) + self.generation_config = GenerationConfig(**generation_kwargs, disable_compile=True) + # Keep training-specific generation kwargs to overwrite model's original generation config + self.generation_kwargs = generation_kwargs + + # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the + # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set + # self.model_accepts_loss_kwargs to False to enable scaling. + self.model_accepts_loss_kwargs = False + self._dist = DistributedBackend(self.accelerator) + + # Add tags to the model + self.model.add_model_tags(self._tag_names) + + if self.ref_model is not None: + if self.is_deepspeed_enabled: + self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator) + elif self.is_fsdp_enabled: + self.ref_model = prepare_fsdp(self.ref_model, self.accelerator) + else: + self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True) + + if args.sync_ref_model: + if self.beta == 0.0: + raise ValueError( + "You passed `sync_ref_model=True` while `beta=0.0`, which means the reference model is not used " + "during training. Consequently, GRPOTrainer does not create a `ref_model` instance, and there is " + "nothing to synchronize. Please set `sync_ref_model=False`, or set `beta` to a non-zero value." + ) + if is_peft_model(model): + raise NotImplementedError( + "You passed `sync_ref_model=True` while using a PEFT model, which is currently not supported. " + "With PEFT, GRPOTrainer does not keep a separate reference model in memory; instead, it recovers " + "reference behavior by temporarily disabling the adapter. As a result, there is no standalone " + "`ref_model` instance to synchronize. Use `sync_ref_model=False`, or opt for full fine-tuning if " + "you need a synced reference model. If you need `sync_ref_model` to work with PEFT, please open a " + "feature request at https://github.com/huggingface/trl/issues." + ) + self.add_callback(SyncRefModelCallback(ref_model=self.ref_model, accelerator=self.accelerator)) + + for i, reward_func in enumerate(self.reward_funcs): + if isinstance(reward_func, PreTrainedModel): + if self.is_deepspeed_enabled: + self.reward_funcs[i] = prepare_deepspeed(reward_func, self.accelerator) + else: + # set device placement to True to make `prepare_model` move `reward_func` to device when using fsdp + self.reward_funcs[i] = self.accelerator.prepare_model( + reward_func, evaluation_mode=True, device_placement=True + ) + + if self.accelerator.is_main_process and self.log_completions: + os.makedirs(os.path.join(self.args.output_dir, "completions"), exist_ok=True) + if self.args.log_completions_hub_repo is not None: + repo_id = self.args.log_completions_hub_repo + create_repo(repo_id, private=self.args.hub_private_repo, repo_type="dataset", exist_ok=True) + template_path = pkg_resources.files("trl").joinpath("templates/completions_dataset_card.md") + card_data = DatasetCardData( + pretty_name="TRL Completion logs", + tags=["trl", "trl-logs", "completions"], + ) + card = DatasetCard.from_template( + card_data=card_data, + template_path=str(template_path), + repo_id=repo_id, + hub_model_id=self.args.hub_model_id, + ) + card.push_to_hub(repo_id) + self.commit_scheduler = CommitScheduler( + repo_id=repo_id, + repo_type="dataset", + folder_path=f"{self.args.output_dir}/completions", + every=2, # minutes + allow_patterns=["*.parquet"], + ) + + def _set_signature_columns_if_needed(self): + # If `self.args.remove_unused_columns` is True, non-signature columns are removed. + # By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids" + # and "attention_mask"). In GRPOTrainer, we preprocess data, so using the model's signature columns doesn't + # work. Instead, we set them to the columns expected by the `training_step` method, hence the override. + if self._signature_columns is None: + self._signature_columns = ["prompt", "image", "images"] + + # This method overrides `Trainer.get_train_dataloader` to support our custom batching strategy. + # Instead of returning a standard per-step batch (i.e., `per_device_batch_size), our dataloader loads an + # *generation* batch (i.e., `per_device_batch_size × steps_per_generation`). This allows us to generate completions + # once every steps_per_generation step—rather than once per accumulation step—which is significantly more + # efficient. The only change from the original implementation is multiplying the batch size by + # `steps_per_generation`. Thus, `_prepare_inputs` is called with this *generation* batch, and it handles the + # splitting internally. + # Maintenance note: This method is a copy-paste of the original `Trainer.get_train_dataloader` with only one line + # modification. + def get_train_dataloader(self): + return self._get_dataloader( + dataset=self.train_dataset, + description="Training", + batch_size=self._train_batch_size * self.args.steps_per_generation, # < this is the change + sampler_fn=self._get_train_sampler, + is_training=True, + ) + + def _get_train_sampler(self, dataset: Dataset | None = None) -> Sampler: + # Returns a sampler that + # 1. ensures each prompt is repeated across multiple processes. This guarantees that identical prompts are + # distributed to different GPUs, allowing rewards to be computed and normalized correctly within each prompt + # group. Using the same seed across processes ensures consistent prompt assignment, preventing discrepancies + # in group formation. + # 2. repeats the batch multiple times to allow reusing generations across multiple updates. Refer to + # _prepare_inputs to see how the generations are stored and reused. + + # In the following figure, the values are the prompt indices. Each row shows the per-step batch + # returned by `_prepare_inputs`; rows within a `steps_per_generation` block are slices of the same + # generated batch. When `num_iterations > 1`, that block is reused for multiple optimization passes + # before regenerating. + # + # | GPU 0 | GPU 1 | + # + # global_step step <-───> num_generations=2 + # <-───────> per_device_train_batch_size=3 + # grad_accum ▲ ▲ 0 0 0 0 1 1 2 2 <- Generate for the first `steps_per_generation` (prompts 0 to 11); store the completions; use the first slice to compute the loss + # =2 ▼ | 0 1 3 3 4 4 5 5 <- Take the stored generations and use the second slice to compute the loss + # | + # | 1 2 6 6 7 7 8 8 <- Take the stored generations and use the third slice to compute the loss + # steps_per_gen=4 ▼ 1 3 9 9 10 10 11 11 <- Take the stored generations and use the fourth slice to compute the loss + # + # 2 4 12 12 13 13 14 14 <- Generate for the second `steps_per_generation` (prompts 12 to 23); store the completions; use the first slice to compute the loss + # 2 5 15 15 16 16 17 17 <- Take the stored generations and use the second slice to compute the loss + # ... + if dataset is None: + dataset = self.train_dataset + return RepeatSampler( + data_source=dataset, + mini_repeat_count=self.num_generations, + batch_size=self.args.generation_batch_size // self.num_generations, + repeat_count=self.num_iterations * self.args.steps_per_generation, + shuffle=self.shuffle_dataset, + seed=self.args.seed, + ) + + def _get_eval_sampler(self, eval_dataset) -> Sampler: + # See _get_train_sampler for an explanation of the sampler. + return RepeatSampler( + data_source=eval_dataset, + mini_repeat_count=self.num_generations_eval, + seed=self.args.seed, + ) + + @profiling_decorator + def _get_last_hidden_state( + self, + unwrapped_model, + input_ids, + attention_mask, + logits_to_keep, + pixel_values=None, + image_grid_thw=None, + pixel_attention_mask=None, + spatial_shapes=None, + image_sizes=None, + image_position_ids=None, + ): + if is_peft_model(unwrapped_model): + unwrapped_model = unwrapped_model.base_model.model + + # Build model inputs - check if the model supports logits_to_keep (some models and VLMs don't) + model_inputs = {"input_ids": input_ids, "attention_mask": attention_mask} + + # For Qwen models: + if image_grid_thw is not None and pixel_values is not None: + model_inputs["image_grid_thw"] = image_grid_thw + # For Gemma, SmolVLM2, LLaVa-Next etc.: + if pixel_values is not None: + model_inputs["pixel_values"] = pixel_values + # For SmolVLM2 + if pixel_attention_mask is not None: + model_inputs["pixel_attention_mask"] = pixel_attention_mask + # For LFM2-VL + if spatial_shapes is not None: + model_inputs["spatial_shapes"] = spatial_shapes + # For LLaVa-Next + if image_sizes is not None: + model_inputs["image_sizes"] = image_sizes + if image_position_ids is not None: + model_inputs["image_position_ids"] = image_position_ids + + # Only add logits_to_keep if the model supports it + if "logits_to_keep" in self.model_kwarg_keys: + # We add 1 to `logits_to_keep` because the last logits of the sequence is later excluded + model_inputs["logits_to_keep"] = logits_to_keep + 1 + + model_inputs["use_cache"] = False # only used in generation; set False to suppress warnings + + # `base_model` gives the backbone model (skipping `lm_head`) — text decoder for LMs, multimodal wrapper for + # VLMs (so vision-token injection runs before the text decoder). `get_decoder()` won't do: on VLMs it + # returns just the text stack and feeds image-placeholder IDs through it. + # Pre-5.0 transformers VLMs set `base_model_prefix = ""` so `base_model is self` (re-runs `lm_head`). + # Fall back to `.model` there. + if self._is_vlm and Version(transformers.__version__) < Version("5.0.0"): + backbone = unwrapped_model.model + else: + backbone = unwrapped_model.base_model + last_hidden_state = backbone(**model_inputs).last_hidden_state + # Exclude the last value: it corresponds to the next token pred + last_hidden_state = last_hidden_state[:, :-1, :] # (B, L-1, H) + # Only keep the last logits_to_keep. For model that support logits_to_keep, this is a no-op. + last_hidden_state = last_hidden_state[:, -logits_to_keep:, :] # (B, logits_to_keep, H) + return last_hidden_state + + def get_high_entropy_mask(self, entropies: torch.Tensor, mask: torch.Tensor, threshold: float) -> torch.Tensor: + """ + Returns a binary mask identifying tokens whose entropy exceeds a given quantile threshold. + + Args: + entropies (`torch.Tensor`): + Tensor of shape (batch_size, seq_len) with per-token entropy values. + mask (`torch.Tensor`): + Binary mask of the same shape as `entropies`, where `1` indicates valid tokens and `0` padding. + threshold (`float`): + Quantile threshold between `0.0` and `1.0` to select high-entropy tokens. + + Returns: + `torch.Tensor`: + Boolean mask of shape (batch_size, seq_len), where `True` indicates tokens with entropy >= threshold + and `False` otherwise. + """ + local = entropies[mask.bool()].float() + + # Use a negative pad_value as a sentinel because entropy values are always >= 0. + # This guarantees that the sentinel cannot collide with any real entropy value. + pad_value = -1e9 + + # Pad across processes so that every rank has the same tensor length + padded = self.accelerator.pad_across_processes(local, dim=0, pad_index=pad_value) + gathered = self.accelerator.gather(padded) + + # Drop sentinel values (safe because no entropy can be negative) + gathered = gathered[gathered != pad_value] + + if gathered.numel() == 0: + return torch.zeros_like(entropies, dtype=torch.bool) + + entropy_threshold = torch.quantile(gathered, threshold) + masked_entropies = entropies * mask.float() + entropy_mask = masked_entropies >= entropy_threshold + return entropy_mask & mask.bool() # ensure padding tokens are always masked out + + @profiling_decorator + def _get_per_token_logps_and_entropies( + self, + model, + input_ids, + attention_mask, + logits_to_keep, + batch_size=None, + compute_entropy=False, + compute_aux_loss=False, + pixel_values=None, + image_grid_thw=None, + num_images=None, + pixel_attention_mask=None, + spatial_shapes=None, + num_tiles=None, + image_sizes=None, + token_type_ids=None, + mm_token_type_ids=None, + image_position_ids=None, + ) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]: + """Compute log-probs, (optionally) entropies, and (optionally) the MoE load-balancing aux loss.""" + batch_size = batch_size or input_ids.size(0) # Chunk inputs into smaller batches to reduce memory peak + all_logps = [] + all_entropies = [] + all_aux_losses = [] + for start in range(0, input_ids.size(0), batch_size): + input_ids_batch = input_ids[start : start + batch_size] + attention_mask_batch = attention_mask[start : start + batch_size] + + # Build model inputs + model_inputs = {"input_ids": input_ids_batch, "attention_mask": attention_mask_batch} + if image_grid_thw is not None and pixel_values is not None: + rows_per_image = image_grid_thw.prod(dim=-1) + rows_per_sample = torch.split(rows_per_image, num_images) + rows_per_sample = torch.stack([s.sum() for s in rows_per_sample]) + cum_rows = torch.cat([torch.tensor([0], device=rows_per_sample.device), rows_per_sample.cumsum(0)]) + row_start, row_end = cum_rows[start].item(), cum_rows[start + batch_size].item() + model_inputs["pixel_values"] = pixel_values[row_start:row_end] + cum_imgs = torch.tensor([0] + num_images).cumsum(0) + img_start, img_end = cum_imgs[start], cum_imgs[start + batch_size] + model_inputs["image_grid_thw"] = image_grid_thw[img_start:img_end] + elif image_position_ids is not None and pixel_values is not None: + cum_imgs = torch.tensor([0] + num_images).cumsum(0) + img_start, img_end = cum_imgs[start], cum_imgs[start + batch_size] + model_inputs["pixel_values"] = pixel_values[img_start:img_end] + model_inputs["image_position_ids"] = image_position_ids[img_start:img_end] + elif spatial_shapes is not None and pixel_values is not None: + # LFM2-VL tensors are tile-indexed. + cum_tiles = torch.tensor([0] + num_tiles).cumsum(0) + tile_start, tile_end = cum_tiles[start], cum_tiles[start + batch_size] + model_inputs["pixel_values"] = pixel_values[tile_start:tile_end] + model_inputs["pixel_attention_mask"] = pixel_attention_mask[tile_start:tile_end] + model_inputs["spatial_shapes"] = spatial_shapes[tile_start:tile_end] + elif pixel_values is not None: + model_inputs["pixel_values"] = pixel_values[start : start + batch_size] + if pixel_attention_mask is not None and spatial_shapes is None: + model_inputs["pixel_attention_mask"] = pixel_attention_mask[start : start + batch_size] + if image_sizes is not None: + model_inputs["image_sizes"] = image_sizes[start : start + batch_size] + if token_type_ids is not None: + model_inputs["token_type_ids"] = token_type_ids[start : start + batch_size] + if mm_token_type_ids is not None: + model_inputs["mm_token_type_ids"] = mm_token_type_ids[start : start + batch_size] + + # Only add logits_to_keep if the model supports it + if "logits_to_keep" in self.model_kwarg_keys: + # We add 1 to `logits_to_keep` because the last logits of the sequence is later excluded + model_inputs["logits_to_keep"] = logits_to_keep + 1 + + model_inputs["use_cache"] = False # only used in generation; set False to suppress warnings + + # MoE models: request router logits so the model returns `outputs.aux_loss`. VLM wrappers honor this only + # as a forward kwarg (not from the model config), so it must be passed here. + if compute_aux_loss: + model_inputs["output_router_logits"] = True + + outputs = model(**model_inputs) + logits = outputs.logits + # Exclude the last value: it corresponds to the next token pred + logits = logits[:, :-1, :] # (B, L-1, H) + # Only keep the last logits_to_keep. For model that support logits_to_keep, this is a no-op. + logits = logits[:, -logits_to_keep:, :] # (B, logits_to_keep, H) + # Divide logits by sampling temperature. + # See https://huggingface.co/blog/the_n_implementation_details_of_rlhf_with_ppo#policy-training-implementation-details + logits.div_(self.temperature) + completion_ids = input_ids_batch[:, -logits_to_keep:] + logps = selective_log_softmax(logits, completion_ids) # compute logprobs + all_logps.append(logps) + + if compute_entropy: + with torch.no_grad(): + entropies = entropy_from_logits(logits) + all_entropies.append(entropies) + + if compute_aux_loss: + all_aux_losses.append(outputs.aux_loss) + + logps = torch.cat(all_logps, dim=0) + entropies = torch.cat(all_entropies, dim=0) if compute_entropy else None + aux_loss = torch.stack(all_aux_losses).mean() if compute_aux_loss else None + return logps, entropies, aux_loss + + def training_step(self, model, inputs, num_items_in_batch): + time_before = time.perf_counter() + output = super().training_step(model, inputs, num_items_in_batch) + self._step += 1 + time_after = time.perf_counter() + self._current_train_step_time += time_after - time_before + if self._step % self.current_gradient_accumulation_steps == 0: + self._metrics["train"]["step_time"].append(self._current_train_step_time) + self._current_train_step_time = 0.0 + return output + + @profiling_decorator + def _prepare_inputs(self, generation_batch: dict[str, torch.Tensor | Any]) -> dict[str, torch.Tensor | Any]: + # Prepares inputs for model training/evaluation by managing completion generation and batch handling. + # During training: + # - Receives the local generation batch (Per-GPU batch size × steps per generation) + # from the modified training dataloader instead of the standard local batch + # - Generates completions once for the entire generation batch and splits it into batches of size + # `per_device_train_batch_size` + # - Buffers these completions and returns the appropriate slice for the current accumulation step + # - Optimizes by regenerating completions only periodically (every steps_per_generation * num_iterations) + # During evaluation: + # - The input is treated as a standard local batch (no accumulation, no multiple iterations) + # - Completions are generated for each batch without buffering or reuse + # Returns a single local batch in both cases. + + mode = "train" if self.model.training else "eval" + if mode == "train": + generate_every = self.args.steps_per_generation * self.num_iterations + if self._step % generate_every == 0 or self._buffered_inputs is None: + # self._buffered_inputs=None can occur when resuming from a checkpoint + generation_batch = self._generate_and_score_completions(generation_batch) + generation_batch = split_pixel_values_by_grid(generation_batch) + generation_batch = shuffle_sequence_dict(generation_batch) + generation_batches = split_tensor_dict(generation_batch, self.args.steps_per_generation) + self._buffered_inputs = [unsplit_pixel_values_by_grid(batch) for batch in generation_batches] + inputs = self._buffered_inputs[self._step % self.args.steps_per_generation] + else: + # In evaluation, there is neither batch grouping for generation, nor multiple iterations, hence + # local generation batch == local eval batch + inputs = self._generate_and_score_completions(generation_batch) + return inputs + + def _log_completion_extra(self, column: str, values: list): + """ + Log extra columns to the completions table. Called from reward functions via the `log_extra` kwarg. + + Args: + column (`str`): + Name of the column to add. + values (`list`): + Values for the column, one per sample in the batch. + """ + self._pending_extra_logs[column].extend(values) + + def _log_metric(self, name: str, value: float): + """ + Log a scalar metric from a reward function. Called via the `log_metric` kwarg. Values are averaged over each + logging step and reported alongside built-in metrics like `kl` and `entropy`. + + Args: + name (`str`): + Name of the metric. + value (`float`): + Scalar value for this batch. + """ + self._pending_metrics[name].append(value) + + @profiling_decorator + def _calculate_rewards(self, inputs, prompts, completions, completion_ids_list): + device = self.accelerator.device + rewards_per_func = torch.zeros(len(prompts), len(self.reward_funcs), device=device) + + # Repeat all input columns (but "prompt", "completion", and "completion_ids") to match the num of generations + keys = [key for key in inputs[0] if key not in ["prompt", "completion", "completion_ids"]] + reward_kwargs = {key: [example[key] for example in inputs] for key in keys} + + # This allows for dynamic reward shaping based on training progress. + reward_kwargs["trainer_state"] = self.state + + # Allow reward functions to log extra columns to the completions table. + reward_kwargs["log_extra"] = self._log_completion_extra + + # Allow reward functions to log additional scalar metrics. + reward_kwargs["log_metric"] = self._log_metric + + async_funcs_info = [] # async custom functions for asyncio.gather + + for i, (reward_func, reward_processing_class, reward_func_name) in enumerate( + zip(self.reward_funcs, self.reward_processing_classes, self.reward_func_names, strict=True) + ): + if isinstance(reward_func, nn.Module): # Module (no PretrainedModel) for compat with compiled models + with profiling_context(self, reward_func_name): + if is_conversational(inputs[0]): + messages = [{"messages": p + c} for p, c in zip(prompts, completions, strict=True)] + texts = [ + apply_chat_template(x, reward_processing_class, **self.chat_template_kwargs)["text"] + for x in messages + ] + else: + texts = [p + c for p, c in zip(prompts, completions, strict=True)] + reward_inputs = reward_processing_class( + text=texts, return_tensors="pt", padding=True, padding_side="right", add_special_tokens=False + ) + reward_inputs = super()._prepare_inputs(reward_inputs) + with torch.inference_mode(): + rewards_per_func[:, i] = reward_func(**reward_inputs).logits[:, 0] # Shape (B*G,) + elif inspect.iscoroutinefunction(reward_func): # Separate async reward funcs to run them in parallel later + async_funcs_info.append((i, reward_func, reward_func_name)) + else: + # Run synchronous reward function + with profiling_context(self, reward_func_name): + if self.environments is not None: + reward_kwargs["environments"] = self.environments + output_reward_func = reward_func( + prompts=prompts, completions=completions, completion_ids=completion_ids_list, **reward_kwargs + ) + # Convert None values to NaN + output_reward_func = [reward if reward is not None else torch.nan for reward in output_reward_func] + rewards_per_func[:, i] = torch.tensor(output_reward_func, dtype=torch.float32, device=device) + + # Execute async custom functions in parallel using asyncio.gather + if async_funcs_info: + + async def _invoke_async(index, func, func_name): + with profiling_context(self, func_name): + output = await func( + prompts=prompts, completions=completions, completion_ids=completion_ids_list, **reward_kwargs + ) + output = [r if r is not None else torch.nan for r in output] + return index, output + + async def _run_async_funcs(): + coros = [_invoke_async(i, func, func_name) for (i, func, func_name) in async_funcs_info] + return await asyncio.gather(*coros) + + async_results = asyncio.run_coroutine_threadsafe(_run_async_funcs(), self.async_loop).result() + for idx, output_reward_func in async_results: + rewards_per_func[:, idx] = torch.tensor(output_reward_func, dtype=torch.float32, device=device) + + # If all reward functions return None for a given row, issue a detailed warning + if torch.isnan(rewards_per_func).all(dim=1).any(): + nan_row_idx = torch.isnan(rewards_per_func).all(dim=1).nonzero(as_tuple=True)[0][0] + row_reward_kwargs = { + key: value[nan_row_idx] + for key, value in reward_kwargs.items() + if key not in ("trainer_state", "log_extra", "log_metric") + } + row_reward_kwargs["prompt"] = prompts[nan_row_idx] + row_reward_kwargs["completion"] = completions[nan_row_idx] + logger.warning( + f"All reward functions returned None for the following kwargs:\n{row_reward_kwargs}\n" + "Please ensure that at least one reward function returns a valid reward." + ) + + # Gather the reward per function: this part is crucial, because the rewards are normalized per group and the + # completions may be distributed across processes + rewards_per_func = gather(rewards_per_func) + return rewards_per_func + + def _tokenize_prompts(self, prompts: list): + """Tokenize prompts and extract images/multimodal fields for generation.""" + if is_conversational({"prompt": prompts[0]}): + # Normalize string content to content blocks for VLM processors that don't handle plain strings. + if self._is_vlm: + prompts = [prepare_multimodal_messages(prompt) for prompt in prompts] + + # Extract images from messages for VLM support + images = [] + has_images = False + for prompt in prompts: + prompt_images = [] + for message in prompt: + if isinstance(message["content"], list): + for part in message["content"]: + if part["type"] == "image": + prompt_images.append(part["image"]) + has_images = True + images.append(prompt_images if prompt_images else None) + images = images if has_images else None + + # Workaround for a bug in transformers 5.3.0 where some processors (e.g. Qwen2.5-VL) crash on + # batched unpadded input (transformers#44514). + # Fixed in transformers 5.4.0 (transformers#44563). + needs_padding_workaround = Version("5.3.0") <= Version(transformers.__version__) < Version("5.4.0") + tokenized = self.processing_class.apply_chat_template( + conversation=prompts, + tools=self.tools or None, # `or None`: Llama bug: it renders tool boilerplate for tools=[] + chat_template=self.chat_template, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + **({"padding": True} if needs_padding_workaround else {}), + **self.chat_template_kwargs, + ) + if needs_padding_workaround: + # Unpad input_ids: remove padding tokens using attention_mask to get per-sequence lists + prompt_ids = [ + [tok for tok, m in zip(ids, mask, strict=True) if m] + for ids, mask in zip(tokenized["input_ids"], tokenized["attention_mask"], strict=True) + ] + else: + prompt_ids = tokenized["input_ids"] + # For VLMs, the processor returns extra multimodal fields (pixel_values, image_grid_thw, etc.) + multimodal_fields = {k: v for k, v in tokenized.items() if k not in ("input_ids", "attention_mask")} + else: + prompt_ids = self.processing_class(text=prompts)["input_ids"] + images = None + multimodal_fields = {} + return prompt_ids, images, multimodal_fields + + def _generate_single_turn(self, prompt_ids, images, multimodal_fields): + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + + # Generate completions using either vLLM or regular generation + if self.use_vllm: + # Sync weights if training step changed + if self.state.global_step != self._last_loaded_step: + with profiling_context(self, "sync_weights"): + self.vllm_generation.sync_weights() + self._last_loaded_step = self.state.global_step + + # Generate using vLLM with raw token IDs + num_generations = self.num_generations if mode == "train" else self.num_generations_eval + _, completion_ids, logprobs, _ = self.vllm_generation.generate( + prompts=prompt_ids, + images=images, + num_generations=num_generations, + profiler=profiling_context(self, "vLLM.generate"), + ) + # vLLM returns per-token top-k logprobs; keep only the top-1 (sampled token) logprob + logprobs = [[lp[0] for lp in seq] for seq in logprobs] + + elif self.use_transformers_continuous_batching: + with ( + profiling_context(self, "transformers.generate_batch"), + unwrap_model_for_generation( + self.model_wrapped, self.accelerator, gather_deepspeed3_params=self.args.ds3_gather_for_generation + ) as unwrapped_model, + torch.no_grad(), + self._dist.summon_full_params(self.model_wrapped, recurse=False), + ): + # Cast to the appropriate dtype based on training configuration + if self.args.bf16: + unwrapped_model.to(torch.bfloat16) + elif self.args.fp16: + unwrapped_model.to(torch.float16) + if self.args.cast_lm_head_to_fp32: + unwrapped_model.lm_head.to(torch.float32) + all_outputs = unwrapped_model.generate_batch( + prompt_ids, + generation_config=self.generation_config, + continuous_batching_config=self.continuous_batching_config, + progress_bar=False, + ) + unwrapped_model.train() + completion_ids = [output.generated_tokens for output in all_outputs.values()] + logprobs = None + + else: + # Regular generation path: left-pad token IDs into tensors + prompt_tensors = [torch.tensor(ids) for ids in prompt_ids] + padded_ids = pad(prompt_tensors, padding_value=self._tokenizer.pad_token_id, padding_side="left") + attention_mask = pad([torch.ones_like(t) for t in prompt_tensors], padding_value=0, padding_side="left") + generate_inputs = {"input_ids": padded_ids, "attention_mask": attention_mask} + # For VLMs, include multimodal fields as tensors (pixel_values, image_grid_thw, etc.) + for k, v in multimodal_fields.items(): + if isinstance(v, torch.Tensor): + generate_inputs[k] = v + elif isinstance(v, list) and v and isinstance(v[0], list): + # Per-token field (e.g., token_type_ids): left-pad like input_ids + generate_inputs[k] = pad([torch.tensor(x) for x in v], padding_value=0, padding_side="left") + else: + generate_inputs[k] = torch.tensor(np.array(v)) + generate_inputs = super()._prepare_inputs(generate_inputs) + + with ( + profiling_context(self, "transformers.generate"), + unwrap_model_for_generation( + self.model_wrapped, + self.accelerator, + gather_deepspeed3_params=self.args.ds3_gather_for_generation, + generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762 + ) as unwrapped_model, + torch.no_grad(), + self._dist.summon_full_params(self.model_wrapped, recurse=False), + ): + prompt_completion_ids = unwrapped_model.generate( + **generate_inputs, generation_config=self.generation_config + ) + # Compute prompt length and extract completion ids + prompt_length = generate_inputs["input_ids"].size(1) + completion_ids = prompt_completion_ids[:, prompt_length:] + + # Mask everything after the first EOS token + is_eos = completion_ids == self._tokenizer.eos_token_id + eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device) + eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)] + sequence_indices = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1) + completion_mask = (sequence_indices <= eos_idx.unsqueeze(1)).int() + completion_ids = [ + c[m].tolist() for c, m in zip(completion_ids.cpu(), completion_mask.bool().cpu(), strict=True) + ] + logprobs = None # not used in this case + + return completion_ids, logprobs + + def _get_tool_suffix_ids(self, tool_messages): + """Get token IDs for tool result formatting by using a minimal dummy conversation.""" + # Use the real tool name instead of a dummy: some templates (e.g. GPT-OSS) derive the tool response + # header from the assistant's tool call name. + dummy_tool_calls = [{"type": "function", "function": {"name": tool_messages[0]["name"], "arguments": {}}}] + dummy_messages = [ + {"role": "user", "content": "dummy"}, + { + "role": "assistant", + # "content" is required here because VLM processors crash on tokenize=True without it + # (KeyError in processing_utils.py). See huggingface/transformers#45290. + "content": "", + "tool_calls": dummy_tool_calls, + }, + ] + if self._is_vlm: + dummy_messages = prepare_multimodal_messages(dummy_messages) + tool_messages = prepare_multimodal_messages(tool_messages) + + prefix_ids = self.processing_class.apply_chat_template( + dummy_messages, + add_generation_prompt=False, + tokenize=True, + chat_template=self.chat_template, + return_dict=False, + **self.chat_template_kwargs, + ) + full_ids = self.processing_class.apply_chat_template( + dummy_messages + tool_messages, + add_generation_prompt=True, + tokenize=True, + chat_template=self.chat_template, + return_dict=False, + **self.chat_template_kwargs, + ) + # VLM processors return batched output (list of lists), unbatch for single conversation + if self._is_vlm: + prefix_ids = prefix_ids[0] + full_ids = full_ids[0] + + # Some chat templates (notably Qwen3/Qwen3.5) render "...<|im_end|>\n" after an assistant/tool block. + # When we compute `suffix_ids` by slicing `full_ids`, we must align the slicing boundary to + # EOS (not EOS + newline). Templates that don't use EOS as end-of-turn (e.g. Gemma uses + # ) skip this trimming. + eos_positions = [i for i, tok_id in enumerate(prefix_ids) if tok_id == self._tokenizer.eos_token_id] + if eos_positions: + prefix_ids = prefix_ids[: eos_positions[-1] + 1] + + if full_ids[: len(prefix_ids)] != prefix_ids: + raise ValueError("Unexpected tokenization: the EOS-trimmed prefix IDs are not a prefix of the full IDs.") + return full_ids[len(prefix_ids) :] + + def _tool_call_loop(self, prompts, prompt_ids, completion_ids, completions, logprobs, images, multimodal_fields): + # Tool execution loop: execute tools, then regenerate completions with tool results appended to the prompt + tool_calls = [completion[0].get("tool_calls") for completion in completions] + idxs_with_tool = [idx for idx, tool_call in enumerate(tool_calls) if tool_call] + tool_calls = [tool_calls[idx] for idx in idxs_with_tool] + tool_mask = [[1] * len(ids) for ids in completion_ids] # 0 for tool result tokens, 1 elsewhere + # Collect images from multimodal tool responses for the forward pass + tool_images = [[] for _ in completion_ids] + tool_call_count = 0 + tool_failure_count = 0 + iteration_num = 0 + + while idxs_with_tool and iteration_num < self.max_tool_calling_iterations: + prompt_completion_tools = [prompts[i] for i in idxs_with_tool] # select only prompts that need tool calls + # Snapshot state so we can rollback tool results that would exceed max_completion_length + completions_len_before = [len(completions[i]) for i in idxs_with_tool] + tool_images_len_before = [len(tool_images[i]) for i in idxs_with_tool] + prompts_len_before = [len(prompts[i]) for i in idxs_with_tool] + + # Call the tools, and build the new prompt for generation + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + tool_call_list = tool_calls[idx] + prompt_completion_tool = prompt_completion_tools[idx] + sync_tool_dict = self._sync_tool_dicts[idx_with_tool] + async_tool_dict = self._async_tool_dicts[idx_with_tool] + # Append the last assistant message (which triggered tool_calls) to the prompt + prompt_completion_tool.append(completions[idx_with_tool][-1]) + async_coros = [] + tool_call_results = [] + for tool_call in tool_call_list: + tool_call_count += 1 + if tool_call["type"] == "function": + function = tool_call["function"] + name = function["name"] + try: + if name in sync_tool_dict: + tool_call_results.append((name, sync_tool_dict[name](**function["arguments"]))) + elif name in async_tool_dict: + async_coros.append((name, async_tool_dict[name](**function["arguments"]))) + else: + raise ValueError(f"Tool {name} not found.") + except Exception as e: + tool_failure_count += 1 + result = {"error": str(e)} + tool_call_results.append((name, result)) + else: + tool_failure_count += 1 + name = tool_call.get("name", "unknown") + tool_call_results.append((name, {"error": f"Unsupported tool call type: {tool_call['type']}"})) + + if async_coros: + + async def _run_async_tools(async_coros): + coros = [coro for _, coro in async_coros] + results = await asyncio.gather(*coros, return_exceptions=True) + return [(name, result) for (name, _), result in zip(async_coros, results, strict=False)] + + async_results = asyncio.run_coroutine_threadsafe( + _run_async_tools(async_coros), self.async_loop + ).result() + + for name, result in async_results: + if isinstance(result, Exception): + tool_failure_count += 1 + tool_call_results.append((name, {"error": str(result)})) + else: + tool_call_results.append((name, result)) + + for name, result in tool_call_results: + # Support multimodal tool responses: if the tool returns a list of content blocks + # (e.g., [{"type": "image", "image": ...}, {"type": "text", "text": "..."}]), + # pass them through directly so _tokenize_prompts can extract images for VLMs. + content = result if isinstance(result, list) else str(result) + tool_message = {"role": "tool", "name": name, "content": content} + # Collect images from multimodal tool responses + if isinstance(content, list): + for part in content: + if isinstance(part, dict) and part.get("type") == "image": + tool_images[idx_with_tool].append(part["image"]) + prompt_completion_tool.append(tool_message) + completions[idx_with_tool].append(tool_message) + + # Build token IDs by concatenation: prompt + completion + tool_suffix. + prompt_completion_tool_ids = [] + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + # Extract trailing tool messages from completions + tool_messages = [] + for message in reversed(completions[idx_with_tool]): + if message["role"] == "tool": + tool_messages.insert(0, message) + else: + break + suffix_ids = self._get_tool_suffix_ids(tool_messages) + prompt_completion_tool_ids.append( + prompt_ids[idx_with_tool] + completion_ids[idx_with_tool] + suffix_ids + ) + + # Drop tool results whose addition would push the sequence past max_completion_length (the completion + # budget) or past the backend context ceiling (vLLM and transformers will error out on inputs longer than + # the model's max length). The sample exits the loop with its completion as-is, and the tool + # messages/images appended this iteration are rolled back so completions and tool_images stay consistent + # with completion_ids. + if self.use_vllm and self.vllm_mode == "colocate": + max_model_len = self.vllm_generation.llm.llm_engine.model_config.max_model_len + else: + config = self.model.config.text_config if self._is_vlm else self.model.config + max_model_len = config.max_position_embeddings + overlong = [ + len(pct) - len(prompt_ids[i]) > self.max_completion_length or len(pct) >= max_model_len + for i, pct in zip(idxs_with_tool, prompt_completion_tool_ids, strict=True) + ] + for idx in range(len(idxs_with_tool)): + if overlong[idx]: + idx_with_tool = idxs_with_tool[idx] + del completions[idx_with_tool][completions_len_before[idx] :] + del tool_images[idx_with_tool][tool_images_len_before[idx] :] + del prompts[idx_with_tool][prompts_len_before[idx] :] + # Keep only non-overlong items for further processing + idxs_with_tool = [idx for idx, o in zip(idxs_with_tool, overlong, strict=True) if not o] + prompt_completion_tool_ids = [ + pct for pct, o in zip(prompt_completion_tool_ids, overlong, strict=True) if not o + ] + if not idxs_with_tool: + break # all overlong, exit tool loop + + # Filter images and multimodal fields to match the current subset (index into full batch). + # Merge tool response images so the model can see visual feedback during generation. + merged_images = images + if any(imgs for imgs in tool_images): + if merged_images is None: + merged_images = [imgs if imgs else None for imgs in tool_images] + else: + merged_images = [ + (existing or []) + new for existing, new in zip(merged_images, tool_images, strict=True) + ] + loop_images = [merged_images[i] for i in idxs_with_tool] if merged_images else None + if multimodal_fields: + loop_multimodal_fields = {} + for k, v in multimodal_fields.items(): + selected = [v[i] for i in idxs_with_tool] + # Per-token fields (e.g. token_type_ids) need zero-padding to match extended prompt length + if isinstance(selected[0], list): + selected = [ + s + [0] * (len(pct) - len(s)) + for s, pct in zip(selected, prompt_completion_tool_ids, strict=True) + ] + loop_multimodal_fields[k] = selected + else: + loop_multimodal_fields = {} + + # Generate new completions after tool execution (using concatenated IDs, no re-tokenization) + post_tool_ids, post_tool_logprobs = self._generate_single_turn( + prompt_completion_tool_ids, loop_images, loop_multimodal_fields + ) + + # Truncate so that pct[len(prompt_ids[idx]) :] + post_tool does not exceed max_completion_length. + # The pre-regen check guarantees len(completion_tool_ids) <= max_completion_length, so any + # excess can only come from post_tool_ids. post_tool_ids is model-generated text and never + # contains image tokens, so a plain slice is safe. + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + completion_tool_length = len(prompt_completion_tool_ids[idx]) - len(prompt_ids[idx_with_tool]) + excess_length = completion_tool_length + len(post_tool_ids[idx]) - self.max_completion_length + if excess_length > 0: + new_len = len(post_tool_ids[idx]) - excess_length + post_tool_ids[idx] = post_tool_ids[idx][:new_len] + if logprobs is not None: + post_tool_logprobs[idx] = post_tool_logprobs[idx][:new_len] + + # Update tool_mask: the tool result should be 0 and the post-tool 1 + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + prompt_completion_tool_length = len(prompt_completion_tool_ids[idx]) + prompt_length = len(prompt_ids[idx_with_tool]) + completion_length = len(completion_ids[idx_with_tool]) + post_tool_length = len(post_tool_ids[idx]) + tool_length = prompt_completion_tool_length - prompt_length - completion_length + tool_mask[idx_with_tool] += [0] * tool_length + [1] * post_tool_length + if logprobs is not None: + logprobs[idx_with_tool] += [0.0] * tool_length + post_tool_logprobs[idx] + + # Update completion_ids with the new completions (after tool execution) + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + prompt_length = len(prompt_ids[idx_with_tool]) + pct = prompt_completion_tool_ids[idx] # = prompt-completion-tool + completion_ids[idx_with_tool] = pct[prompt_length:] + post_tool_ids[idx] + + # Decode post-tool completions. + post_tool_completions = [parse_response(self._tokenizer, ids) if ids else {} for ids in post_tool_ids] + + # Add post-tool completions to the existing completions + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + if post_tool_completions[idx]: # {} if post-tool completions completely truncated + completions[idx_with_tool].append(post_tool_completions[idx]) + + # Check for further tool calls + tool_calls = [completion.get("tool_calls") for completion in post_tool_completions] + idxs_with_tool = [idx for idx, tool_call in zip(idxs_with_tool, tool_calls, strict=True) if tool_call] + tool_calls = [tool_call for tool_call in tool_calls if tool_call] + iteration_num += 1 + + return tool_mask, completions, completion_ids, logprobs, tool_call_count, tool_failure_count, tool_images + + def _generate(self, prompts: list): + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + + # Copy the prompts to avoid modifying the original list + prompts = copy.deepcopy(prompts) + + if self.rollout_func is not None: + # Keep vLLM weights in sync for custom rollouts that rely on vLLM utilities. + if self.use_vllm and self.state.global_step != self._last_loaded_step: + with profiling_context(self, "sync_weights"): + self.vllm_generation.sync_weights() + self._last_loaded_step = self.state.global_step + + # Pass prompts to rollout_func preserving structured messages. + # Chat templating must happen inside rollout_func, at the backend boundary, so that + # multimodal content (images, typed content blocks) is not lost before rollout logic runs. + output = self.rollout_func(prompts, self) + required_keys = {"prompt_ids", "completion_ids", "logprobs"} + missing_keys = required_keys - output.keys() + if missing_keys: + missing_keys_list = sorted(missing_keys) + raise ValueError(f"rollout_func must return keys {missing_keys_list} in its output dict.") + extra_fields = {k: v for k, v in output.items() if k not in required_keys} + prompt_ids, completion_ids, logprobs = output["prompt_ids"], output["completion_ids"], output["logprobs"] + images = None + multimodal_fields = {} + else: + prompt_ids, images, multimodal_fields = self._tokenize_prompts(prompts) + completion_ids, logprobs = self._generate_single_turn(prompt_ids, images, multimodal_fields) + extra_fields = {} + + # Decode completions. It's important to use `parse_response` when possible, because it handles tool calls. + if is_conversational({"prompt": prompts[0]}): + if ( + Version(transformers.__version__) >= Version("5.0.0") # parse_response added in v5 + and hasattr(self._tokenizer, "response_schema") # attribute not set by default for now + and self._tokenizer.response_schema is not None # only works if the tokenizer has a schema + ): + completions = [[parse_response(self._tokenizer, ids)] for ids in completion_ids] + else: + contents = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + completions = [[{"role": "assistant", "content": content}] for content in contents] + else: + completions = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + + # Extract tool calls from the completions and (possibly) execute them + tool_images = [] + if self.tools: + ( + tool_mask, + completions, + completion_ids, + logprobs, + tool_call_count, + tool_failure_count, + tool_images, + ) = self._tool_call_loop( + prompts, prompt_ids, completion_ids, completions, logprobs, images, multimodal_fields + ) + # Merge tool response images into the images list for the forward pass + if any(imgs for imgs in tool_images): + if images is None: + images = [imgs if imgs else None for imgs in tool_images] + else: + images = [(existing or []) + new for existing, new in zip(images, tool_images, strict=True)] + else: + # Support custom env_mask from rollout_func (e.g., for environment feedback masking) + # Internally treated as tool_mask - marks model tokens (1) vs external tokens (0) + tool_mask = extra_fields.pop("env_mask", None) + + # Get completion length per sequence, used for logging + prompt_lengths = torch.tensor([len(ids) for ids in prompt_ids], device=device) + if tool_mask is not None: # count only model-generated tokens (tool_mask=1) + completion_lengths = torch.tensor([sum(mask) for mask in tool_mask], device=device) + else: + completion_lengths = torch.tensor([len(ids) for ids in completion_ids], device=device) + agg_prompt_lengths = self.accelerator.gather(prompt_lengths) + agg_completion_lengths = self.accelerator.gather(completion_lengths) + total_prompt_tokens = agg_prompt_lengths.sum() + total_completion_tokens = agg_completion_lengths.sum() # = num_items_in_batch, required for the DAPO loss + + # Log the metrics + if mode == "train": + self.state.num_input_tokens_seen += (total_prompt_tokens + total_completion_tokens).item() + self._metrics[mode]["num_tokens"] = [self.state.num_input_tokens_seen] + + # Log completion lengths, mean, min, max + self._metrics[mode]["completions/mean_length"].append(agg_completion_lengths.float().mean().item()) + self._metrics[mode]["completions/min_length"].append(agg_completion_lengths.float().min().item()) + self._metrics[mode]["completions/max_length"].append(agg_completion_lengths.float().max().item()) + + # Identify sequences that terminated with EOS and log their lengths + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids], device=device) + agg_is_truncated = self.accelerator.gather(is_truncated) + self._metrics[mode]["completions/clipped_ratio"].append(agg_is_truncated.float().mean().item()) + term_completion_lengths = agg_completion_lengths[~agg_is_truncated] + if len(term_completion_lengths) == 0: # edge case where no terminated sequences are found + term_completion_lengths = torch.zeros(1, device=device) + self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_lengths.float().mean().item()) + self._metrics[mode]["completions/min_terminated_length"].append(term_completion_lengths.float().min().item()) + self._metrics[mode]["completions/max_terminated_length"].append(term_completion_lengths.float().max().item()) + + if self.tools: + agg_tool_call_count = self.accelerator.gather(torch.tensor(tool_call_count, device=device)).sum() + tool_call_frequency = (agg_tool_call_count / len(agg_prompt_lengths)).item() + self._metrics[mode]["tools/call_frequency"].append(tool_call_frequency) + agg_tool_failure_count = self.accelerator.gather(torch.tensor(tool_failure_count, device=device)).sum() + failure_frequency = ( + (agg_tool_failure_count / agg_tool_call_count).item() if agg_tool_call_count > 0 else 0.0 + ) + self._metrics[mode]["tools/failure_frequency"].append(failure_frequency) + + return ( + prompt_ids, + completion_ids, + tool_mask, + completions, + total_completion_tokens, + logprobs, + extra_fields, + images, + tool_images, + ) + + def _generate_and_score_completions( + self, inputs: list[dict[str, torch.Tensor | Any]] + ) -> dict[str, torch.Tensor | Any]: + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + + prompts = [x["prompt"] for x in inputs] + + if self.environments: + for prompt, environment, reset_kwargs in zip(prompts, self.environments, inputs, strict=True): + observation = environment.reset(**reset_kwargs) + if observation is None: + continue + if isinstance(observation, list) and isinstance(prompt[-1]["content"], str): + prompt[-1]["content"] = [{"type": "text", "text": prompt[-1]["content"]}] + if isinstance(observation, str) and isinstance(prompt[-1]["content"], list): + observation = [{"type": "text", "text": observation}] + prompt[-1]["content"] += observation + + if "images" in inputs[0]: + images = [example.get("images") for example in inputs] + elif "image" in inputs[0]: + images = [[example.get("image")] if example.get("image") is not None else None for example in inputs] + else: + images = None + # Transformers requires at least one image in the batch, otherwise it throws an error + if images is not None and all(img_list == [] for img_list in images): + images = None + + # If the prompts are conversational and the inputs contain images, we need to convert the prompts from + # [{"role": "user", "content": "What color is the sky?"}] to + # [{"role": "user", "content": [{"type": "image", "image": }, {"type": "text", "text": "What color is the sky?"}]}] + if images is not None: + if not is_conversational(inputs[0]): + raise ValueError( + "Multimodal training requires conversational prompts. It looks like the dataset contains " + "non-conversational inputs, likely because a chat template was applied before passing the dataset " + "to the trainer. Please provide the raw conversational prompts and let the trainer apply the chat " + "template internally." + ) + prompts = [ + prepare_multimodal_messages(prompt, images=image_list) + for prompt, image_list in zip(prompts, images, strict=True) + ] + + dataset_images = images # preserve dataset images before _generate may overwrite + ( + prompt_ids_list, + completion_ids_list, + tool_mask_list, + completions, + num_items_in_batch, + sampling_per_token_logps_list, + extra_fields, + images, + tool_images, + ) = self._generate(prompts) + if images is None: + images = dataset_images # restore dataset images (rollout_func path returns None) + + # Convert lists of token IDs to padded tensors + prompt_ids = [torch.tensor(ids) for ids in prompt_ids_list] + prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids] + prompt_ids = pad( + prompt_ids, + padding_value=self._tokenizer.pad_token_id, + padding_side="left", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + prompt_mask = pad( + prompt_mask, padding_value=0, padding_side="left", pad_to_multiple_of=self.pad_to_multiple_of + ).to(device=device) + completion_ids = [torch.tensor(ids) for ids in completion_ids_list] + completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids] + completion_ids = pad( + completion_ids, + padding_value=self._tokenizer.pad_token_id, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + completion_mask = pad( + completion_mask, padding_value=0, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of + ).to(device=device) + if sampling_per_token_logps_list is not None: + sampling_per_token_logps = [torch.tensor(logps) for logps in sampling_per_token_logps_list] + sampling_per_token_logps = pad( + sampling_per_token_logps, + padding_value=0.0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + else: + sampling_per_token_logps = None + if tool_mask_list is not None: + tool_mask = [torch.tensor(mask) for mask in tool_mask_list] + tool_mask = pad( + tool_mask, padding_value=1, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of + ).to(device=device) + else: + tool_mask = None + + # If mask_truncated_completions is enabled, zero out truncated completions for attention and loss masking + if self.mask_truncated_completions: + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device) + # Mask completion_mask for attention masking + completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int() + # Also mask tool_mask for consistency in multi-turn training + if tool_mask is not None: + tool_mask = tool_mask * (~is_truncated).unsqueeze(1).int() + + # Concatenate prompt_mask with completion_mask for logit computation + prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) # (B, P+C) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P+C) + + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + batch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size + + num_images = [len(img_list) if img_list else 0 for img_list in images] if images is not None else None + + # Get forward_kwargs for models with multimodal inputs. + # When tool images are present (from _tool_call_loop), use image_processor directly and build + # mm_token_type_ids from prompt_completion_ids. Otherwise, use the full processor pipeline + # which returns model-specific keys (image_sizes, pixel_attention_mask, etc.). + if self.tools and any(imgs for imgs in tool_images) and self._is_vlm: + flat_images = [img for img_list in images if img_list for img in img_list] + image_inputs = self.processing_class.image_processor(images=flat_images, return_tensors="pt") + image_inputs = super()._prepare_inputs(image_inputs) + forward_kwargs = dict(image_inputs) + elif images is not None: + prompts_text = [ + apply_chat_template( + {"prompt": prompt}, self.processing_class, tools=self.tools, **self.chat_template_kwargs + )["prompt"] + for prompt in prompts + ] + prompt_inputs = self.processing_class(images=images, text=prompts_text, padding=True, return_tensors="pt") + prompt_inputs = super()._prepare_inputs(prompt_inputs) + forward_kwargs = {k: v for k, v in prompt_inputs.items() if k not in ["input_ids", "attention_mask"]} + else: + forward_kwargs = {} + + # Recover LFM2-VL tile counts; the full processor drops row/column metadata. + num_tiles = None + if images is not None and "spatial_shapes" in forward_kwargs: + image_info = self.processing_class.image_processor( + images=images, return_tensors="pt", return_row_col_info=True + ) + tiles_per_image = image_info["image_rows"] * image_info["image_cols"] + if self.processing_class.image_processor.use_thumbnail: + tiles_per_image = tiles_per_image + (tiles_per_image > 1).to(tiles_per_image.dtype) + num_tiles = [group.sum().item() for group in torch.split(tiles_per_image, num_images)] + + # If token_type_ids are used, extend them with zeros for the completion part + if "token_type_ids" in forward_kwargs: + token_type_ids = forward_kwargs["token_type_ids"] + if self.pad_to_multiple_of is not None: + # Needed only with pad_to_multiple_of: otherwise prompt_ids and token_type_ids must have equal len + padding_size = prompt_ids.size(1) - token_type_ids.size(1) + if padding_size > 0: + token_type_ids = torch.cat( + [token_type_ids.new_zeros((token_type_ids.size(0), padding_size)), token_type_ids], dim=1 + ) + forward_kwargs["token_type_ids"] = torch.cat( + [token_type_ids, token_type_ids.new_zeros(completion_ids.shape)], dim=1 + ) + # If mm_token_type_ids are used, extend them with zeros for the completion part + if "mm_token_type_ids" in forward_kwargs: + mm_token_type_ids = forward_kwargs["mm_token_type_ids"] + if self.pad_to_multiple_of is not None: + # Needed only with pad_to_multiple_of: otherwise prompt_ids and mm_token_type_ids must have equal len + padding_size = prompt_ids.size(1) - mm_token_type_ids.size(1) + if padding_size > 0: + mm_token_type_ids = torch.cat( + [mm_token_type_ids.new_zeros((mm_token_type_ids.size(0), padding_size)), mm_token_type_ids], + dim=1, + ) + forward_kwargs["mm_token_type_ids"] = torch.cat( + [mm_token_type_ids, mm_token_type_ids.new_zeros(completion_ids.shape)], dim=1 + ) + + # For VLM tool images: build token type IDs from the full prompt_completion_ids. + # This must happen AFTER the token_type_ids/mm_token_type_ids extension blocks above, + # because our version already covers the full sequence (images are in the completion, + # not just the prompt). + if self.tools and any(imgs for imgs in tool_images) and self._is_vlm: + mm_ids = torch.zeros_like(prompt_completion_ids) + if self._image_pad_token_id is not None: + mm_ids[prompt_completion_ids == self._image_pad_token_id] = 1 + if self._video_pad_token_id is not None: + mm_ids[prompt_completion_ids == self._video_pad_token_id] = 2 + + # Use the same key the model expects: token_type_ids for models like Gemma, + # mm_token_type_ids for models like Qwen. + image_grid_thw = forward_kwargs.get("image_grid_thw") + if image_grid_thw is not None: + forward_kwargs["mm_token_type_ids"] = mm_ids + else: + forward_kwargs["token_type_ids"] = mm_ids + + # Truncation safety (Qwen-style models with image_grid_thw only): if + # max_completion_length truncated some image tokens, the number of image pad tokens + # in input_ids won't match pixel_values features. Check per-sample and drop ALL + # images for any sample with a mismatch (safe fallback). + if image_grid_thw is not None and num_images is not None: + merge_length = getattr(self.processing_class.image_processor, "merge_size", 2) ** 2 + img_offset = 0 + has_mismatch = False + for b in range(mm_ids.shape[0]): + sample_tokens = (mm_ids[b] == 1).sum().item() + sample_features = 0 + for i in range(num_images[b]): + grid_idx = img_offset + i + if grid_idx < image_grid_thw.shape[0]: + sample_features += image_grid_thw[grid_idx].prod().item() // merge_length + if sample_tokens != sample_features: + has_mismatch = True + break + img_offset += num_images[b] + + if has_mismatch: + # Drop all images: safer than partial trim which is error-prone + forward_kwargs.pop("pixel_values", None) + forward_kwargs.pop("image_grid_thw", None) + mm_ids.zero_() + forward_kwargs["mm_token_type_ids"] = mm_ids + num_images = None + + # When gradient checkpointing is enabled with use_reentrant=True (non default), calling the model inside a + # torch.no_grad() block triggers a harmless PyTorch warning ("None of the inputs have requires_grad=True"). + # Temporarily disable checkpointing to avoid this warning during inference. + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + # If the generation and optimization steps are misaligned—i.e., if generation does not occur at the end of + # a full optimizer step (when gradient_accumulation_steps is not a multiple of generate_every)—then the + # samples may come from an earlier version of the model. In that case, we need to track old_per_token_logps + # for importance sampling. If the steps are aligned, importance sampling isn't necessary and we set + # old_per_token_logps to None. + # When using vLLM, we always compute old_per_token_logps for importance sampling, it was shown that the + # distribution mismatch between vLLM and the training model can be large and harm the training. + generate_every = self.args.steps_per_generation * self.num_iterations # generation frequency + if self.args.gradient_accumulation_steps % generate_every != 0 or ( + self.use_vllm and self.vllm_importance_sampling_correction + ): + old_per_token_logps, _, _ = self._get_per_token_logps_and_entropies( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size, + num_images=num_images, + num_tiles=num_tiles, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask, spatial_shapes, image_sizes, image_position_ids + ) + else: + old_per_token_logps = None + + # Compute the importance sampling ratio when using vLLM, to correct for potential distribution mismatch + if self.use_vllm and self.vllm_importance_sampling_correction: + mask = completion_mask if tool_mask is None else completion_mask * tool_mask + per_token_logps_diff = (old_per_token_logps - sampling_per_token_logps) * mask + + sequence_level_is = self.vllm_importance_sampling_mode in ["sequence_mask", "sequence_truncate"] + if sequence_level_is: + per_sequence_logps_diff = per_token_logps_diff.sum(dim=-1, keepdim=True) + logps_diff = per_sequence_logps_diff + else: + logps_diff = per_token_logps_diff + + vllm_importance_sampling_ratio = torch.exp(logps_diff) + + # vllm_importance_sampling_ratio.shape: + # token_* modes: (B, T) (per-token ratio) + # sequence_* modes: (B, 1) (per-sequence ratio) + + if self.vllm_importance_sampling_mode in ["sequence_truncate", "token_truncate"]: + vllm_importance_sampling_ratio = torch.clamp( + vllm_importance_sampling_ratio, + min=self.vllm_importance_sampling_clip_min, + max=self.vllm_importance_sampling_clip_max, + ) + elif self.vllm_importance_sampling_mode in ["sequence_mask", "token_mask"]: + min_val = ( + self.vllm_importance_sampling_clip_min + if self.vllm_importance_sampling_clip_min is not None + else -math.inf + ) + max_val = ( + self.vllm_importance_sampling_clip_max + if self.vllm_importance_sampling_clip_max is not None + else math.inf + ) + + invalid_mis_mask = (vllm_importance_sampling_ratio < min_val) | ( + vllm_importance_sampling_ratio > max_val + ) + vllm_importance_sampling_ratio = vllm_importance_sampling_ratio.masked_fill( + invalid_mis_mask, value=0.0 + ) + else: + raise ValueError( + f"Unknown vLLM importance sampling level: {self.vllm_importance_sampling_mode}. Possible values are 'token_truncate', 'token_mask', 'sequence_truncate', and 'sequence_mask'." + ) + + # Compute the per-token log probabilities for the reference model + if self.beta != 0.0: + if self.ref_model is not None: + ref_per_token_logps, _, _ = self._get_per_token_logps_and_entropies( + self.ref_model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size=batch_size, + num_images=num_images, + num_tiles=num_tiles, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask, spatial_shapes, image_sizes, image_position_ids + ) + else: + # When training a PEFT adapter, how we obtain the reference depends on the setup: + # - New adapter: disabling adapters yields the base model. + # - Re-training an existing adapter: an initial copy is loaded under the name "ref". + model = self.accelerator.unwrap_model(self.model) + with use_adapter(model, adapter_name="ref" if "ref" in model.peft_config else None): + ref_per_token_logps, _, _ = self._get_per_token_logps_and_entropies( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size=batch_size, + num_images=num_images, + num_tiles=num_tiles, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask, spatial_shapes, image_sizes, image_position_ids + ) + else: + ref_per_token_logps = None + + # Decode + prompts_text = self.processing_class.batch_decode(prompt_ids, skip_special_tokens=True) + completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + + # Merge extra_fields from rollout_func into inputs for reward functions + if extra_fields: + for i, inp in enumerate(inputs): + for key, values in extra_fields.items(): + if isinstance(values, list) and i < len(values): + inp[key] = values[i] + elif not isinstance(values, list): + inp[key] = values + + # Calculate rewards for each reward function. rewards_per_func aggregates rewards across all processes. This is + # important because rewards will be normalized per group, and completions are distributed. We will later slice + # rewards_per_func to extract each process's subset. + rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list) + num_generations = self.num_generations if mode == "train" else self.num_generations_eval + + # A completion for which every reward function returned None is unscorable. nansum would collapse it to 0, + # which both biases the per-group baseline and hands the completion a spurious advantage. Mark these rows NaN + # so they're excluded from the (nan-aware) baseline below; their advantage is forced to 0 afterwards. + unscorable_mask = torch.isnan(rewards_per_func).all(dim=1) + + if self.multi_objective_aggregation == "sum_then_normalize": + # Apply weights to each reward function's output and sum + rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1) + rewards[unscorable_mask] = torch.nan + mean_grouped_rewards = torch.nanmean(rewards.view(-1, num_generations), dim=1) + mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(num_generations, dim=0) + if self.scale_rewards in ["group", "none"]: + # If self.scale_rewards = "none", we'll only use std_rewards to check for zero std for logging + if num_generations > 1: + std_rewards = nanstd(rewards.view(-1, num_generations), dim=1) + std_rewards = std_rewards.repeat_interleave(num_generations, dim=0) + else: # doesn't occur during training, but could occur in eval when num_generations_eval=1 + std_rewards = torch.zeros_like(rewards) + elif self.scale_rewards == "batch": + # Compute global std + if rewards.numel() > 1: + std_rewards = nanstd(rewards).expand_as(rewards) + else: # doesn't occur during training, but could occur in eval when num_generations_eval=batch_size=1 + std_rewards = torch.zeros_like(rewards) + else: + raise ValueError( + f"Invalid value for scale_rewards: {self.scale_rewards}. Must be one of 'batch', 'group', or 'none'." + ) + + advantages = rewards - mean_grouped_rewards + if self.scale_rewards != "none": + advantages = advantages / (std_rewards + 1e-4) + is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards)) # for logging + + elif self.multi_objective_aggregation == "normalize_then_sum": + grouped = rewards_per_func.view(-1, num_generations, len(self.reward_funcs)) + mean_k = torch.nanmean(grouped, dim=1, keepdim=True) + std_k = nanstd(grouped, dim=1, keepdim=True) if num_generations > 1 else torch.zeros_like(mean_k) + reward_k = (grouped - mean_k) / (std_k + 1e-4) + reward_k = reward_k.view(-1, len(self.reward_funcs)) + rewards = (reward_k * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1) + rewards[unscorable_mask] = torch.nan + std_rewards = nanstd(rewards).expand_as(rewards) if rewards.numel() > 1 else torch.zeros_like(rewards) + advantages = (rewards - torch.nanmean(rewards)) / (std_rewards + 1e-4) + is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards)) # for logging + + else: + raise ValueError( + f"Invalid multi_objective_aggregation: {self.multi_objective_aggregation}. Must be " + "'sum_then_normalize' or 'normalize_then_sum'." + ) + + # Unscorable completions (every reward func returned None) carry no learning signal: their reward is NaN here, + # so zero their advantage to keep them from moving the policy. + advantages = torch.nan_to_num(advantages, nan=0.0) + + # Slice to keep only the local part of the data + process_slice = slice( + self.accelerator.process_index * len(prompts), + (self.accelerator.process_index + 1) * len(prompts), + ) + all_process_advantages = advantages.clone() # keep the aggregated advantages for logging + advantages = advantages[process_slice] + + # Calculate mean reward per function, but only for samples where the function was applied (non-NaN values) + for i, reward_func_name in enumerate(self.reward_func_names): + mean_rewards = torch.nanmean(rewards_per_func[:, i]).item() + self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards) + std_func_rewards = nanstd(rewards_per_func[:, i]).item() + self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_func_rewards) + rewards = (rewards_per_func * self.reward_weights.to(rewards_per_func.device).unsqueeze(0)).nansum(dim=1) + rewards[unscorable_mask] = torch.nan # exclude unscorable rows from the logged reward stats + self._metrics[mode]["reward"].append(torch.nanmean(rewards).item()) + self._metrics[mode]["reward_std"].append(nanstd(rewards).item()) + self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item()) + + # Log prompt and completion texts + self._logs["prompt"].extend(gather_object(prompts_text)) + self._logs["completion"].extend(gather_object(completions_text)) + for i, name in enumerate(self.reward_func_names): + self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist()) + self._logs["advantages"].extend(all_process_advantages.tolist()) + + # Flush user-logged extra columns (from log_extra), gathering across processes. + # Keys must be sorted so that all ranks call gather_object in the same order, otherwise values + # get mis-attributed across columns (dict insertion order may differ between processes). + for column in sorted(self._pending_extra_logs): + self._logs["extra"][column].extend(gather_object(self._pending_extra_logs[column])) + self._pending_extra_logs.clear() + + # Flush user-logged metrics (from log_metric), averaging across processes. + # Keys must be sorted so that all ranks call accelerator.gather in the same order, otherwise values + # get mis-attributed across metrics (dict insertion order may differ between processes). + for name in sorted(self._pending_metrics): + values = self._pending_metrics[name] + local_mean = sum(values) / len(values) + global_mean = self.accelerator.gather(torch.tensor(local_mean, device=device)).mean().item() + self._metrics[mode][name].append(global_mean) + self._pending_metrics.clear() + + if images is not None: + self._logs["images"].extend(gather_object(images)) + + if self.use_vllm and self.vllm_importance_sampling_correction: + delta = torch.abs(old_per_token_logps - sampling_per_token_logps) + mask = completion_mask.bool() if tool_mask is None else (completion_mask * tool_mask).bool() + delta = delta[mask] + mean_delta = torch.mean(delta) if delta.numel() > 0 else torch.tensor(0.0, device=device) + max_delta = torch.max(delta) if delta.numel() > 0 else torch.tensor(0.0, device=device) + self._metrics[mode]["sampling/sampling_logp_difference/mean"].append( + self.accelerator.gather(mean_delta).mean().item() + ) + self._metrics[mode]["sampling/sampling_logp_difference/max"].append( + self.accelerator.gather(max_delta).max().item() + ) + if sequence_level_is: + flat_is_ratio = vllm_importance_sampling_ratio.flatten() + else: + flat_is_ratio = vllm_importance_sampling_ratio[mask] + + min_importance_sampling_ratio = ( + torch.min(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device) + ) + mean_importance_sampling_ratio = ( + torch.mean(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device) + ) + max_importance_sampling_ratio = ( + torch.max(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device) + ) + self._metrics[mode]["sampling/importance_sampling_ratio/min"].append( + nanmin(self.accelerator.gather(min_importance_sampling_ratio)).item() + ) + self._metrics[mode]["sampling/importance_sampling_ratio/mean"].append( + self.accelerator.gather(mean_importance_sampling_ratio).nanmean().item() + ) + self._metrics[mode]["sampling/importance_sampling_ratio/max"].append( + nanmax(self.accelerator.gather(max_importance_sampling_ratio)).item() + ) + + output = { + "prompt_ids": prompt_ids, + "prompt_mask": prompt_mask, + "completion_ids": completion_ids, + "completion_mask": completion_mask, + "advantages": advantages, + "num_items_in_batch": num_items_in_batch, + } + if old_per_token_logps is not None: + output["old_per_token_logps"] = old_per_token_logps + if self.use_vllm and self.vllm_importance_sampling_correction: + output["importance_sampling_ratio"] = vllm_importance_sampling_ratio + if sampling_per_token_logps is not None: + output["sampling_per_token_logps"] = sampling_per_token_logps + if ref_per_token_logps is not None: + output["ref_per_token_logps"] = ref_per_token_logps + if "pixel_values" in forward_kwargs: + output["pixel_values"] = forward_kwargs["pixel_values"] + if "image_grid_thw" in forward_kwargs: + output["image_grid_thw"] = forward_kwargs["image_grid_thw"] + if "pixel_attention_mask" in forward_kwargs: + output["pixel_attention_mask"] = forward_kwargs["pixel_attention_mask"] + if "spatial_shapes" in forward_kwargs: + output["spatial_shapes"] = forward_kwargs["spatial_shapes"] + if "image_sizes" in forward_kwargs: + output["image_sizes"] = forward_kwargs["image_sizes"] + if "token_type_ids" in forward_kwargs: + output["token_type_ids"] = forward_kwargs["token_type_ids"] + if "mm_token_type_ids" in forward_kwargs: + output["mm_token_type_ids"] = forward_kwargs["mm_token_type_ids"] + if "image_position_ids" in forward_kwargs: + output["image_position_ids"] = forward_kwargs["image_position_ids"] + if images is not None: + output["num_images"] = num_images + if num_tiles is not None: + output["num_tiles"] = num_tiles + if tool_mask is not None: + output["tool_mask"] = tool_mask + return output + + def compute_liger_loss(self, unwrapped_model, inputs): + # Compute the per-token log probabilities for the model + prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"] + completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"] + input_ids = torch.cat([prompt_ids, completion_ids], dim=1) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + + # Get the last hidden state of the model + last_hidden_state = self._get_last_hidden_state( + unwrapped_model, + input_ids, + attention_mask, + logits_to_keep, + inputs.get("pixel_values"), + inputs.get("image_grid_thw"), + inputs.get("pixel_attention_mask"), + inputs.get("spatial_shapes"), + inputs.get("image_sizes"), + inputs.get("image_position_ids"), + ) + + # Apply tool_mask (from env_mask) for loss computation in multi-turn training scenarios + loss_mask = completion_mask if "tool_mask" not in inputs else completion_mask * inputs["tool_mask"] + lm_head_weight = unwrapped_model.lm_head.weight + lm_head_bias = unwrapped_model.lm_head.bias + # Liger reads `lm_head` directly instead of through `model.forward()`, so its ZeRO-3 gather hook never fires + # and the fused matmul gets an empty shard. Gather the weight/bias ourselves for the call (the weight grad is + # computed during this forward, so it isn't needed in the backward). Skip it when already gathered: with tied + # embeddings `embed_tokens` keeps the weight `AVAILABLE`, and re-partitioning on exit breaks its tracking. + deepspeed_plugin = self.accelerator.state.deepspeed_plugin + gather_ctx = nullcontext() + if deepspeed_plugin is not None and deepspeed_plugin.zero_stage == 3: + from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus + + params = [lm_head_weight] if lm_head_bias is None else [lm_head_weight, lm_head_bias] + if any(p.ds_status != ZeroParamStatus.AVAILABLE for p in params): + import deepspeed + + gather_ctx = deepspeed.zero.GatheredParameters(params, modifier_rank=None) + with gather_ctx: + loss, metrics = self.liger_grpo_loss( + _input=last_hidden_state, + lin_weight=lm_head_weight, + selected_token_ids=completion_ids, + # The attention_mask parameter in liger loss is actually used as a loss mask (not model attention) + attention_mask=loss_mask, + advantages=inputs["advantages"], + bias=lm_head_bias, + old_per_token_logps=inputs.get("old_per_token_logps"), + ref_per_token_logps=inputs.get("ref_per_token_logps"), + vllm_is_ratio=inputs.get("importance_sampling_ratio"), + ) + # Extract metrics from the liger_grpo_loss output + # KL divergence is the first metric when beta is non-zero + mean_kl = metrics[0] if self.beta != 0.0 else None + clip_ratio = metrics[-1] + + mode = "train" if self.model.training else "eval" + if self.beta != 0.0: + self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).mean().item()) + self._metrics[mode]["clip_ratio"].append(self.accelerator.gather(clip_ratio).mean().item()) + normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval + return loss / normalizer + + @profiling_decorator + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + if return_outputs: + raise ValueError("The GRPOTrainer does not support returning outputs") + if self.use_liger_kernel: + # Compute the loss using the liger grpo loss + unwrapped_model = self.accelerator.unwrap_model(model) + return self._forward_redirection(model, unwrapped_model, self.compute_liger_loss, unwrapped_model, inputs) + return self._compute_loss(model, inputs) + + @staticmethod + def get_off_policy_mask( + advantages: torch.Tensor, + per_token_logps: torch.Tensor, + sampling_per_token_logps: torch.Tensor, + mask: torch.Tensor, + off_policy_threshold: float, + ) -> torch.Tensor: + """ + Computes the Off-Policy Sequence Mask from DeepSeek-V3.2 paper. Returns a (B, 1) tensor where 1.0 indicates + "Keep" and 0.0 indicates "Drop". + """ + # forward KL div: log(pi_old) - log(pi_theta) + kl_div = sampling_per_token_logps - per_token_logps.detach() + # Sequence-level Mean KL (ignoring prompt+padding) + seq_kl_sum = (kl_div * mask).sum(dim=1, keepdim=True) + avg_seq_kl = seq_kl_sum / mask.sum(dim=1, keepdim=True).clamp(min=1.0) + # Keep if (Advantage >= 0) OR (KL <= delta) + is_pos_adv = advantages >= 0 + is_low_kl = avg_seq_kl <= off_policy_threshold + return (is_pos_adv | is_low_kl).to(dtype=mask.dtype) # (B, 1) + + @staticmethod + @torch.no_grad() + def get_gamma_weights( + advantages: torch.Tensor, + log_ratio_per_token: torch.Tensor, + mask: torch.Tensor, + importance_sampling_ratio: torch.Tensor | None, # (B, T) + k_pos: float = 2.0, + lambda_pos: float = 3.0, + k_neg: float = 3.0, + lambda_neg: float = 2.0, + ) -> torch.Tensor: + """ + Computes the Gamma weights for the VESPO loss. For reference: + φ(w) = e^λ × w^k × e^{-λw} is the gamma weighting (normalized so φ(1)=1) + with w = sequence-level importance sampling ratio + note: we will compute φ(w) in log space + + φ(w) is detached via @torch.no_grad(), only acts as gradient scaling coefficient + + VESPO loss = -φ(w) × A × log_prob, gradient naturally gives φ(w) × A × ∇log π + """ + # reducing clamp range directly to log(1e-8) ~ -18.42, to avoid recomputing log_w=log(w.clamp(min=1e-8)) later + # This is solely for matching truthfully the original implementation, otherwise keeping -20 could be fine. + lower_clamp = math.log(1e-8) + + # Sequence-level log ratio Σ log(π_θ/π_old) (not a mean like for `log_importance_weights`) + log_ratio_clamped = torch.clamp(log_ratio_per_token, -20.0, 20.0) + seq_log_ratio = torch.sum(log_ratio_clamped * mask, dim=-1, keepdim=True) # (B, 1) + + # Apply token-level TIS or MIS correction (in log space) + if importance_sampling_ratio is not None: + log_is_ratio = torch.clamp(torch.log(importance_sampling_ratio), lower_clamp, 20.0) + # log(w) = log(π_θ/π_old) + log(π_old/π_sampler) + seq_log_ratio += torch.sum(log_is_ratio, dim=-1, keepdim=True) + + log_w_seq = torch.clamp(seq_log_ratio, lower_clamp, 20.0) + w_seq = torch.exp(log_w_seq) + + # compute k and lambda based on advantage sign + is_nonneg_adv = advantages >= 0 + k_seq = torch.where(is_nonneg_adv, k_pos, k_neg) + lambda_seq = torch.where(is_nonneg_adv, lambda_pos, lambda_neg).clamp(min=1e-4) + + # log(φ(w)) = λ + k × log(w) - λ × w + log_phi = lambda_seq + k_seq * log_w_seq - lambda_seq * w_seq + phi_seq = torch.exp(log_phi).nan_to_num(nan=0.0, posinf=0.0, neginf=0.0) + + return phi_seq # (B, 1) + + def _compute_loss(self, model, inputs): + # Compute the per-token log probabilities for the model + prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"] + completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"] + input_ids = torch.cat([prompt_ids, completion_ids], dim=1) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + mask = completion_mask if "tool_mask" not in inputs else completion_mask * inputs["tool_mask"] + + # Compute the per_token_logps and the entropy at each position in the completion + per_token_logps, entropies, aux_loss = self._get_per_token_logps_and_entropies( + model, + input_ids, + attention_mask, + logits_to_keep, + compute_entropy=True, + compute_aux_loss=self.aux_loss_enabled, + pixel_values=inputs.get("pixel_values"), + image_grid_thw=inputs.get("image_grid_thw"), + num_images=inputs.get("num_images"), + pixel_attention_mask=inputs.get("pixel_attention_mask"), + spatial_shapes=inputs.get("spatial_shapes"), + num_tiles=inputs.get("num_tiles"), + image_sizes=inputs.get("image_sizes"), + token_type_ids=inputs.get("token_type_ids"), + mm_token_type_ids=inputs.get("mm_token_type_ids"), + image_position_ids=inputs.get("image_position_ids"), + ) + + if self.top_entropy_quantile < 1.0: + entropy_mask = self.get_high_entropy_mask(entropies, mask, 1 - self.top_entropy_quantile) + else: + entropy_mask = None + + # Compute the loss + advantages = inputs["advantages"] + # In the base GRPO implementation, advantages are expected to have shape (B,). To support subclasses that + # provide advantages with shape (B, T) (e.g., MiniLLM), we *conditionally* unsqueeze the tensor. + if advantages.dim() == 1: + advantages = advantages.unsqueeze(1) + # When num_iterations == 1 and steps_per_generation <= gradient_accumulation_steps, + # old_per_token_logps == per_token_logps. In this case we can skip its computation + # (see _generate_and_score_completions) and instead use per_token_logps.detach(). + # The exception is when using vLLM, where we always compute old_per_token_logps + # for importance sampling + old_per_token_logps = inputs.get("old_per_token_logps") + old_per_token_logps = per_token_logps.detach() if old_per_token_logps is None else old_per_token_logps + + if self.off_policy_mask_threshold is not None: + # OPSM should use inference-time logprobs to detect both sources of off-policyness: + # 1. Drift from gradient updates (always present) + # 2. Drift from training-inference mismatch (when using vLLM) + # When using vLLM, prioritize sampling_per_token_logps, otherwise use old_per_token_logps + sampling_per_token_logps = inputs.get("sampling_per_token_logps", old_per_token_logps) + + off_policy_mask = self.get_off_policy_mask( + advantages=advantages, + per_token_logps=per_token_logps, + sampling_per_token_logps=sampling_per_token_logps, + mask=mask, + off_policy_threshold=self.off_policy_mask_threshold, + ) + + log_ratio = per_token_logps - old_per_token_logps + if self.importance_sampling_level == "token": + log_importance_weights = log_ratio + elif self.importance_sampling_level == "sequence": + log_importance_weights = (log_ratio * mask).sum(-1) / mask.sum(-1).clamp(min=1.0) + log_importance_weights = log_importance_weights.unsqueeze(-1) + else: + raise ValueError( + f"Unknown importance sampling level: {self.importance_sampling_level}. Possible values are 'token' " + "and 'sequence'." + ) + + coef_1 = torch.exp(log_importance_weights) + + # Compute the KL divergence between the model and the reference model + if self.beta != 0.0: + ref_per_token_logps = inputs["ref_per_token_logps"] + per_token_kl = ( + torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1 + ) + # Importance sampling correction for the KL divergence + if self.args.use_bias_correction_kl: + per_token_kl = per_token_kl * coef_1 + + # From here, log_importance_weights (and all subsequent tensors, coef_1, coef_2, etc.) shape depends on + # importance_sampling_level: "token" level: (B, T); "sequence" level: (B, 1) + if self.loss_type == "cispo": + clamped_ratios = torch.clamp(coef_1, max=self.epsilon_high).detach() + per_token_loss = -clamped_ratios * advantages * per_token_logps + elif self.loss_type in ["grpo", "bnpo", "dr_grpo", "dapo", "luspo"]: + coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high) + # Two-sided clipping + if self.args.delta is not None: + coef_1 = torch.clamp(coef_1, max=self.args.delta) + + per_token_loss1 = coef_1 * advantages + per_token_loss2 = coef_2 * advantages + per_token_loss = -torch.min(per_token_loss1, per_token_loss2) + elif self.loss_type == "sapo": + temperatures = torch.where(advantages > 0, self.args.sapo_temperature_pos, self.args.sapo_temperature_neg) + soft_coef_1 = torch.sigmoid(temperatures * (coef_1 - 1)) * 4 / temperatures + per_token_loss = -soft_coef_1 * advantages + elif self.loss_type == "vespo": + phi_seq = self.get_gamma_weights( + advantages=advantages, + log_ratio_per_token=log_ratio, + mask=mask, + importance_sampling_ratio=inputs.get("importance_sampling_ratio"), + k_pos=self.args.vespo_k_pos, + lambda_pos=self.args.vespo_lambda_pos, + k_neg=self.args.vespo_k_neg, + lambda_neg=self.args.vespo_lambda_neg, + ) + per_token_loss = -phi_seq * advantages * per_token_logps + else: + raise ValueError(f"Unknown loss type: {self.loss_type}") + + if self.off_policy_mask_threshold is not None: + per_token_loss = per_token_loss * off_policy_mask + + if entropy_mask is not None: + per_token_loss = per_token_loss * entropy_mask + + if self.use_vllm and self.vllm_importance_sampling_correction and self.loss_type != "vespo": + per_token_loss = per_token_loss * inputs["importance_sampling_ratio"] + + if self.beta != 0.0: + per_token_loss = per_token_loss + self.beta * per_token_kl + + mode = "train" if self.model.training else "eval" + if self.loss_type in ["grpo", "sapo"]: + loss = ((per_token_loss * mask).sum(-1) / mask.sum(-1).clamp(min=1.0)).mean() + normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval + loss = loss / normalizer + elif self.loss_type == "bnpo": + loss = (per_token_loss * mask).sum() / mask.sum().clamp(min=1.0) + normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval + loss = loss / normalizer + elif self.loss_type == "dr_grpo": + loss = (per_token_loss * mask).sum() / (per_token_loss.size(0) * self.max_completion_length) + normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval + loss = loss / normalizer + elif self.loss_type in ["cispo", "dapo", "vespo"]: + normalizer = inputs["num_items_in_batch"] / self.accelerator.num_processes + loss = (per_token_loss * mask).sum() / normalizer + elif self.loss_type == "luspo": + # Unless importance_sampling_level="token" (not recommended here), per_token_loss is expected to be (B, 1) + loss = (per_token_loss * mask.sum(1, keepdim=True)).mean() + normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 + loss = loss / normalizer + else: + raise ValueError(f"Unknown loss type: {self.loss_type}") + + # The policy loss above is scaled for gradient accumulation (HF auto-scaling is off here), so scale aux too + if self.aux_loss_enabled: + normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 + loss = loss + self.router_aux_loss_coef * aux_loss / normalizer + self._metrics[mode]["aux_loss"].append(self.accelerator.gather_for_metrics(aux_loss).mean().item()) + + # Log the metrics + completion_token_count = mask.sum().clamp(min=1.0) + + def masked_batch_mean(x): + if x.shape[1] == 1: # when importance_sampling_level == "sequence" + return x.mean() + else: + return (x * mask).sum() / completion_token_count + + if self.beta != 0.0: + mean_kl = masked_batch_mean(per_token_kl) + self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item()) + + mean_entropy = masked_batch_mean(entropies) + self._metrics[mode]["entropy"].append(self.accelerator.gather(mean_entropy).nanmean().item()) + + if self.loss_type in ["grpo", "bnpo", "dr_grpo", "dapo", "luspo"]: + # Compute the clipped probability ratios + is_low_clipped = (coef_1 < 1 - self.epsilon_low) & (advantages < 0) + is_high_clipped = (coef_1 > 1 + self.epsilon_high) & (advantages > 0) + is_region_clipped = is_low_clipped | is_high_clipped + + low_clip = masked_batch_mean(is_low_clipped.float()) + high_clip = masked_batch_mean(is_high_clipped.float()) + clip_ratio = masked_batch_mean(is_region_clipped.float()) + + gathered_low_clip = self.accelerator.gather(low_clip) + self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item()) + self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item()) + gathered_high_clip = self.accelerator.gather(high_clip) + self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item()) + self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item()) + gathered_clip_ratio = self.accelerator.gather(clip_ratio) + self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item()) + elif self.loss_type == "cispo": + is_cispo_clipped = (coef_1 > self.epsilon_high) & (advantages > 0) + cispo_clip_ratio = masked_batch_mean(is_cispo_clipped.float()) + gathered_cispo_clip_ratio = self.accelerator.gather(cispo_clip_ratio) + self._metrics[mode]["cispo_clip_ratio"].append(gathered_cispo_clip_ratio.nanmean().item()) + elif self.loss_type == "vespo": + gathered_phi_seq = self.accelerator.gather(phi_seq) + self._metrics[mode]["vespo/phi_seq_mean"].append(gathered_phi_seq.nanmean().item()) + + return loss + + # During eval, Trainer calls prediction_step. If no labels are present in the inputs, it only runs forward and + # returns logits. We override prediction_step to force compute_loss, because this trainer doesn't involve labels. + def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys: list[str] | None = None): + inputs = self._prepare_inputs(inputs) + with torch.no_grad(): + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + loss = loss.mean().detach() + return loss, None, None + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + # Average the metrics + metrics = {} + for key, val in self._metrics[mode].items(): + # Filter out NaN values before averaging. A reward function that returns None for all samples + # in a batch produces NaN for that batch's metric. With logging_steps > 1, a naive sum()/len() + # would let a single NaN contaminate valid data from other batches. Only return None when no + # valid values remain (e.g. JSON loggers crash on float NaN). + valid = [v for v in val if not math.isnan(v)] + metrics[key] = sum(valid) / len(valid) if valid else None + + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + if self.accelerator.is_main_process and self.log_completions: + if is_rich_available(): + print_prompt_completions_sample( + self._logs["prompt"], + self._logs["completion"], + self._logs["rewards"], + self._logs["advantages"], + self.state.global_step, + self.num_completions_to_print, + extra=dict(self._logs["extra"]), + ) + + logging_backends = [] + if self.args.report_to and "wandb" in self.args.report_to and wandb.run is not None: + logging_backends.append(wandb) + if self.args.report_to and "trackio" in self.args.report_to: + logging_backends.append(trackio) + + table = { + "step": [self.state.global_step] * len(self._logs["prompt"]), + "prompt": self._logs["prompt"], + "completion": self._logs["completion"], + **self._logs["rewards"], + **self._logs["extra"], + "advantage": self._logs["advantages"], + } + + df_base = pd.DataFrame(table) + df_base.to_parquet( + os.path.join( + self.args.output_dir, + "completions", + f"completions_{self.state.global_step:05d}.parquet", + ) + ) + + images_raw = self._logs["images"] or [] + + for logging_backend in logging_backends: + if images_raw: + images = [] + for image_list in self._logs["images"]: + if image_list: + images.append([logging_backend.Image(image) for image in image_list]) + else: + images.append([]) + df = pd.concat( + [df_base, pd.Series(images, name="image")], + axis=1, + copy=False, + ) + else: + df = df_base + + if self.log_unique_prompts: + df = df.drop_duplicates(subset=["prompt"]) + + logging_backend.log({"completions": logging_backend.Table(dataframe=df)}) + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/kto_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/kto_config.py new file mode 100644 index 0000000000000000000000000000000000000000..849648a8f74f245df98cab016a7b87fa1b628f93 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/kto_config.py @@ -0,0 +1,36 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass + +from ..import_utils import suppress_experimental_warning + + +with suppress_experimental_warning(): + from ..experimental.kto import KTOConfig as _KTOConfig + + +@dataclass +class KTOConfig(_KTOConfig): + def __post_init__(self): + warnings.warn( + "The `KTOConfig` is now located in `trl.experimental`. Please update your imports to " + "`from trl.experimental.kto import KTOConfig`. For more information, see " + "https://github.com/huggingface/trl/issues/4223. Promoting KTO to the stable API is a high-priority task. " + "Until then, this current path (`from trl import KTOConfig`) will remain, but API changes may occur.", + FutureWarning, + stacklevel=3, + ) + super().__post_init__() diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/kto_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/kto_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..110e29f0a8062efe09a87cddf2a7574d4f8d999e --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/kto_trainer.py @@ -0,0 +1,36 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass + +from ..import_utils import suppress_experimental_warning + + +with suppress_experimental_warning(): + from ..experimental.kto import KTOTrainer as _KTOTrainer + + +@dataclass +class KTOTrainer(_KTOTrainer): + def __init__(self, *args, **kwargs): + warnings.warn( + "The `KTOTrainer` is now located in `trl.experimental`. Please update your imports to " + "`from trl.experimental.kto import KTOTrainer`. For more information, see " + "https://github.com/huggingface/trl/issues/4223. Promoting KTO to the stable API is a high-priority task. " + "Until then, this current path (`from trl import KTOTrainer`) will remain, but API changes may occur.", + FutureWarning, + stacklevel=2, + ) + super().__init__(*args, **kwargs) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/model_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/model_config.py new file mode 100644 index 0000000000000000000000000000000000000000..c64d7a9ccade1cc7adb27dbd73742ee888714fb1 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/model_config.py @@ -0,0 +1,178 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field + + +@dataclass +class ModelConfig: + """ + Configuration class for the models. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + model_name_or_path (`str`, *optional*): + Model checkpoint for weights initialization. + model_revision (`str`, *optional*, defaults to `"main"`): + Specific model version to use. It can be a branch name, a tag name, or a commit id. + dtype (`Literal["auto", "bfloat16", "float16", "float32"]`, *optional*, defaults to `"float32"`): + Override the default `torch.dtype` and load the model under this dtype. Possible values are + + - `"bfloat16"`: `torch.bfloat16` + - `"float16"`: `torch.float16` + - `"float32"`: `torch.float32` + - `"auto"`: Automatically derive the dtype from the model's weights. + + attn_implementation (`str`, *optional*): + Which attention implementation to use. More information in the [Kernels Hub Integrations + Guide](kernels_hub). + use_peft (`bool`, *optional*, defaults to `False`): + Whether to use PEFT for training. + lora_r (`int`, *optional*, defaults to `16`): + LoRA R value. + lora_alpha (`int`, *optional*, defaults to `32`): + LoRA alpha. + lora_dropout (`float`, *optional*, defaults to `0.05`): + LoRA dropout. + lora_target_modules (`str | list[str]`, *optional*): + LoRA target modules. + lora_target_parameters (`str | list[str]`, *optional*): + List of target parameters for LoRA. + lora_modules_to_save (`list[str]`, *optional*): + Model layers to unfreeze & train. + lora_task_type (`str`, *optional*, defaults to `"CAUSAL_LM"`): + Task type to pass for LoRA (use `"SEQ_CLS"` for reward modeling). + use_rslora (`bool`, *optional*, defaults to `False`): + Whether to use Rank-Stabilized LoRA, which sets the adapter scaling factor to `lora_alpha/√r`, instead of + the original default value of `lora_alpha/r`. + use_dora (`bool`, *optional*, defaults to `False`): + Enable [Weight-Decomposed Low-Rank Adaptation (DoRA)](https://huggingface.co/papers/2402.09353). This + technique decomposes the updates of the weights into two parts, magnitude and direction. Direction is + handled by normal LoRA, whereas the magnitude is handled by a separate learnable parameter. This can + improve the performance of LoRA, especially at low ranks. Right now, DoRA only supports linear and Conv2D + layers. DoRA introduces a bigger overhead than pure LoRA, so it is recommended to merge weights for + inference. + load_in_8bit (`bool`, *optional*, defaults to `False`): + Whether to use 8 bit precision for the base model. Works only with LoRA. + load_in_4bit (`bool`, *optional*, defaults to `False`): + Whether to use 4 bit precision for the base model. Works only with LoRA. + bnb_4bit_quant_type (`str`, *optional*, defaults to `"nf4"`): + Quantization type (`"fp4"` or `"nf4"`). + use_bnb_nested_quant (`bool`, *optional*, defaults to `False`): + Whether to use nested quantization. + bnb_4bit_quant_storage (`str`, *optional*): + Quantization storage dtype. + """ + + model_name_or_path: str | None = field( + default=None, + metadata={"help": "Model checkpoint for weights initialization."}, + ) + model_revision: str = field( + default="main", + metadata={"help": "Specific model version to use. It can be a branch name, a tag name, or a commit id."}, + ) + dtype: str | None = field( + default="float32", + metadata={ + "help": "Override the default `torch.dtype` and load the model under this dtype. It defaults to `'float32'`.", + "choices": ["auto", "bfloat16", "float16", "float32"], + }, + ) + attn_implementation: str | None = field( + default=None, + metadata={ + "help": "Which attention implementation to use. You can run `--attn_implementation=flash_attention_2`, in " + "which case you must install this manually by running `pip install flash-attn --no-build-isolation`." + }, + ) + use_peft: bool = field( + default=False, + metadata={"help": "Whether to use PEFT for training."}, + ) + lora_r: int = field( + default=16, + metadata={"help": "LoRA R value."}, + ) + lora_alpha: int = field( + default=32, + metadata={"help": "LoRA alpha."}, + ) + lora_dropout: float = field( + default=0.05, + metadata={"help": "LoRA dropout."}, + ) + lora_target_modules: list[str] | None = field( + default=None, + metadata={"help": "LoRA target modules."}, + ) + lora_target_parameters: list[str] | None = field( + default=None, + metadata={"help": "List of target parameters for LoRA."}, + ) + lora_modules_to_save: list[str] | None = field( + default=None, + metadata={"help": "Model layers to unfreeze & train."}, + ) + lora_task_type: str = field( + default="CAUSAL_LM", + metadata={"help": "Task type to pass for LoRA (use 'SEQ_CLS' for reward modeling)."}, + ) + use_rslora: bool = field( + default=False, + metadata={ + "help": "Whether to use Rank-Stabilized LoRA, which sets the adapter scaling factor to `lora_alpha/√r`, " + "instead of the original default value of `lora_alpha/r`." + }, + ) + use_dora: bool = field( + default=False, + metadata={ + "help": "Enable Weight-Decomposed Low-Rank Adaptation (DoRA). This technique decomposes the updates of " + "the weights into two parts, magnitude and direction. Direction is handled by normal LoRA, whereas the " + "magnitude is handled by a separate learnable parameter. This can improve the performance of LoRA, " + "especially at low ranks. Right now, DoRA only supports linear and Conv2D layers. DoRA introduces a " + "bigger overhead than pure LoRA, so it is recommended to merge weights for inference." + }, + ) + load_in_8bit: bool = field( + default=False, + metadata={"help": "Whether to use 8 bit precision for the base model. Works only with LoRA."}, + ) + load_in_4bit: bool = field( + default=False, + metadata={"help": "Whether to use 4 bit precision for the base model. Works only with LoRA."}, + ) + bnb_4bit_quant_type: str = field( + default="nf4", + metadata={"help": "Quantization type.", "choices": ["fp4", "nf4"]}, + ) + use_bnb_nested_quant: bool = field( + default=False, + metadata={"help": "Whether to use nested quantization."}, + ) + bnb_4bit_quant_storage: str | None = field( + default=None, + metadata={"help": "Quantization storage dtype"}, + ) + + def __post_init__(self): + if self.load_in_8bit and self.load_in_4bit: + raise ValueError("You can't use 8 bit and 4 bit precision at the same time") + + if hasattr(self.lora_target_modules, "__len__") and len(self.lora_target_modules) == 1: + self.lora_target_modules = self.lora_target_modules[0] diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/reward_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/reward_config.py new file mode 100644 index 0000000000000000000000000000000000000000..af36bca3df5e9f79f86248890139b4251f580124 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/reward_config.py @@ -0,0 +1,183 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass, field +from typing import Any + +from .base_config import _BaseConfig + + +@dataclass +class RewardConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`RewardTrainer`]. + + This class includes only the parameters that are specific to Reward training. For a full list of training + arguments, please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this + class may differ from those in [`~transformers.TrainingArguments`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + > Parameters that control the model + + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model` + argument of the [`RewardTrainer`] is provided as a string. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to + [`~transformers.AutoModelForSequenceClassification.from_pretrained`] and + [`~transformers.AutoTokenizer.from_pretrained`]. + chat_template_path (`str`, *optional*): + If specified, sets the model's chat template. This can either be the path to a tokenizer (local directory + or Hugging Face Hub model) or a direct path to a Jinja template file. When using a Jinja file, you must + ensure that any special tokens referenced in the template are added to the tokenizer and that the model's + embedding layer is resized accordingly. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. + + > Parameters that control the data preprocessing + + dataset_num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + eos_token (`str`, *optional*): + Token used to indicate the end of a turn or sequence. If `None`, it defaults to + `processing_class.eos_token`. + max_length (`int` or `None`, *optional*, defaults to `1024`): + Maximum length of the tokenized sequence. Samples are filtered out if either chosen or rejected sequence + exceeds this value. If `None`, no filtering is applied. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + + > Parameters that control the training + + center_rewards_coefficient (`float`, *optional*): + Coefficient to incentivize the reward model to output mean-zero rewards (proposed by + https://huggingface.co/papers/2312.09244, Eq. 2). Recommended value: `0.01`. + activation_offloading (`bool`, *optional*, defaults to `False`): + Whether to offload the activations to the CPU. + + > Deprecated parameters + + pad_token: + + + + Parameter `pad_token` is deprecated and will be removed in version v2.0.0. Set `tokenizer.pad_token` + directly and pass it as `processing_class` to the trainer instead. + + + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `1e-4` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=1e-4, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + # Parameters that control the model + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of " + "the `RewardTrainer` is provided as a string." + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. " + "Forwarded to `AutoModelForSequenceClassification.from_pretrained` and `AutoTokenizer.from_pretrained`." + }, + ) + chat_template_path: str | None = field( + default=None, + metadata={ + "help": "If specified, sets the model's chat template. This can either be the path to a tokenizer (local " + "directory or Hugging Face Hub model) or a direct path to a Jinja template file. When using a Jinja file, " + "you must ensure that any special tokens referenced in the template are added to the tokenizer and " + "that the model's embedding layer is resized accordingly." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the model."}, + ) + + # Parameters that control the data preprocessing + dataset_num_proc: int | None = field( + default=None, + metadata={"help": "Number of processes to use for processing the dataset."}, + ) + eos_token: str | None = field( + default=None, + metadata={ + "help": "Token used to indicate the end of a turn or sequence. If `None`, it defaults to `processing_class.eos_token`." + }, + ) + max_length: int | None = field( + default=1024, + metadata={ + "help": "Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from " + "the right. If `None`, no truncation is applied." + }, + ) + pad_to_multiple_of: int | None = field( + default=None, + metadata={"help": "If set, the sequences will be padded to a multiple of this value."}, + ) + + # Parameters that control the training + center_rewards_coefficient: float | None = field( + default=None, + metadata={ + "help": "Coefficient to incentivize the reward model to output mean-zero rewards (proposed by " + "https://huggingface.co/papers/2312.09244, Eq. 2). Recommended value: `0.01`." + }, + ) + activation_offloading: bool = field( + default=False, + metadata={"help": "Whether to offload the activations to the CPU."}, + ) + + # Deprecated parameters + pad_token: str | None = field( + default=None, + metadata={ + "help": "Deprecated. Set `tokenizer.pad_token` directly and pass it as `processing_class` to the trainer instead." + }, + ) + + def __post_init__(self): + super().__post_init__() + if self.pad_token is not None: + warnings.warn( + "`pad_token` is deprecated and will be removed in v2.0.0. " + "Set `tokenizer.pad_token` directly and pass it as `processing_class` to the trainer instead.", + FutureWarning, + stacklevel=3, + ) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/reward_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/reward_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..a10d435cd8ce87385f410bcd93345cd0c9536976 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/reward_trainer.py @@ -0,0 +1,757 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import contextlib +import json +import logging +import os +import re +import warnings +from collections import defaultdict +from collections.abc import Callable +from contextlib import contextmanager +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import torch +import torch.nn as nn +import transformers +from accelerate import PartialState +from accelerate.logging import get_logger +from accelerate.utils import is_peft_model +from datasets import Dataset, IterableDataset +from packaging.version import Version +from transformers import ( + AutoModelForSequenceClassification, + AutoTokenizer, + DataCollator, + PreTrainedModel, + PreTrainedTokenizerBase, + TrainerCallback, + set_seed, +) +from transformers.data.data_collator import DataCollatorMixin +from transformers.modeling_layers import GenericForSequenceClassification +from transformers.trainer_utils import EvalPrediction +from transformers.utils import is_peft_available + +from ..chat_template_utils import clone_chat_template +from ..data_utils import is_conversational +from ..models import get_act_offloading_ctx_manager +from .base_trainer import _BaseTrainer +from .reward_config import RewardConfig +from .utils import create_model_from_path, disable_dropout_in_model, get_config_model_id, pad + + +if is_peft_available(): + import peft + from peft import PeftConfig, PeftModel, get_peft_model + + +logger = get_logger(__name__) + + +# Loading a CausalLM checkpoint into AutoModelForSequenceClassification triggers harmless warnings: +# - MISSING score.weight : the new seq-clf head was not in the checkpoint and is randomly initialized. +# - UNEXPECTED lm_head.weight: the causal LM head is in the checkpoint but absent from seq-clf (>= 4.57.0 only). +# Both are expected consequences of intentional cross-architecture loading. We suppress them to avoid +# confusing users. + + +# Old approach using logging filter (for transformers < 4.57.0) +# Note: in transformers < 4.57.0, only the MISSING score.weight warning is emitted; lm_head.weight is not reported. +@contextmanager +def _suppress_seqcls_cross_arch_keys(logger: logging.Logger): + pattern = re.compile( + r"^Some weights of \S+ were not initialized from the model checkpoint at \S+ and are newly initialized: " + r"\[.*\]\nYou should probably TRAIN this model on a down-stream task to be able to use it for predictions and " + r"inference\.$" + ) + + class _Filter(logging.Filter): + def filter(self, record: logging.LogRecord) -> bool: + return not pattern.search(record.getMessage()) + + f = _Filter() + logger.addFilter(f) + try: + yield + finally: + logger.removeFilter(f) + + +# New approach using scoped override (for transformers >= 4.57.0) +@contextmanager +def _ignore_seqcls_cross_arch_keys(): + # Scoped override: ignore the expected seq-clf head key (newly added) and the causal LM head + # key (present in the checkpoint but absent from seq-clf). + old_missing = getattr(GenericForSequenceClassification, "_keys_to_ignore_on_load_missing", None) + old_unexpected = getattr(GenericForSequenceClassification, "_keys_to_ignore_on_load_unexpected", None) + + merged_missing = list(old_missing) if old_missing is not None else [] + if r"^score\.weight$" not in merged_missing: + merged_missing.append(r"^score\.weight$") + + merged_unexpected = list(old_unexpected) if old_unexpected is not None else [] + if r"^lm_head\." not in merged_unexpected: + merged_unexpected.append(r"^lm_head\.") + + GenericForSequenceClassification._keys_to_ignore_on_load_missing = merged_missing + GenericForSequenceClassification._keys_to_ignore_on_load_unexpected = merged_unexpected + try: + yield + finally: + GenericForSequenceClassification._keys_to_ignore_on_load_missing = old_missing + GenericForSequenceClassification._keys_to_ignore_on_load_unexpected = old_unexpected + + +# Version-aware wrapper that chooses the appropriate approach +@contextmanager +def suppress_seqcls_warning(): + # Use the new approach for transformers >= 4.57.0, old approach for earlier versions + # The old approach is needed for 4.56.2 to avoid meta tensor issues with device_map=None + if Version(transformers.__version__) >= Version("4.57.0"): + with _ignore_seqcls_cross_arch_keys(): + yield + else: + # Get the transformers logger + transformers_logger = logging.getLogger("transformers.modeling_utils") + with _suppress_seqcls_cross_arch_keys(transformers_logger): + yield + + +def get_dataset_column_names(dataset: Dataset | IterableDataset) -> list[str]: + return list(next(iter(dataset)).keys()) if dataset.column_names is None else dataset.column_names + + +@dataclass +class DataCollatorForPreference(DataCollatorMixin): + """ + Data collator used for preference data. Inputs are dynamically padded to the maximum length of a batch. + + This collator expects each example in the input list to be a dictionary containing the `"chosen_ids"` and + `"rejected_ids"` keys. The collator returns a dictionary containing the following keys: + - `"input_ids"`: Tensor of input IDs, padded to the maximum length of the batch. The first half of the batch + corresponds to the `"chosen_ids"` and the second half to the `"rejected_ids"`. + - `"attention_mask"`: Tensor of attention mask, padded to the maximum length of the batch. + + Optionally, the examples can contain a `"margin"` key, in which case the returned dictionary will also contain a + `"margin"` key with a tensor of margins. + + Args: + pad_token_id (`int`): + Token ID to use for padding. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + return_tensors (`str`, *optional*, defaults to `"pt"`): + Type of Tensor to return. Only `"pt"` is currently supported. + + Examples: + ```python + >>> from trl.trainer.reward_trainer import DataCollatorForPreference + + >>> collator = DataCollatorForPreference(pad_token_id=0) + >>> examples = [ + ... {"chosen_ids": [1, 2, 3], "rejected_ids": [4, 5]}, + ... {"chosen_ids": [6, 7], "rejected_ids": [8]}, + ... ] + >>> collator(examples) + {'input_ids': tensor([[1, 2, 3], + [6, 7, 0], + [4, 5, 0], + [8, 0, 0]]), + 'attention_mask': tensor([[1, 1, 1], + [1, 1, 0], + [1, 1, 0], + [1, 0, 0]])} + + >>> examples = [ + ... {"chosen_ids": [1, 2, 3], "rejected_ids": [4, 5], "margin": 0.5}, + ... {"chosen_ids": [6, 7], "rejected_ids": [8], "margin": 0.0}, + ... ] + >>> collator(examples) + {'input_ids': tensor([[1, 2, 3], + [6, 7, 0], + [4, 5, 0], + [8, 0, 0]]), + 'attention_mask': tensor([[1, 1, 1], + [1, 1, 0], + [1, 1, 0], + [1, 0, 0]]), + 'margin': tensor([0.5, 0.0])} + ``` + """ + + pad_token_id: int + pad_to_multiple_of: int | None = None + return_tensors: str = "pt" + + def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + # Convert to tensor + chosen_ids = [torch.tensor(example["chosen_ids"]) for example in examples] + rejected_ids = [torch.tensor(example["rejected_ids"]) for example in examples] + if "margin" in examples[0]: + margins = torch.tensor([example["margin"] for example in examples], dtype=torch.float) + input_ids = chosen_ids + rejected_ids + attention_mask = [torch.ones_like(ids) for ids in input_ids] + + output = {} + + # Pad + output["input_ids"] = pad( + input_ids, + padding_value=self.pad_token_id, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + output["attention_mask"] = pad( + attention_mask, + padding_value=0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + if "margin" in examples[0]: + output["margin"] = margins + return output + + +class RewardTrainer(_BaseTrainer): + """ + Trainer for Outcome-supervised Reward Models (ORM). + + This class is a wrapper around the [`~transformers.Trainer`] class and inherits all of its attributes and methods. + + Example: + + ```python + >>> from trl import RewardTrainer + >>> from datasets import load_dataset + + >>> dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") + + >>> trainer = RewardTrainer( + ... model="Qwen/Qwen2.5-0.5B-Instruct", + ... train_dataset=dataset, + ... ) + >>> trainer.train() + ``` + + Args: + model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]): + Model to be trained. Can be either: + + - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using `AutoModelForSequenceClassification.from_pretrained` with the keyword arguments in + `args.model_init_kwargs`. + - A sequence classification [`~transformers.PreTrainedModel`] object. + - A sequence classification [`~peft.PeftModel`] object. + args ([`RewardConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + data_collator ([`~transformers.DataCollator`], *optional*): + Function to use to form a batch from a list of elements of the processed `train_dataset` or `eval_dataset`. + Will default to [`~trainer.reward_trainer.DataCollatorForPreference`]. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + Dataset to use for training. This trainer supports [preference](#preference) type (both implicit and + explicit prompt). The format of the samples can be either: + + - [Standard](dataset_formats#standard): Each sample contains plain text. + - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role + and content). + + The trainer also supports processed datasets (tokenized) as long as they contain `chosen_ids` and + `rejected_ids` fields. + eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`): + Dataset to use for evaluation. It must meet the same requirements as `train_dataset`. + processing_class ([`~transformers.PreTrainedTokenizerBase`], *optional*): + Tokenizer used to process the data. If `None`, the tokenizer is loaded from the model's name with + [`~transformers.AutoTokenizer.from_pretrained`]. A padding token, `processing_class.pad_token`, must be + set. If the processing class has not set a padding token, `processing_class.eos_token` will be used as the + default. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function that will be used to compute metrics at evaluation. Must take a + [`~transformers.EvalPrediction`] and return a dictionary string to metric values. When passing + [`RewardConfig`] with `batch_eval_metrics` set to `True`, your `compute_metrics` function must take a + boolean `compute_result` argument. This will be triggered after the last eval batch to signal that the + function needs to calculate and return the global summary statistics rather than accumulating the + batch-level statistics. + callbacks (list of [`~transformers.TrainerCallback`], *optional*): + List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed + in [here](https://huggingface.co/docs/transformers/main_classes/callback). + + If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`] + method. + optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`): + A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your + model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`. + optimizer_cls_and_kwargs (`tuple[Type[torch.optim.Optimizer], Dict[str, Any]]`, *optional*): + A tuple containing the optimizer class and keyword arguments to use. Overrides `optim` and `optim_args` in + `args`. Incompatible with the `optimizers` argument. + + Unlike `optimizers`, this argument avoids the need to place model parameters on the correct devices before + initializing the Trainer. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`, *optional*): + A function that preprocess the logits right before caching them at each evaluation step. Must take two + tensors, the logits and the labels, and return the logits once processed as desired. The modifications made + by this function will be reflected in the predictions received by `compute_metrics`. + + Note that the labels (second parameter) will be `None` if the dataset does not have them. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration used to wrap the model. If `None`, the model is not wrapped. Note that if the loaded + model is a causal LM, it's highly recommended to set `modules_to_save=["score"]` in the PEFT configuration + to ensure that the reward head is properly trained. + """ + + _tag_names = ["trl", "reward-trainer"] + _name = "Reward" + _template_file = "rm_model_card.md" + + def __init__( + self, + model: "str | PreTrainedModel | PeftModel", + args: RewardConfig | None = None, + data_collator: DataCollator | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | None = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + optimizer_cls_and_kwargs: tuple[type[torch.optim.Optimizer], dict[str, Any]] | None = None, + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + peft_config: "PeftConfig | None" = None, + ): + # Args + if args is None: + model_name = model if isinstance(model, str) else get_config_model_id(model.config) + model_name = model_name.split("/")[-1] + args = RewardConfig(f"{model_name}-Reward") + + if train_dataset is None: + raise ValueError("`train_dataset` is required") + elif isinstance(train_dataset, IterableDataset): + # IterableDataset requires dispatch_batches=False because Accelerate's dispatch mode may try to concatenate + # batches from multiple processes, leading to mismatch errors. + if args.accelerator_config.dispatch_batches is True: + logger.warning( + "You are using an `IterableDataset` for training with `dispatch_batches=True`. `dispatch_batches` " + "is forced to `False` when using an `IterableDataset`. To remove this warning, unset " + "`dispatch_batches` in `RewardConfig` or set it to `False`." + ) + args.accelerator_config.dispatch_batches = False + + # Model + # As AutoModelForSequenceClassification.from_pretrained() will add a random head for the model, set_seed must + # be done before loading the model to ensure reproducibility. + set_seed(args.seed) + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model_init_kwargs["num_labels"] = 1 # the only output of the model is the reward score + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + with suppress_seqcls_warning(): + model = create_model_from_path(model, AutoModelForSequenceClassification, **model_init_kwargs) + else: + if args.model_init_kwargs is not None: + logger.warning( + "You passed `model_init_kwargs` to the `RewardConfig`, but your model is already instantiated. " + "The `model_init_kwargs` will be ignored." + ) + # Validate that the model has num_labels = 1 (required for reward models) + if getattr(model.config, "num_labels", None) != 1: + raise ValueError( + f"The model has `num_labels={model.config.num_labels}`, but reward models require `num_labels=1` " + "to output a single scalar reward per sequence. Please instantiate your model with `num_labels=1` " + "or pass a model name as a string to have it configured automatically." + ) + # Non-quantized models do not have the `is_loaded_in_{8,4}bit` attributes, whereas quantized models do + _is_quantized_model = getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False) + + # Processing class + if processing_class is None: + processing_class = AutoTokenizer.from_pretrained( + get_config_model_id(model.config), trust_remote_code=args.trust_remote_code + ) + + # Handle pad token for processors or tokenizers + if args.eos_token is not None: + if args.eos_token not in processing_class.get_vocab(): + raise ValueError( + f"The specified `eos_token` ('{args.eos_token}') is not found in the vocabulary of the given " + f"`processing_class` ({processing_class.__class__.__name__}). Ensure that the `eos_token` exists " + "in the vocabulary before using it as an EOS token." + ) + processing_class.eos_token = args.eos_token + + if args.chat_template_path is not None: + if os.path.isfile(args.chat_template_path) and args.chat_template_path.endswith((".jinja", ".j2")): + with open(args.chat_template_path, encoding="utf-8") as chat_template_file: + processing_class.chat_template = chat_template_file.read() + added_tokens = [] + else: + model, processing_class, added_tokens = clone_chat_template( + model, processing_class, args.chat_template_path + ) + else: + added_tokens = [] + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge " + "and unload the existing adapter, save the resulting base model, and then pass that base model along " + "with the new `peft_config` to the trainer." + ) + if added_tokens: + # Ensure that the added tokens are trainable + if peft_config.trainable_token_indices is None: + peft_config.trainable_token_indices = {"embed_tokens": added_tokens} + elif "embed_tokens" not in peft_config.trainable_token_indices: + peft_config.trainable_token_indices["embed_tokens"] = added_tokens + else: + peft_config.trainable_token_indices["embed_tokens"].extend(added_tokens) + # Ensure that the lm_head is trainable + if peft_config.modules_to_save is None or "lm_head" not in peft_config.modules_to_save: + logger.warning( + "Cloning chat template added new tokens to the tokenizer, but 'lm_head' is not in PEFT's " + "`modules_to_save`. As a result, the model may not learn to generate outputs with these new " + "tokens, leading to degraded generation quality. To fix this, add " + "`modules_to_save=['lm_head']` to your PEFT configuration." + ) + + if peft_config.modules_to_save is None: + peft_config.modules_to_save = ["lm_head"] + else: + peft_config.modules_to_save.append("lm_head") + # Create PEFT model + # ZeRO-3 + PEFT for non-quantized models: + # - PEFT's default autocast_adapter_dtype=True upcasts LoRA adapter params to fp32 even when the base model is bf16. + # - ZeRO-3's _allgather_params_coalesced allocates output buffers using the dtype of the first persistent parameter, + # so mixed-dtype persistent_parameters (bf16 base + fp32 LoRA) cause a TypeError on the first optimizer step. + # - Passing autocast_adapter_dtype=False keeps adapter params in the base model dtype (bf16), fixing the mismatch. + # - This is safe: the fp32 upcast is a QLoRA-specific concern (low-bit quantized base models), not needed for + # non-quantized bf16 training. + # - See: + # - TRL issue: https://github.com/huggingface/trl/issues/6089 + # - Upstream issue: https://github.com/deepspeedai/DeepSpeed/issues/8072 + # - autocast_adapter_dtype was introduced in PEFT 0.12.0; before, no upcast existed: no need to pass the kwarg + get_peft_model_kwargs = {} + if ( + args.deepspeed_plugin is not None + and args.deepspeed_plugin.zero_stage == 3 + and not _is_quantized_model + and Version(peft.__version__) >= Version("0.12.0") + ): + get_peft_model_kwargs["autocast_adapter_dtype"] = False + model = get_peft_model(model, peft_config, **get_peft_model_kwargs) + + # When using gradient checkpointing with PEFT, we need to enable input gradients. transformers.Trainer normally + # handles this, but a bug currently prevents it; see https://github.com/huggingface/transformers/issues/42489 + if is_peft_model(model) and args.gradient_checkpointing: + model.enable_input_require_grads() + + # When using QLoRA, the PEFT adapter weights are converted to bf16 to follow the recommendations from the + # original paper (see https://huggingface.co/papers/2305.14314, paragraph 3). Normally, this can be done by + # passing `autocast_adapter_dtype=False` to `get_peft_model`, but this option is not yet supported for + # quantized models. See: https://github.com/huggingface/peft/issues/2889 + if _is_quantized_model: + for param in model.parameters(): + if param.requires_grad: + param.data = param.data.to(torch.bfloat16) + + # Disable dropout in the model + if args.disable_dropout: + disable_dropout_in_model(model) + + # Pad token (needed for SequenceClassification models) + # If not provided, use the one from the processing class or the eos token if the processing class does not have + # a pad token. + pad_token = args.pad_token or processing_class.pad_token or processing_class.eos_token + if pad_token not in processing_class.get_vocab(): + raise ValueError( + f"The specified `pad_token` ('{pad_token}') is not found in the vocabulary of the given " + f"`processing_class` ({processing_class.__class__.__name__}). Ensure that the `pad_token` exists " + "in the vocabulary before using it as a padding token." + ) + processing_class.pad_token = pad_token + # SequenceClassification models need `config.pad_token_id` to locate the last non-pad token. + model.config.pad_token_id = processing_class.pad_token_id + + # Data collator + if data_collator is None: + data_collator = DataCollatorForPreference( + pad_token_id=processing_class.pad_token_id, + pad_to_multiple_of=args.pad_to_multiple_of, + ) + + # Dataset + train_dataset = self._prepare_dataset(train_dataset, processing_class, args, "train") + if eval_dataset is not None: + if isinstance(eval_dataset, dict): + eval_dataset = { + key: self._prepare_dataset(dataset, processing_class, args, key) + for key, dataset in eval_dataset.items() + } + else: + eval_dataset = self._prepare_dataset(eval_dataset, processing_class, args, "eval") + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + optimizer_cls_and_kwargs=optimizer_cls_and_kwargs, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # During evaluation, Trainer calls compute_loss() only if can_return_loss is True and label_names is empty. + self.can_return_loss = True + self.label_names = [] + + # Initialize activation offloading context + if self.args.activation_offloading: + self.maybe_activation_offload_context = get_act_offloading_ctx_manager(model=self.model) + else: + self.maybe_activation_offload_context = contextlib.nullcontext() + + # Initialize the metrics + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + self._total_train_tokens = 0 + + # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the + # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set + # self.model_accepts_loss_kwargs to False to enable scaling. + self.model_accepts_loss_kwargs = False + + # Add tags to the model + self.model.add_model_tags(self._tag_names) + + def _prepare_dataset( + self, + dataset: Dataset | IterableDataset, + processing_class: PreTrainedTokenizerBase, + args: RewardConfig, + dataset_name: str, + ) -> Dataset | IterableDataset: + # If the dataset is already preprocessed (tokenized), skip the processing steps. + column_names = get_dataset_column_names(dataset) + is_processed = "chosen_ids" in column_names and "rejected_ids" in column_names + has_legacy_processed_columns = "chosen_input_ids" in column_names and "rejected_input_ids" in column_names + if has_legacy_processed_columns and not is_processed: + warnings.warn( + "Detected legacy dataset columns `chosen_input_ids`/`rejected_input_ids`; they are deprecated and " + "will not be supported in v1. Please migrate to `chosen_ids`/`rejected_ids`.", + FutureWarning, + stacklevel=2, + ) + dataset = dataset.rename_column("chosen_input_ids", "chosen_ids") + dataset = dataset.rename_column("rejected_input_ids", "rejected_ids") + is_processed = True + + # Build the kwargs for the `map` function + map_kwargs = {} + if isinstance(dataset, Dataset): # IterableDataset does not support num_proc + map_kwargs["num_proc"] = args.dataset_num_proc + + with PartialState().main_process_first(): + if not is_processed: + # Add EOS token if needed: non-conversational only + first_example = next(iter(dataset)) + if not is_conversational(first_example): + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Adding EOS to {dataset_name} dataset" + + def add_eos(example, eos_token): + if not example["chosen"].endswith(eos_token): + example["chosen"] = example["chosen"] + eos_token + if "rejected" in example and not example["rejected"].endswith(eos_token): + example["rejected"] = example["rejected"] + eos_token + return example + + dataset = dataset.map( + add_eos, + fn_kwargs={"eos_token": processing_class.eos_token}, + **map_kwargs, + ) + + # Tokenize the dataset + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Tokenizing {dataset_name} dataset" + + def tokenize_fn(example, processing_class): + tools = example.get("tools") + tools = json.loads(tools) if isinstance(tools, str) else tools + if "prompt" in example: # explicit prompt case + example["chosen"] = example["prompt"] + example["chosen"] + example["rejected"] = example["prompt"] + example["rejected"] + + if is_conversational(example): + chosen_ids = processing_class.apply_chat_template( + example["chosen"], + tools=tools, + return_dict=True, + **example.get("chat_template_kwargs", {}), + )["input_ids"] + rejected_ids = processing_class.apply_chat_template( + example["rejected"], + tools=tools, + return_dict=True, + **example.get("chat_template_kwargs", {}), + )["input_ids"] + output = {"chosen_ids": chosen_ids, "rejected_ids": rejected_ids} + else: + output = { + "chosen_ids": processing_class(text=example["chosen"])["input_ids"], + "rejected_ids": processing_class(text=example["rejected"])["input_ids"], + } + return output + + dataset = dataset.map(tokenize_fn, fn_kwargs={"processing_class": processing_class}, **map_kwargs) + + # Filter samples that are longer than `max_length` + if args.max_length is not None: + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Filtering {dataset_name} >{args.max_length} tokens" + dataset = dataset.filter( + lambda example: len(example["chosen_ids"]) <= args.max_length + and len(example["rejected_ids"]) <= args.max_length, + **map_kwargs, + ) + + return dataset + + def _set_signature_columns_if_needed(self): + # If `self.args.remove_unused_columns` is True, non-signature columns are removed. + # By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids" + # and "attention_mask"). + if self._signature_columns is None: + self._signature_columns = ["chosen_ids", "rejected_ids", "margin"] + + def evaluate( + self, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + ignore_keys: list[str] | None = None, + metric_key_prefix: str = "eval", + ) -> dict[str, float]: + # When a dataset is passed directly to `evaluate` (e.g. a held-out test set), preprocess it the same way + # `__init__` does, so that `evaluate` accepts the same dataset types as the trainer. `_prepare_dataset` is + # idempotent: it skips datasets that are already tokenized. A `str` selects a dataset that was already prepared + # at init time, so it's left untouched. + if eval_dataset is not None and not isinstance(eval_dataset, str): + if isinstance(eval_dataset, dict): + eval_dataset = { + key: self._prepare_dataset(dataset, self.processing_class, self.args, key) + for key, dataset in eval_dataset.items() + } + else: + eval_dataset = self._prepare_dataset(eval_dataset, self.processing_class, self.args, "eval") + return super().evaluate( + eval_dataset=eval_dataset, ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix + ) + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + mode = "train" if self.model.training else "eval" + + # If not set, defaults from model config and may warn since cache isn't compatible with gradient checkpointing + inputs["use_cache"] = False + outputs = model(**inputs) + + # Split the rewards into chosen and rejected + rewards_chosen, rewards_rejected = torch.chunk(outputs.logits.squeeze(-1), chunks=2) + + # Calculate loss, optionally modulate with margin + if "margin" in inputs: + loss = -nn.functional.logsigmoid(rewards_chosen - rewards_rejected - inputs["margin"]).mean() + else: + loss = -nn.functional.logsigmoid(rewards_chosen - rewards_rejected).mean() + + if self.args.center_rewards_coefficient is not None: + loss += self.args.center_rewards_coefficient * torch.mean((rewards_chosen + rewards_rejected) ** 2) + + if mode == "train": + num_tokens_in_batch = self.accelerator.gather_for_metrics(inputs["attention_mask"].sum()).sum().item() + self._total_train_tokens += num_tokens_in_batch + self._metrics[mode]["num_tokens"] = [self._total_train_tokens] + + # Compute min, mean, max, accuracy and margin + with torch.no_grad(): + all_rewards = self.accelerator.gather(outputs.logits) + self._metrics[mode]["min_reward"].append(all_rewards.min().item()) + self._metrics[mode]["mean_reward"].append(all_rewards.mean().item()) + self._metrics[mode]["max_reward"].append(all_rewards.max().item()) + + mean_accuracy = (rewards_chosen > rewards_rejected).float().mean() + mean_accuracy = self.accelerator.gather_for_metrics(mean_accuracy).mean().item() + self._metrics[mode]["accuracy"].append(mean_accuracy) + + mean_margin = (rewards_chosen - rewards_rejected).mean() + mean_margin = self.accelerator.gather_for_metrics(mean_margin).mean() + self._metrics[mode]["margin"].append(mean_margin.item()) + + return (loss, outputs) if return_outputs else loss + + # Override training step to add activation offloading context. + def training_step(self, *args, **kwargs): + with self.maybe_activation_offload_context: + return super().training_step(*args, **kwargs) + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} # average the metrics + + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/rloo_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/rloo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..5cd2bb565ac2d8f600d5113cfa00bcddaaf9b952 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/rloo_config.py @@ -0,0 +1,668 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass, field +from typing import Any + +from .base_config import _BaseConfig + + +@dataclass +class RLOOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`RLOOTrainer`]. + + This class includes only the parameters that are specific to RLOO training. For a full list of training arguments, + please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may + differ from those in [`~transformers.TrainingArguments`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + > Parameters that control the model and reference model + + model_init_kwargs (`str`, `dict[str, Any]`, *optional*): + Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model` + argument of the [`RLOOTrainer`] is provided as a string. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to + [`~transformers.AutoModelForCausalLM.from_pretrained`] and + [`~transformers.AutoProcessor.from_pretrained`]. Also applied to reward-model and reward-tokenizer loads. + router_aux_loss_coef (`float`, *optional*, defaults to `0.001`): + Coefficient of the load-balancing auxiliary loss. Only has an effect when training a Mixture-of-Experts + (MoE) model; for other models it does nothing. The auxiliary loss is added to the training loss with this + weight. Set to `0.0` to disable it. + disable_dropout (`bool`, *optional*, defaults to `False`): + Whether to disable dropout in the model. This is useful for training with a reference model, as it prevents + the model from generating different logprobs for the same input. + + > Parameters that control the data preprocessing + + remove_unused_columns (`bool`, *optional*, defaults to `False`): + Whether to only keep the column `"prompt"` in the dataset. If you use a custom reward function that + requires any column other than `"prompts"` and `"completions"`, you should keep this to `False`. + num_generations (`int`, *optional*, defaults to `2`): + Number of generations per prompt to sample. The effective batch size (num_processes * per_device_batch_size + * gradient_accumulation_steps) must be evenly divisible by this value. + num_generations_eval (`int` or `None`, *optional*): + Number of generations to sample during evaluation. This allows using fewer generations during evaluation to + save computation. If `None`, uses the value of `num_generations`. + max_completion_length (`int` or `None`, *optional*, defaults to `256`): + Maximum length of the generated completion. + ds3_gather_for_generation (`bool`, *optional*, defaults to `True`): + This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation, + improving generation speed. However, disabling this option allows training models that exceed the VRAM + capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible + with vLLM generation. + shuffle_dataset (`bool`, *optional*, defaults to `True`): + Whether to shuffle the training dataset. + pad_to_multiple_of (`int`, *optional*): + If set, the prompts ids and completions ids will be padded to a multiple of this value. + + > Parameters that control generation + + generation_batch_size (`int`, *optional*): + Batch size to use for generation. If `None`, it defaults to the effective training batch size: + `per_device_train_batch_size * num_processes * steps_per_generation`. In other words, there is one + generation batch processed per optimization step. Mutually exclusive with `steps_per_generation`. + steps_per_generation (`int`, *optional*): + Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`. Mutually exclusive + with `generation_batch_size`. + temperature (`float`, defaults to `1.0`): + Temperature for sampling. The higher the temperature, the more random the completions. + top_p (`float`, *optional*, defaults to `1.0`): + Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to + `1.0` to consider all tokens. + top_k (`int`, *optional*, defaults to `0`): + Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is + disabled and all tokens are considered. + min_p (`float`, *optional*): + Minimum token probability, which will be scaled by the probability of the most likely token. It must be a + value between `0.0` and `1.0`. Typical values are in the `0.01-0.2` range. + generation_kwargs (`dict[str, Any]`, *optional*): + Additional keyword arguments to pass to [`~transformers.GenerationConfig`] (if using transformers) or + `SamplingParams` (if using vLLM) when sampling completions. This can be used to further customize the + generation behavior, such as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that conflict + with the other generation parameters (like `min_p`, `top_p`, etc.), they will override them. + chat_template_kwargs (`dict[str, Any]`, *optional*): + Additional keyword arguments to pass to the `apply_chat_template` function when generating completions. + repetition_penalty (`float`, *optional*, defaults to `1.0`): + Float that penalizes new tokens based on whether they appear in the prompt and the generated text so far. + Values > `1.0` encourage the model to use new tokens, while values < `1.0` encourage the model to repeat + tokens. + cache_implementation (`str`, *optional*): + Implementation of the cache method for faster generation when `use_vllm` is set to `False`. + + > Parameters that control generation acceleration powered by vLLM + + use_vllm (`bool`, *optional*, defaults to `False`): + Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for generation + instead of the default model.generate(). Requires `vllm` to be installed. + vllm_mode (`str`, *optional*, defaults to `"colocate"`): + Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `"server"` or + `"colocate"`. + + - `"server"`: The trainer will send generation requests to a separate vLLM server. Make sure a TRL vLLM + server is running (start with `trl vllm-serve`). + - `"colocate"`: vLLM will run in the same process and share the training GPUs. This avoids the need for a + separate server but may cause resource contention with training. + vllm_model_impl (`str`, *optional*, defaults to `"vllm"`): + Model implementation to use for vLLM. Must be one of `"transformers"` or `"vllm"`. `"transformers"`: Use + the `transformers` backend for model implementation. `"vllm"`: Use the `vllm` library for model + implementation. + vllm_structured_outputs_regex (`str`, *optional*): + Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled. + + > Parameters that control the vLLM server (only used when `vllm_mode` is `"server"`) + + vllm_server_base_url (`str`, *optional*): + Base URL for the vLLM server (e.g., `"http://localhost:8000"`). If provided, `vllm_server_host` and + `vllm_server_port` are ignored. + vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`): + Host of the vLLM server to connect to. Ignored if `vllm_server_base_url` is provided. + vllm_server_port (`int`, *optional*, defaults to `8000`): + Port of the vLLM server to connect to. Ignored if `vllm_server_base_url` is provided. + vllm_server_timeout (`float`, *optional*, defaults to `240.0`): + Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up after the + timeout, a `ConnectionError` is raised. + vllm_group_port (`int`, *optional*, defaults to `51216`): + Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port + is occupied, there is no need to change it. + + > Parameters that control colocated vLLM execution (only used when `vllm_mode` is `"colocate"`) + + vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.3`): + Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set to + `"colocate"`. If you are using `vllm_mode="server"`, this parameter must be passed separately when + launching the vLLM server via the `--vllm_gpu_memory_utilization` flag. + vllm_max_model_length (`int`, *optional*): + Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus + `max_completion_length`; if omitted, it is inferred from the model config. + vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`): + Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set to + `"colocate"`. If you are using `vllm_mode="server"`, this parameter must be passed separately when + launching the vLLM server via the `--vllm_tensor_parallel_size` flag. + vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`): + Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but + waking the engine adds host–device transfer latency. + + > Parameters that control generation acceleration powered by transformers continuous batching + + use_transformers_continuous_batching (`bool`, *optional*, defaults to `False`): + Whether to use transformers' continuous batching engine for generating completions. Requires + `transformers>=5.8.0`. + transformers_continuous_batching_config (`dict`, *optional*): + Keyword arguments for [`~transformers.generation.ContinuousBatchingConfig`]. + + > Parameters that control the training + + beta (`float`, *optional*, defaults to `0.05`): + KL coefficient. If `0.0`, the reference model is not loaded, reducing memory usage and improving training + speed. + num_iterations (`int`, *optional*, defaults to `1`): + Number of iterations per batch (denoted as μ in the algorithm). + epsilon (`float`, *optional*, defaults to `0.2`): + Epsilon value for clipping. + epsilon_high (`float`, *optional*): + Upper-bound epsilon value for clipping. If not specified, it defaults to the same value as the lower-bound + specified in argument `epsilon`. Paper [DAPO](https://huggingface.co/papers/2503.14476) recommends `0.28`. + reward_weights (`list[float]`, *optional*): + Weights for each reward function. Must match the number of reward functions. If `None`, all rewards are + weighted equally with weight `1.0`. + normalize_advantages (`bool`, *optional*, defaults to `False`): + Whether to normalize advantages. Normalization is done per generation batch to have mean `0.0` and standard + deviation of `1.0`. + reward_clip_range (`tuple[float, float]`, *optional*): + Clip range for rewards as (min, max). If `None`, no clipping is applied. + mask_truncated_completions (`bool`, *optional*, defaults to `False`): + When enabled, truncated completions are excluded from the loss calculation, preventing them from being + incorrectly penalized and introducing noise during training. According to the + [DAPO](https://huggingface.co/papers/2503.14476) paper, this is a good practice for training stability. + sync_ref_model (`bool`, *optional*, defaults to `False`): + Whether to synchronize the reference model with the active model every `ref_model_sync_steps` steps, using + the `ref_model_mixup_alpha` parameter. This synchronization originates from the + [TR-DPO](https://huggingface.co/papers/2404.09656) paper. + ref_model_mixup_alpha (`float`, *optional*, defaults to `0.6`): + α parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which controls the mix + between the current policy and the previous reference policy during updates. The reference policy is + updated according to the equation: `π_ref = α * π_θ + (1 - α) * π_ref_prev`. To use this parameter, you + must set `sync_ref_model=True`. + ref_model_sync_steps (`int`, *optional*, defaults to `512`): + τ parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which determines how + frequently the current policy is synchronized with the reference policy. To use this parameter, you must + set `sync_ref_model=True`. + + > Parameters that control the logging + + log_completions (`bool`, *optional*, defaults to `False`): + Whether to log a sample of (prompt, completion) pairs every `logging_steps` steps. If `rich` is installed, + it prints the sample. If `wandb` and/or `trackio` logging is enabled, it logs it to `wandb` and/or + `trackio`. + num_completions_to_print (`int`, *optional*): + Number of completions to print with `rich`. If `None`, all completions are logged. + log_unique_prompts (`bool`, *optional*, defaults to `False`): + Whether to log unique prompts. If `True`, only unique prompts are logged. If `False`, all prompts are + logged. + + > Deprecated parameters + + use_transformers_paged: + + + + Parameter `use_transformers_paged` is deprecated and will be removed in version v2.0.0. Use + `use_transformers_continuous_batching` instead. + + + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `1e-6` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + [ + "model_init_kwargs", + "transformers_continuous_batching_config", + ] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=1e-6, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + # Parameters that control the model and reference model + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `transformers.AutoModelForCausalLM.from_pretrained`, used when the `model` " + "argument of the `RLOOTrainer` is provided as a string." + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. " + "Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoProcessor.from_pretrained`. Also applied to " + "reward-model and reward-tokenizer loads." + }, + ) + router_aux_loss_coef: float = field( + default=0.001, + metadata={ + "help": "Coefficient of the load-balancing auxiliary loss. Only has an effect when training a " + "Mixture-of-Experts (MoE) model; for other models it does nothing. The auxiliary loss is added to the " + "training loss with this weight. Set to `0.0` to disable it." + }, + ) + disable_dropout: bool = field( + default=False, + metadata={ + "help": "Whether to disable dropout in the model. This is useful for training with a reference model, as " + "it prevents the model from generating different logprobs for the same input." + }, + ) + + # Parameters that control the data preprocessing + # The default value remove_unused_columns is overwritten from the parent class, because in RLOO we usually rely on + # additional columns to compute the reward + remove_unused_columns: bool | None = field( + default=False, + metadata={ + "help": "Whether to only keep the column 'prompt' in the dataset. If you use a custom reward function " + "that requires any column other than 'prompts' and 'completions', you should keep this to `False`." + }, + ) + num_generations: int | None = field( + default=2, + metadata={ + "help": "Number of generations to sample. The effective batch size (num_processes * per_device_batch_size " + "* gradient_accumulation_steps) must be evenly divisible by this value." + }, + ) + num_generations_eval: int | None = field( + default=None, + metadata={ + "help": "Number of generations to sample during evaluation. This allows using fewer generations during " + "evaluation to save computation. If `None`, uses the value of `num_generations`." + }, + ) + max_completion_length: int | None = field( + default=256, + metadata={"help": "Maximum length of the generated completion."}, + ) + ds3_gather_for_generation: bool = field( + default=True, + metadata={ + "help": "This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for " + "generation, improving generation speed. However, disabling this option allows training models that " + "exceed the VRAM capacity of a single GPU, albeit at the cost of slower generation. Disabling this option " + "is not compatible with vLLM generation." + }, + ) + shuffle_dataset: bool | None = field( + default=True, + metadata={"help": "Whether to shuffle the training dataset."}, + ) + pad_to_multiple_of: int | None = field( + default=None, + metadata={"help": "If set, the prompts ids and completions ids will be padded to a multiple of this value."}, + ) + + # Parameters that control generation + generation_batch_size: int | None = field( + default=None, + metadata={ + "help": "Batch size to use for generation. If `None`, it defaults to the effective training batch size: " + "`per_device_train_batch_size * num_processes * steps_per_generation`." + }, + ) + steps_per_generation: int | None = field( + default=None, + metadata={"help": "Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`."}, + ) + temperature: float = field( + default=1.0, + metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."}, + ) + top_p: float = field( + default=1.0, + metadata={ + "help": "Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. " + "Set to 1.0 to consider all tokens." + }, + ) + top_k: int = field( + default=0, + metadata={ + "help": "Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, " + "top-k-filtering is disabled and all tokens are considered." + }, + ) + min_p: float | None = field( + default=None, + metadata={ + "help": "Minimum token probability, which will be scaled by the probability of the most likely token. It " + "must be a value between 0.0 and 1.0. Typical values are in the 0.01-0.2 range." + }, + ) + generation_kwargs: dict | None = field( + default=None, + metadata={ + "help": "Additional keyword arguments to pass to `GenerationConfig` (if using transformers) or " + "`SamplingParams` (if using vLLM) when sampling completions. This can be used to further customize the " + "generation behavior, such as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that " + "conflict with the other generation parameters (like `min_p`, `top_p`, etc.), they will override them." + }, + ) + chat_template_kwargs: dict | None = field( + default=None, + metadata={ + "help": "Additional keyword arguments to pass to the `apply_chat_template` function when generating " + "completions." + }, + ) + repetition_penalty: float = field( + default=1.0, + metadata={ + "help": "Float that penalizes new tokens based on whether they appear in the prompt and the generated " + "text so far. Values > 1.0 encourage the model to use new tokens, while values < 1.0 encourage the model " + "to repeat tokens." + }, + ) + cache_implementation: str | None = field( + default=None, + metadata={"help": "Implementation of the cache method for faster generation when use_vllm is set to False."}, + ) + + # Parameters that control generation acceleration powered by vLLM + use_vllm: bool = field( + default=False, + metadata={ + "help": "Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for " + "generation instead of the default model.generate(). Requires `vllm` to be installed." + }, + ) + vllm_mode: str = field( + default="colocate", + metadata={ + "help": "Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `'server'` or " + "`'colocate'`. `'server'`: The trainer will send generation requests to a separate vLLM server. Make sure " + "a TRL vLLM server is running (start with `trl vllm-serve`). `'colocate'`: vLLM will run in the same " + "process and share the training GPUs. This avoids the need for a separate server but may cause resource " + "contention with training." + }, + ) + vllm_model_impl: str = field( + default="vllm", + metadata={ + "help": "Model implementation to use for vLLM. Must be one of `transformers` or `vllm`. `transformers`: " + "Use the `transformers` backend for model implementation. `vllm`: Use the `vllm` library for " + "model implementation." + }, + ) + vllm_enable_sleep_mode: bool = field( + default=False, + metadata={ + "help": "Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory " + "usage low, but waking the engine adds host–device transfer latency." + }, + ) + vllm_structured_outputs_regex: str | None = field( + default=None, + metadata={"help": "Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled."}, + ) + + # Parameters that control the vLLM server (only used when `vllm_mode` is `"server"`) + vllm_server_base_url: str | None = field( + default=None, + metadata={ + "help": "Base URL for the vLLM server (e.g., 'http://localhost:8000'). If provided, `vllm_server_host` " + "and `vllm_server_port` are ignored." + }, + ) + vllm_server_host: str = field( + default="0.0.0.0", + metadata={"help": "Host of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."}, + ) + vllm_server_port: int = field( + default=8000, + metadata={"help": "Port of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."}, + ) + vllm_server_timeout: float = field( + default=240.0, + metadata={ + "help": "Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up " + "after the timeout, a `ConnectionError` is raised." + }, + ) + vllm_group_port: int = field( + default=51216, + metadata={ + "help": "Port number for the weight update group. This is used to communicate with the vLLM server. " + "Unless the port is occupied, there is no need to change it.", + }, + ) + + # Parameters that control colocated vLLM execution (only used when `vllm_mode` is `"colocate"`) + vllm_gpu_memory_utilization: float = field( + default=0.3, + metadata={ + "help": "Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set " + "to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when " + "launching the vLLM server via the `--vllm_gpu_memory_utilization` flag." + }, + ) + vllm_max_model_length: int | None = field( + default=None, + metadata={ + "help": "Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus " + "`max_completion_length`; if omitted, it is inferred from the model config." + }, + ) + vllm_tensor_parallel_size: int = field( + default=1, + metadata={ + "help": "Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set " + "to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when " + "launching the vLLM server via the `--vllm_tensor_parallel_size` flag." + }, + ) + + # Parameters that control the training + beta: float = field( + default=0.05, + metadata={ + "help": "KL coefficient. If `0.0`, the reference model is not loaded, reducing memory usage and improving " + "training speed." + }, + ) + num_iterations: int = field( + default=1, + metadata={"help": "Number of iterations per batch (denoted as μ in the algorithm)."}, + ) + epsilon: float = field( + default=0.2, + metadata={"help": "Epsilon value for clipping."}, + ) + epsilon_high: float | None = field( + default=None, + metadata={ + "help": "Upper-bound epsilon value for clipping. If not specified, it defaults to the same value as the " + "lower-bound specified in argument `epsilon`. Paper DAPO recommends `0.28`." + }, + ) + reward_weights: list[float] | None = field( + default=None, + metadata={ + "help": "Weights for each reward function. Must match the number of reward functions. If `None`, all " + "rewards are weighted equally with weight `1.0`." + }, + ) + normalize_advantages: bool = field( + default=False, + metadata={ + "help": "Whether to normalize advantages. Normalization is done per generation batch to have mean `0.0` " + "and standard deviation of `1.0`." + }, + ) + reward_clip_range: tuple[float, float] | None = field( + default=None, + metadata={"help": "Clip range for rewards as (min, max). If None, no clipping is applied."}, + ) + mask_truncated_completions: bool = field( + default=False, + metadata={ + "help": "When enabled, truncated completions are excluded from the loss calculation, preventing them from " + "being incorrectly penalized and introducing noise during training. According to the DAPO paper, this is " + "a good practice for training stability." + }, + ) + sync_ref_model: bool = field( + default=False, + metadata={ + "help": "Whether to synchronize the reference model with the active model every `ref_model_sync_steps` " + "steps, using the `ref_model_mixup_alpha` parameter." + }, + ) + ref_model_mixup_alpha: float = field( + default=0.6, + metadata={ + "help": "α parameter from the TR-DPO paper, which controls the mix between the current policy and the " + "previous reference policy during updates. The reference policy is updated according to the equation: " + "`π_ref = α * π_θ + (1 - α) * π_ref_prev`. To use this parameter, you must set `sync_ref_model=True`." + }, + ) + ref_model_sync_steps: int = field( + default=512, + metadata={ + "help": "τ parameter from the TR-DPO paper, which determines how frequently the current policy is " + "synchronized with the reference policy. To use this parameter, you must set `sync_ref_model=True`." + }, + ) + + # Parameters that control the logging + log_completions: bool = field( + default=False, + metadata={ + "help": "Whether to log a sample of (prompt, completion) pairs every `logging_steps` steps. If `rich` is " + "installed, it prints the sample. If `wandb` logging is enabled, it logs it to `wandb`." + }, + ) + num_completions_to_print: int | None = field( + default=None, + metadata={"help": "Number of completions to print with `rich`. If `None`, all completions are logged."}, + ) + log_unique_prompts: bool = field( + default=False, + metadata={ + "help": "Whether to log unique prompts. If `True`, only unique prompts are logged. If `False`, all " + "prompts are logged." + }, + ) + + # Parameters that control generation acceleration powered by transformers continuous batching + use_transformers_continuous_batching: bool = field( + default=False, + metadata={ + "help": "Whether to use transformers' continuous batching engine for generating completions. Requires " + "transformers>=5.8.0." + }, + ) + transformers_continuous_batching_config: dict | None = field( + default=None, + metadata={"help": "Keyword arguments for `transformers.generation.ContinuousBatchingConfig`."}, + ) + + # Deprecated parameters + use_transformers_paged: bool = field( + default=False, + metadata={"help": "Deprecated. Use `use_transformers_continuous_batching` instead."}, + ) + + def __post_init__(self): + super().__post_init__() + + if self.use_transformers_paged: + warnings.warn( + "`use_transformers_paged` is deprecated and will be removed in v2.0.0. Use " + "`use_transformers_continuous_batching` instead.", + FutureWarning, + stacklevel=3, + ) + self.use_transformers_continuous_batching = True + + if self.parallelism_config is not None and ( + self.parallelism_config.cp_enabled or self.parallelism_config.sp_enabled + ): + raise ValueError( + "RLOOTrainer does not support sequence-dim parallelism (`parallelism_config.cp_size > 1` or " + "`parallelism_config.sp_size > 1`) yet. RLOO builds model inputs after generation inside the trainer, " + "so Transformers' context-parallel / Ulysses sequence-parallel input sharding cannot be applied to the " + "raw generation batch. Set both `cp_size=1` and `sp_size=1`, or disable `parallelism_config`." + ) + + num_processes = self.world_size + # The current default effective batch size + if self.generation_batch_size is None and self.steps_per_generation is None: + self.steps_per_generation = self.gradient_accumulation_steps + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + elif self.generation_batch_size is not None and self.steps_per_generation is None: + # Just ensure the value is divisible by the global batch size + if self.generation_batch_size % (self.per_device_train_batch_size * num_processes) != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by the global batch size " + f"({self.per_device_train_batch_size * num_processes})." + ) + self.steps_per_generation = self.generation_batch_size // ( + self.per_device_train_batch_size * num_processes + ) + elif self.generation_batch_size is None and self.steps_per_generation is not None: + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + else: + raise ValueError( + "'generation_batch_size' and 'steps_per_generation' can not be both configured at the same time" + ) + + if self.do_eval and self.eval_strategy != "no": + # Determine the number of generations to use for evaluation + num_generations = self.num_generations_eval or self.num_generations + + # Just ensure the value is divisible by the global batch size + if (self.per_device_eval_batch_size * num_processes) % num_generations != 0: + raise ValueError( + f"The global eval batch size ({self.per_device_eval_batch_size} * {num_processes}) must be " + f"divisible by the number of generations used for evaluation ({num_generations})." + ) + + # The generation batch must contain full prompt groups (no partials), so it must be divisible by + # num_generations. + if self.generation_batch_size % self.num_generations != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by num_generations " + f"({self.num_generations})." + ) + + if self.num_generations < 2: + raise ValueError( + "RLOO requires at least 2 generations per prompt to calculate the advantages. You provided " + f"{self.num_generations}, which is less than the minimum required." + ) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/rloo_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/rloo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..1353b9a44824ccbd1cbfbb9df196ad3ed285b219 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/rloo_trainer.py @@ -0,0 +1,1669 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import asyncio +import atexit +import copy +import inspect +import math +import textwrap +import time +from collections import defaultdict, deque +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd +import torch +import torch.utils.data +import transformers +from accelerate.logging import get_logger +from accelerate.utils import gather, gather_object, is_peft_model, set_seed +from datasets import Dataset, IterableDataset +from packaging.version import Version +from torch import nn +from torch.utils.data import Sampler +from transformers import ( + AutoModelForSequenceClassification, + AutoProcessor, + AutoTokenizer, + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, + is_trackio_available, + is_wandb_available, +) +from transformers.utils import is_peft_available, is_rich_available + +from ..data_utils import apply_chat_template, is_conversational, prepare_multimodal_messages +from ..distributed import DistributedBackend +from ..extras.profiling import profiling_context, profiling_decorator +from ..generation.vllm_generation import VLLMGeneration +from ..models import prepare_deepspeed, prepare_fsdp, unwrap_model_for_generation +from ..models.utils import disable_gradient_checkpointing +from .base_trainer import _BaseTrainer +from .callbacks import SyncRefModelCallback +from .rloo_config import RLOOConfig +from .utils import ( + RepeatSampler, + create_model_from_path, + disable_dropout_in_model, + entropy_from_logits, + get_config_model_id, + identity, + nanmax, + nanmin, + nanstd, + pad, + print_prompt_completions_sample, + selective_log_softmax, + shuffle_sequence_dict, + shutdown_event_loop_in_daemon, + split_pixel_values_by_grid, + split_tensor_dict, + start_event_loop_in_daemon, + unsplit_pixel_values_by_grid, + use_adapter, +) + + +if is_peft_available(): + import peft + from peft import LoraConfig, PeftConfig, PeftModel, get_peft_model + + +if is_wandb_available(): + import wandb + +if is_trackio_available(): + import trackio + + +logger = get_logger(__name__) + +# A reward function can be a string, interpreted as a model ID and loaded as a pretrained model, a pretrained model, or +# a callable that returns a list of floats (the rewards). The callable receives prompts, completions, and additional +# arguments from the trainer (refer to the trainer's source for details). To ensure forward compatibility, it should +# accept **kwargs. +RewardFunc = str | PreTrainedModel | Callable[..., list[float | None]] + + +class RLOOTrainer(_BaseTrainer): + """ + Trainer for the Reinforce Leave One Out (RLOO) method. This algorithm was initially proposed in the paper [Back to + Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in + LLMs](https://huggingface.co/papers/2402.14740). + + Example: + + ```python + >>> from trl import RLOOTrainer + >>> from trl.rewards import accuracy_reward + >>> from datasets import load_dataset + + >>> dataset = load_dataset("trl-lib/DeepMath-103K", split="train") + + >>> trainer = RLOOTrainer( + ... model="Qwen/Qwen2.5-0.5B-Instruct", + ... reward_funcs=accuracy_reward, + ... train_dataset=dataset, + ... ) + >>> trainer.train() + ``` + + Args: + model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]): + Model to be trained. Can be either: + + - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using `.from_pretrained` (where `` is derived from the model + config) with the keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported. + - A [`~peft.PeftModel`] object. Only causal language models are supported. + reward_funcs (`RewardFunc | list[RewardFunc]`): + Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward + functions with the prompts and completions and sum the rewards. Can be either: + + - A single reward function, such as: + - A string: The *model ID* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using [`~transformers.AutoModelForSequenceClassification.from_pretrained`] with `num_labels=1` and the + keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object: Only sequence classification models are supported. + - A custom reward function: The function is provided with the prompts and the generated completions, + plus any additional columns in the dataset. It should return a list of rewards. Custom reward + functions can be either synchronous or asynchronous and can also return `None` when the reward is + not applicable to those samples. This is useful for multi-task training where different reward + functions apply to different types of samples. When a reward function returns `None` for a sample, + that reward function is excluded from the reward calculation for that sample. For more details, see + [Using a custom reward + function](#using-a-custom-reward-function). + + The trainer's state is also passed to the reward function. The trainer's state is an instance of + [`~transformers.TrainerState`] and can be accessed by accessing the `trainer_state` argument to the + reward function's signature. + - A list of reward functions, where each item can independently be any of the above types. Mixing different + types within the list (e.g., a string model ID and a custom reward function) is allowed. + args ([`RLOOConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset is + ignored. The format of the samples can be either: + + - [Standard](dataset_formats#standard): Each sample contains plain text. + - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role + and content). + eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`): + Dataset to use for evaluation. It must meet the same requirements as `train_dataset`. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. The padding side must be set to "left". If `None`, the + processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A + padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token, + `tokenizer.eos_token` will be used as the default. + reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*): + Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either: + + - A single processing class: Used when `reward_funcs` contains only one reward function. + - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`. + If set to `None`, or if an element of the list corresponding to a [`~transformers.PreTrainedModel`] is + `None`, the tokenizer for the model is automatically loaded using + [`~transformers.AutoTokenizer.from_pretrained`]. For elements in `reward_funcs` that are custom reward + functions (not [`~transformers.PreTrainedModel`]), the corresponding entries in `reward_processing_classes` + are ignored. + callbacks (list of [`~transformers.TrainerCallback`], *optional*): + List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed + in [here](https://huggingface.co/docs/transformers/main_classes/callback). + + If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`] + method. + optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`): + A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your + model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration used to wrap the model. If `None`, the model is not wrapped. + """ + + _tag_names = ["trl", "rloo"] + _name = "RLOO" + _paper = { + "title": "Back to Basics: Revisiting REINFORCE-Style Optimization for Learning from Human Feedback in LLMs", + "id": "2402.14740", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @inproceedings{ahmadian2024back, + title = {{Back to Basics: Revisiting REINFORCE-Style Optimization for Learning from Human Feedback in LLMs}}, + author = {Arash Ahmadian and Chris Cremer and Matthias Gall{\'{e}} and Marzieh Fadaee and Julia Kreutzer and Olivier Pietquin and Ahmet {\"{U}}st{\"{u}}n and Sara Hooker}, + year = 2024, + booktitle = {Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), {ACL} 2024, Bangkok, Thailand, August 11-16, 2024}, + pages = {12248--12267}, + publisher = {Association for Computational Linguistics}, + editor = {Lun{-}Wei Ku and Andre Martins and Vivek Srikumar}, + }"""), + } + + def __init__( + self, + model: "str | PreTrainedModel | PeftModel", + reward_funcs: RewardFunc | list[RewardFunc], + args: RLOOConfig | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + peft_config: "PeftConfig | None" = None, + ): + # Args + if args is None: + model_name = model if isinstance(model, str) else get_config_model_id(model.config) + model_name = model_name.split("/")[-1] + args = RLOOConfig(f"{model_name}-RLOO") + + # Model + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + model = create_model_from_path(model, **model_init_kwargs) + else: + if args.model_init_kwargs is not None: + logger.warning( + "You passed `model_init_kwargs` to the `RLOOConfig`, but your model is already instantiated. " + "The `model_init_kwargs` will be ignored." + ) + # Non-quantized models do not have the `is_loaded_in_{8,4}bit` attributes, whereas quantized models do + _is_quantized_model = getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False) + + # Some models (SmolVLM/Idefics3) don't support `logits_to_keep` argument and error out if we pass it + # Inspect the forward method before we wrap the model with PEFT + self.model_kwarg_keys = ( + inspect.signature(model.forward).parameters.keys() + if not hasattr(model, "get_base_model") + else inspect.signature(model.get_base_model().forward).parameters.keys() + ) + + # Processing class + if processing_class is None: + processing_class = AutoProcessor.from_pretrained( + get_config_model_id(model.config), + truncation_side="left", + padding_side="left", + trust_remote_code=args.trust_remote_code, + ) + + if args.use_transformers_continuous_batching and isinstance(processing_class, ProcessorMixin): + raise ValueError( + "`use_transformers_continuous_batching` does not support multimodal models. Use `use_vllm` instead." + ) + + # Handle pad token for processors or tokenizers + if isinstance(processing_class, ProcessorMixin): + self._tokenizer = processing_class.tokenizer + elif isinstance(processing_class, PreTrainedTokenizerBase): + self._tokenizer = processing_class + else: + raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`") + + if self._tokenizer.pad_token is None: + self._tokenizer.pad_token = self._tokenizer.eos_token + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge " + "and unload the existing adapter, save the resulting base model, and then pass that base model along " + "with the new `peft_config` to the trainer." + ) + # Create PEFT model + # ZeRO-3 + PEFT for non-quantized models: + # - PEFT's default autocast_adapter_dtype=True upcasts LoRA adapter params to fp32 even when the base model is bf16. + # - ZeRO-3's _allgather_params_coalesced allocates output buffers using the dtype of the first persistent parameter, + # so mixed-dtype persistent_parameters (bf16 base + fp32 LoRA) cause a TypeError on the first optimizer step. + # - Passing autocast_adapter_dtype=False keeps adapter params in the base model dtype (bf16), fixing the mismatch. + # - This is safe: the fp32 upcast is a QLoRA-specific concern (low-bit quantized base models), not needed for + # non-quantized bf16 training. + # - See: + # - TRL issue: https://github.com/huggingface/trl/issues/6089 + # - Upstream issue: https://github.com/deepspeedai/DeepSpeed/issues/8072 + # - autocast_adapter_dtype was introduced in PEFT 0.12.0; before, no upcast existed: no need to pass the kwarg + get_peft_model_kwargs = {} + if ( + args.deepspeed_plugin is not None + and args.deepspeed_plugin.zero_stage == 3 + and not _is_quantized_model + and Version(peft.__version__) >= Version("0.12.0") + ): + get_peft_model_kwargs["autocast_adapter_dtype"] = False + model = get_peft_model(model, peft_config, **get_peft_model_kwargs) + + elif is_peft_model(model): + # If the model is a PEFT model with a pretrained adapter, we need to create a "ref" adapter that is a copy + # of the "default" adapter, so that we can use it as the reference model during the training. PEFT only + # supports one adapter per model when the LoRA config uses `target_parameters` (see peft#3340), so in that + # case we skip the "ref" adapter and compute the reference log probs with adapters disabled, i.e. with the + # base model. + default_config = model.peft_config["default"] + if isinstance(default_config, LoraConfig) and default_config.target_parameters: + logger.warning( + "PEFT can't add a frozen reference adapter alongside one that uses `target_parameters` " + "(peft#3340), so the reference log probs are computed from the base model (adapters disabled). " + "If you wrapped the model only to apply LoRA, pass a `peft_config` to the trainer instead; if you " + "wrapped it deliberately (pretrained adapter or custom init), note that the base model matches " + "your adapter only when it's freshly zero-initialized. If it is, this warning is safe to ignore." + ) + else: + model.add_adapter("ref", default_config) + for name, param in model.named_parameters(): + if ".default." in name: + ref_name = name.replace(".default.", ".ref.") + ref_param = model.get_parameter(ref_name) + ref_param.data.copy_(param.data) + + # When using gradient checkpointing with PEFT, we need to enable input gradients. transformers.Trainer normally + # handles this, but a bug currently prevents it; see https://github.com/huggingface/transformers/issues/42489 + if is_peft_model(model) and args.gradient_checkpointing: + model.enable_input_require_grads() + + # When using QLoRA, the PEFT adapter weights are converted to bf16 to follow the recommendations from the + # original paper (see https://huggingface.co/papers/2305.14314, paragraph 3). Normally, this can be done by + # passing `autocast_adapter_dtype=False` to `get_peft_model`, but this option is not yet supported for + # quantized models. See: https://github.com/huggingface/peft/issues/2889 + if _is_quantized_model: + for param in model.parameters(): + if param.requires_grad: + param.data = param.data.to(torch.bfloat16) + + # Reward functions + if not isinstance(reward_funcs, list): + reward_funcs = [reward_funcs] + self.reward_func_names = [] + for i, reward_func in enumerate(reward_funcs): + if isinstance(reward_func, str): + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + reward_funcs[i] = AutoModelForSequenceClassification.from_pretrained( + reward_func, num_labels=1, **model_init_kwargs + ) + if isinstance(reward_funcs[i], nn.Module): # Use Module over PretrainedModel for compat w/ compiled models + self.reward_func_names.append(get_config_model_id(reward_funcs[i].config).split("/")[-1]) + else: + self.reward_func_names.append(reward_funcs[i].__name__) + self.reward_funcs = reward_funcs + + self._has_async_funcs = any(inspect.iscoroutinefunction(func) for func in self.reward_funcs) + if self._has_async_funcs: + self.async_loop_thread, self.async_loop, self.async_loop_ready_event = start_event_loop_in_daemon( + name="RLOOTrainer-AsyncRewardLoop" + ) + # wait until the event loop is running in the daemon thread + self.async_loop_ready_event.wait() + atexit.register(shutdown_event_loop_in_daemon, self.async_loop_thread, self.async_loop) + + # Reward weights + if args.reward_weights is not None: + if len(args.reward_weights) != len(reward_funcs): + raise ValueError( + f"Number of reward weights ({len(args.reward_weights)}) must match number of reward " + f"functions ({len(reward_funcs)})" + ) + self.reward_weights = torch.tensor(args.reward_weights, dtype=torch.float32) + else: + self.reward_weights = torch.ones(len(reward_funcs), dtype=torch.float32) + + # Reward processing class + if reward_processing_classes is None: + reward_processing_classes = [None] * len(reward_funcs) + elif not isinstance(reward_processing_classes, list): + reward_processing_classes = [reward_processing_classes] + if len(reward_processing_classes) != len(reward_funcs): + raise ValueError( + f"The number of reward processing classes ({len(reward_processing_classes)}) must match the number of " + f"reward functions ({len(reward_funcs)})." + ) + + for i, (reward_processing_class, reward_func) in enumerate( + zip(reward_processing_classes, reward_funcs, strict=True) + ): + if isinstance(reward_func, PreTrainedModel): + if reward_processing_class is None: + reward_processing_class = AutoTokenizer.from_pretrained( + get_config_model_id(reward_func.config), trust_remote_code=args.trust_remote_code + ) + if reward_processing_class.pad_token_id is None: + reward_processing_class.pad_token = reward_processing_class.eos_token + # The reward model computes the reward for the latest non-padded token in the input sequence. + # So it's important to set the pad token ID to the padding token ID of the processing class. + reward_func.config.pad_token_id = reward_processing_class.pad_token_id + reward_processing_classes[i] = reward_processing_class + + self.reward_processing_classes = reward_processing_classes + + # Training arguments + self.max_completion_length = args.max_completion_length + self.num_generations = args.num_generations + self.num_generations_eval = args.num_generations_eval or self.num_generations + self.chat_template_kwargs = args.chat_template_kwargs or {} + self.temperature = args.temperature + self.top_p = args.top_p + self.top_k = args.top_k + self.min_p = args.min_p + self.repetition_penalty = args.repetition_penalty + self.use_transformers_continuous_batching = args.use_transformers_continuous_batching + if self.use_transformers_continuous_batching: + if not Version(transformers.__version__) >= Version("5.8.0"): + raise ImportError( + "Using `use_transformers_continuous_batching` requires transformers>=5.8.0. " + "Please upgrade with `pip install --upgrade transformers`." + ) + from transformers.generation import ContinuousBatchingConfig + + cb_kwargs = dict(args.transformers_continuous_batching_config or {}) + # The transformers default (0.9) leaves almost no VRAM for the training backward pass; + # use a training-aware default unless the user has set it explicitly. + cb_kwargs.setdefault("max_memory_percent", 0.5) + self.continuous_batching_config = ContinuousBatchingConfig(**cb_kwargs) + else: + self.continuous_batching_config = None + self.pad_to_multiple_of = args.pad_to_multiple_of + self.use_vllm = args.use_vllm + self.vllm_mode = args.vllm_mode + self.vllm_gpu_memory_utilization = args.vllm_gpu_memory_utilization # only applies to colocation mode + self.vllm_tensor_parallel_size = args.vllm_tensor_parallel_size # only applies to colocation mode + self.normalize_advantages = args.normalize_advantages + self.mask_truncated_completions = args.mask_truncated_completions + self.reward_clip_range = args.reward_clip_range + + # Datasets + self.shuffle_dataset = args.shuffle_dataset + + if train_dataset is None: + raise ValueError("`train_dataset` is required") + elif ( + isinstance(train_dataset, IterableDataset) + or isinstance(eval_dataset, IterableDataset) + or ( + isinstance(eval_dataset, dict) and any(isinstance(ds, IterableDataset) for ds in eval_dataset.values()) + ) + ): + # See https://github.com/huggingface/trl/issues/3213 + raise NotImplementedError( + "Iterable datasets are not yet supported in RLOOTrainer. Please use a standard dataset instead." + ) + + # Multi-step + self.num_iterations = args.num_iterations + self.epsilon_low = args.epsilon + self.epsilon_high = args.epsilon_high if args.epsilon_high is not None else args.epsilon + + # MoE load-balancing auxiliary loss, applied to Mixture-of-Experts models (no effect otherwise) + text_config = model.config.get_text_config() + is_moe = getattr(text_config, "output_router_logits", None) is not None + self.aux_loss_enabled = is_moe and args.router_aux_loss_coef != 0.0 + self.router_aux_loss_coef = args.router_aux_loss_coef + # Tracks the number of iterations (forward + backward passes), including those within a grad accum cycle + self._step = 0 + # Buffer the batch to reuse generated outputs across multiple updates. For more details, see + # `_get_train_sampler` and `_prepare_inputs`. + self._buffered_inputs = None + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=identity, # No data collation is needed in RLOO + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + callbacks=callbacks, + optimizers=optimizers, + ) + + # Reference model + self.beta = args.beta + if self.beta == 0.0: + # If beta is 0.0, the reference model is not needed + self.ref_model = None + elif is_peft_model(model): + # If PEFT is used, the reference model is not needed since the adapter can be disabled + # to revert to the initial model. + self.ref_model = None + else: + # For deepspeed, fsdp or non-distributed models, create a reference model from scratch + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if self.args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + self.ref_model = create_model_from_path(get_config_model_id(self.model.config), **model_init_kwargs) + + # Disable dropout in the models + if args.disable_dropout: + disable_dropout_in_model(model) + if self.ref_model is not None: + disable_dropout_in_model(self.ref_model) + + # Initialize the metrics + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + self._total_train_tokens = 0 + self._current_train_step_time = 0.0 + self.log_completions = args.log_completions + self.log_unique_prompts = args.log_unique_prompts + self.num_completions_to_print = args.num_completions_to_print + # Keep logs sized to the generation batch to record only outputs from the latest model update. + self._logs = { + "images": deque(maxlen=args.generation_batch_size), + "prompt": deque(maxlen=args.generation_batch_size), + "completion": deque(maxlen=args.generation_batch_size), + "rewards": defaultdict(lambda: deque(maxlen=args.generation_batch_size)), + "advantages": deque(maxlen=args.generation_batch_size), + "extra": defaultdict(lambda: deque(maxlen=args.generation_batch_size)), + } + # Buffers for user-logged data from reward functions, flushed after gathering + self._pending_extra_logs = defaultdict(list) + self._pending_metrics = defaultdict(list) + + # Ensure each process receives a unique seed to prevent duplicate completions when generating with + # transformers if num_generations exceeds per_device_train_batch_size. We could skip it if we use vLLM, but + # it's safer to set it in all cases. + set_seed(args.seed, device_specific=True) + + if self.use_vllm: + # Initialize vLLM generation backend + self.vllm_generation = VLLMGeneration( + model=self.model, + accelerator=self.accelerator, + processing_class=self.processing_class, + # vLLM configuration + mode=args.vllm_mode, + structured_outputs_regex=args.vllm_structured_outputs_regex, + # Server mode configuration + server_base_url=args.vllm_server_base_url, + server_host=args.vllm_server_host, + server_port=args.vllm_server_port, + group_port=args.vllm_group_port, + server_timeout=args.vllm_server_timeout, + # Colocate mode configuration + tensor_parallel_size=args.vllm_tensor_parallel_size, + gpu_memory_utilization=args.vllm_gpu_memory_utilization, + max_model_length=args.vllm_max_model_length, + max_num_seqs=args.per_device_train_batch_size + * args.vllm_tensor_parallel_size + * args.steps_per_generation, + enable_sleep_mode=args.vllm_enable_sleep_mode, + model_impl=args.vllm_model_impl, + # Generation configuration + repetition_penalty=self.repetition_penalty, + temperature=self.temperature, + top_p=self.top_p, + top_k=self.top_k, + min_p=self.min_p, + max_completion_length=self.max_completion_length, + logprobs=None, # we don't need logprobs from vLLM in RLOO + generation_kwargs=args.generation_kwargs, + ) + self._last_loaded_step = -1 # tag to avoid useless loading during grad accumulation + else: + generation_kwargs = { + "max_new_tokens": self.max_completion_length, + "do_sample": True, + "pad_token_id": self._tokenizer.pad_token_id, + "bos_token_id": self._tokenizer.bos_token_id, + "eos_token_id": self._tokenizer.eos_token_id, + "temperature": self.temperature, + "top_p": self.top_p, + "top_k": self.top_k, + "min_p": self.min_p, + "repetition_penalty": self.repetition_penalty, + "cache_implementation": args.cache_implementation, + } + if args.generation_kwargs is not None: + generation_kwargs.update(args.generation_kwargs) + self.generation_config = GenerationConfig(**generation_kwargs, disable_compile=True) + # Keep training-specific generation kwargs to overwrite model's original generation config + self.generation_kwargs = generation_kwargs + + # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the + # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set + # self.model_accepts_loss_kwargs to False to enable scaling. + self.model_accepts_loss_kwargs = False + self._dist = DistributedBackend(self.accelerator) + + # Add tags to the model + self.model.add_model_tags(self._tag_names) + + if self.ref_model is not None: + if self.is_deepspeed_enabled: + self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator) + elif self.is_fsdp_enabled: + self.ref_model = prepare_fsdp(self.ref_model, self.accelerator) + else: + self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True) + + if args.sync_ref_model: + if self.beta == 0.0: + raise ValueError( + "You passed `sync_ref_model=True` while `beta=0.0`, which means the reference model is not used " + "during training. Consequently, RLOOTrainer does not create a `ref_model` instance, and there is " + "nothing to synchronize. Please set `sync_ref_model=False`, or set `beta` to a non-zero value." + ) + if is_peft_model(model): + raise NotImplementedError( + "You passed `sync_ref_model=True` while using a PEFT model, which is currently not supported. " + "With PEFT, RLOOTrainer does not keep a separate reference model in memory; instead, it recovers " + "reference behavior by temporarily disabling the adapter. As a result, there is no standalone " + "`ref_model` instance to synchronize. Use `sync_ref_model=False`, or opt for full fine-tuning if " + "you need a synced reference model. If you need `sync_ref_model` to work with PEFT, please open a " + "feature request at https://github.com/huggingface/trl/issues." + ) + self.add_callback(SyncRefModelCallback(ref_model=self.ref_model, accelerator=self.accelerator)) + + for i, reward_func in enumerate(self.reward_funcs): + if isinstance(reward_func, PreTrainedModel): + if self.is_deepspeed_enabled: + self.reward_funcs[i] = prepare_deepspeed(reward_func, self.accelerator) + else: + # set device placement to True to make `prepare_model` move `reward_func` to device when using fsdp + self.reward_funcs[i] = self.accelerator.prepare_model( + reward_func, evaluation_mode=True, device_placement=True + ) + + def _set_signature_columns_if_needed(self): + # If `self.args.remove_unused_columns` is True, non-signature columns are removed. + # By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids" + # and "attention_mask"). In RLOOTrainer, we preprocess data, so using the model's signature columns doesn't + # work. Instead, we set them to the columns expected by the `training_step` method, hence the override. + if self._signature_columns is None: + self._signature_columns = ["prompt", "image", "images"] + + # This method overrides `Trainer.get_train_dataloader` to support our custom batching strategy. + # Instead of returning a standard per-step batch (i.e., `per_device_batch_size), our dataloader loads an + # *generation* batch (i.e., `per_device_batch_size × steps_per_generation`). This allows us to generate completions + # once every steps_per_generation step—rather than once per accumulation step—which is significantly more + # efficient. The only change from the original implementation is multiplying the batch size by + # `steps_per_generation`. Thus, `_prepare_inputs` is called with this *generation* batch, and it handles the + # splitting internally. + # Maintenance note: This method is a copy-paste of the original `Trainer.get_train_dataloader` with only one line + # modification. + def get_train_dataloader(self): + return self._get_dataloader( + dataset=self.train_dataset, + description="Training", + batch_size=self._train_batch_size * self.args.steps_per_generation, # < this is the change + sampler_fn=self._get_train_sampler, + is_training=True, + ) + + def _get_train_sampler(self, dataset: Dataset | None = None) -> Sampler: + # Returns a sampler that + # 1. ensures each prompt is repeated across multiple processes. This guarantees that identical prompts are + # distributed to different GPUs, allowing rewards to be computed and normalized correctly within each prompt + # group. Using the same seed across processes ensures consistent prompt assignment, preventing discrepancies + # in group formation. + # 2. repeats the batch multiple times to allow reusing generations across multiple updates. Refer to + # _prepare_inputs to see how the generations are stored and reused. + + # In the following figure, the values are the prompt indices. Each row shows the per-step batch + # returned by `_prepare_inputs`; rows within a `steps_per_generation` block are slices of the same + # generated batch. When `num_iterations > 1`, that block is reused for multiple optimization passes + # before regenerating. + # + # | GPU 0 | GPU 1 | + # + # global_step step <-───> num_generations=2 + # <-───────> per_device_train_batch_size=3 + # grad_accum ▲ ▲ 0 0 0 0 1 1 2 2 <- Generate for the first `steps_per_generation` (prompts 0 to 11); store the completions; use the first slice to compute the loss + # =2 ▼ | 0 1 3 3 4 4 5 5 <- Take the stored generations and use the second slice to compute the loss + # | + # | 1 2 6 6 7 7 8 8 <- Take the stored generations and use the third slice to compute the loss + # steps_per_gen=4 ▼ 1 3 9 9 10 10 11 11 <- Take the stored generations and use the fourth slice to compute the loss + # + # 2 4 12 12 13 13 14 14 <- Generate for the second `steps_per_generation` (prompts 12 to 23); store the completions; use the first slice to compute the loss + # 2 5 15 15 16 16 17 17 <- Take the stored generations and use the second slice to compute the loss + # ... + if dataset is None: + dataset = self.train_dataset + return RepeatSampler( + data_source=dataset, + mini_repeat_count=self.num_generations, + batch_size=self.args.generation_batch_size // self.num_generations, + repeat_count=self.num_iterations * self.args.steps_per_generation, + shuffle=self.shuffle_dataset, + seed=self.args.seed, + ) + + def _get_eval_sampler(self, eval_dataset) -> Sampler: + # See _get_train_sampler for an explanation of the sampler. + return RepeatSampler( + data_source=eval_dataset, + mini_repeat_count=self.num_generations_eval, + seed=self.args.seed, + ) + + @profiling_decorator + def _get_per_token_logps_and_entropies( + self, + model, + input_ids, + attention_mask, + logits_to_keep, + batch_size=None, + compute_entropy=False, + compute_aux_loss=False, + pixel_values=None, + image_grid_thw=None, + num_images=None, + pixel_attention_mask=None, + spatial_shapes=None, + num_tiles=None, + image_sizes=None, + token_type_ids=None, + mm_token_type_ids=None, + image_position_ids=None, + ) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]: + """Compute log-probs, (optionally) entropies, and (optionally) the MoE load-balancing aux loss.""" + batch_size = batch_size or input_ids.size(0) # Chunk inputs into smaller batches to reduce memory peak + all_logps = [] + all_entropies = [] + all_aux_losses = [] + for start in range(0, input_ids.size(0), batch_size): + input_ids_batch = input_ids[start : start + batch_size] + attention_mask_batch = attention_mask[start : start + batch_size] + + # Build model inputs + model_inputs = {"input_ids": input_ids_batch, "attention_mask": attention_mask_batch} + if image_grid_thw is not None and pixel_values is not None: + rows_per_image = image_grid_thw.prod(dim=-1) + rows_per_sample = torch.split(rows_per_image, num_images) + rows_per_sample = torch.stack([s.sum() for s in rows_per_sample]) + cum_rows = torch.cat([torch.tensor([0], device=rows_per_sample.device), rows_per_sample.cumsum(0)]) + row_start, row_end = cum_rows[start].item(), cum_rows[start + batch_size].item() + model_inputs["pixel_values"] = pixel_values[row_start:row_end] + cum_imgs = torch.tensor([0] + num_images).cumsum(0) + img_start, img_end = cum_imgs[start], cum_imgs[start + batch_size] + model_inputs["image_grid_thw"] = image_grid_thw[img_start:img_end] + elif image_position_ids is not None and pixel_values is not None: + cum_imgs = torch.tensor([0] + num_images).cumsum(0) + img_start, img_end = cum_imgs[start], cum_imgs[start + batch_size] + model_inputs["pixel_values"] = pixel_values[img_start:img_end] + model_inputs["image_position_ids"] = image_position_ids[img_start:img_end] + elif spatial_shapes is not None and pixel_values is not None: + # LFM2-VL tensors are tile-indexed. + cum_tiles = torch.tensor([0] + num_tiles).cumsum(0) + tile_start, tile_end = cum_tiles[start], cum_tiles[start + batch_size] + model_inputs["pixel_values"] = pixel_values[tile_start:tile_end] + model_inputs["pixel_attention_mask"] = pixel_attention_mask[tile_start:tile_end] + model_inputs["spatial_shapes"] = spatial_shapes[tile_start:tile_end] + elif pixel_values is not None: + model_inputs["pixel_values"] = pixel_values[start : start + batch_size] + if pixel_attention_mask is not None and spatial_shapes is None: + model_inputs["pixel_attention_mask"] = pixel_attention_mask[start : start + batch_size] + if image_sizes is not None: + model_inputs["image_sizes"] = image_sizes[start : start + batch_size] + if token_type_ids is not None: + model_inputs["token_type_ids"] = token_type_ids[start : start + batch_size] + if mm_token_type_ids is not None: + model_inputs["mm_token_type_ids"] = mm_token_type_ids[start : start + batch_size] + + # Only add logits_to_keep if the model supports it + if "logits_to_keep" in self.model_kwarg_keys: + # We add 1 to `logits_to_keep` because the last logits of the sequence is later excluded + model_inputs["logits_to_keep"] = logits_to_keep + 1 + + model_inputs["use_cache"] = False # only used in generation; set False to suppress warnings + + # MoE models: request router logits so the model returns `outputs.aux_loss`. VLM wrappers honor this only + # as a forward kwarg (not from the model config), so it must be passed here. + if compute_aux_loss: + model_inputs["output_router_logits"] = True + + outputs = model(**model_inputs) + logits = outputs.logits + # Exclude the last value: it corresponds to the next token pred + logits = logits[:, :-1, :] # (B, L-1, H) + # Only keep the last logits_to_keep. For model that support logits_to_keep, this is a no-op. + logits = logits[:, -logits_to_keep:, :] # (B, logits_to_keep, H) + # Divide logits by sampling temperature. + # See https://huggingface.co/blog/the_n_implementation_details_of_rlhf_with_ppo#policy-training-implementation-details + logits.div_(self.temperature) + completion_ids = input_ids_batch[:, -logits_to_keep:] + logps = selective_log_softmax(logits, completion_ids) # compute logprobs + all_logps.append(logps) + + if compute_entropy: + with torch.no_grad(): + entropies = entropy_from_logits(logits) + all_entropies.append(entropies) + + if compute_aux_loss: + all_aux_losses.append(outputs.aux_loss) + + logps = torch.cat(all_logps, dim=0) + entropies = torch.cat(all_entropies, dim=0) if compute_entropy else None + aux_loss = torch.stack(all_aux_losses).mean() if compute_aux_loss else None + return logps, entropies, aux_loss + + def training_step(self, model, inputs, num_items_in_batch): + time_before = time.perf_counter() + output = super().training_step(model, inputs, num_items_in_batch) + self._step += 1 + time_after = time.perf_counter() + self._current_train_step_time += time_after - time_before + if self._step % self.current_gradient_accumulation_steps == 0: + self._metrics["train"]["step_time"].append(self._current_train_step_time) + self._current_train_step_time = 0.0 + return output + + @profiling_decorator + def _prepare_inputs(self, generation_batch: dict[str, torch.Tensor | Any]) -> dict[str, torch.Tensor | Any]: + # Prepares inputs for model training/evaluation by managing completion generation and batch handling. + # During training: + # - Receives the local generation batch (Per-GPU batch size × steps per generation) + # from the modified training dataloader instead of the standard local batch + # - Generates completions once for the entire generation batch and splits it into batches of size + # `per_device_train_batch_size` + # - Buffers these completions and returns the appropriate slice for the current accumulation step + # - Optimizes by regenerating completions only periodically (every steps_per_generation * num_iterations) + # During evaluation: + # - The input is treated as a standard local batch (no accumulation, no multiple iterations) + # - Completions are generated for each batch without buffering or reuse + # Returns a single local batch in both cases. + + mode = "train" if self.model.training else "eval" + if mode == "train": + generate_every = self.args.steps_per_generation * self.num_iterations + if self._step % generate_every == 0 or self._buffered_inputs is None: + # self._buffered_inputs=None can occur when resuming from a checkpoint + generation_batch = self._generate_and_score_completions(generation_batch) + generation_batch = split_pixel_values_by_grid(generation_batch) + generation_batch = shuffle_sequence_dict(generation_batch) + generation_batches = split_tensor_dict(generation_batch, self.args.steps_per_generation) + self._buffered_inputs = [unsplit_pixel_values_by_grid(batch) for batch in generation_batches] + inputs = self._buffered_inputs[self._step % self.args.steps_per_generation] + else: + # In evaluation, there is neither batch grouping for generation, nor multiple iterations, hence + # local generation batch == local eval batch + inputs = self._generate_and_score_completions(generation_batch) + return inputs + + def _log_completion_extra(self, column: str, values: list): + """ + Log extra columns to the completions table. Called from reward functions via the `log_extra` kwarg. + + Args: + column (`str`): + Name of the column to add. + values (`list`): + Values for the column, one per sample in the batch. + """ + self._pending_extra_logs[column].extend(values) + + def _log_metric(self, name: str, value: float): + """ + Log a scalar metric from a reward function. Called via the `log_metric` kwarg. Values are averaged over each + logging step and reported alongside built-in metrics like `kl` and `entropy`. + + Args: + name (`str`): + Name of the metric. + value (`float`): + Scalar value for this batch. + """ + self._pending_metrics[name].append(value) + + @profiling_decorator + def _calculate_rewards(self, inputs, prompts, completions, completion_ids_list): + device = self.accelerator.device + rewards_per_func = torch.zeros(len(prompts), len(self.reward_funcs), device=device) + + # Repeat all input columns (but "prompt", "completion", and "completion_ids") to match the num of generations + keys = [key for key in inputs[0] if key not in ["prompt", "completion", "completion_ids"]] + reward_kwargs = {key: [example[key] for example in inputs] for key in keys} + + # This allows for dynamic reward shaping based on training progress. + reward_kwargs["trainer_state"] = self.state + + # Allow reward functions to log extra columns to the completions table. + reward_kwargs["log_extra"] = self._log_completion_extra + + # Allow reward functions to log additional scalar metrics. + reward_kwargs["log_metric"] = self._log_metric + + async_funcs_info = [] # async custom functions for asyncio.gather + + for i, (reward_func, reward_processing_class, reward_func_name) in enumerate( + zip(self.reward_funcs, self.reward_processing_classes, self.reward_func_names, strict=True) + ): + if isinstance(reward_func, nn.Module): # Module (no PretrainedModel) for compat with compiled models + with profiling_context(self, reward_func_name): + if is_conversational(inputs[0]): + messages = [{"messages": p + c} for p, c in zip(prompts, completions, strict=True)] + texts = [ + apply_chat_template(x, reward_processing_class, **self.chat_template_kwargs)["text"] + for x in messages + ] + else: + texts = [p + c for p, c in zip(prompts, completions, strict=True)] + reward_inputs = reward_processing_class( + text=texts, return_tensors="pt", padding=True, padding_side="right", add_special_tokens=False + ) + reward_inputs = super()._prepare_inputs(reward_inputs) + with torch.inference_mode(): + rewards_per_func[:, i] = reward_func(**reward_inputs).logits[:, 0] # Shape (B*G,) + elif inspect.iscoroutinefunction(reward_func): # Separate async reward funcs to run them in parallel later + async_funcs_info.append((i, reward_func, reward_func_name)) + else: + # Run synchronous reward function + with profiling_context(self, reward_func_name): + output_reward_func = reward_func( + prompts=prompts, completions=completions, completion_ids=completion_ids_list, **reward_kwargs + ) + # Convert None values to NaN + output_reward_func = [reward if reward is not None else torch.nan for reward in output_reward_func] + rewards_per_func[:, i] = torch.tensor(output_reward_func, dtype=torch.float32, device=device) + + # Execute async custom functions in parallel using asyncio.gather + if async_funcs_info: + + async def _invoke_async(index, func, func_name): + with profiling_context(self, func_name): + output = await func( + prompts=prompts, completions=completions, completion_ids=completion_ids_list, **reward_kwargs + ) + output = [r if r is not None else torch.nan for r in output] + return index, output + + async def _run_async_funcs(): + coros = [_invoke_async(i, func, func_name) for (i, func, func_name) in async_funcs_info] + return await asyncio.gather(*coros) + + async_results = asyncio.run_coroutine_threadsafe(_run_async_funcs(), self.async_loop).result() + for idx, output_reward_func in async_results: + rewards_per_func[:, idx] = torch.tensor(output_reward_func, dtype=torch.float32, device=device) + + # If all reward functions return None for a given row, issue a detailed warning + if torch.isnan(rewards_per_func).all(dim=1).any(): + nan_row_idx = torch.isnan(rewards_per_func).all(dim=1).nonzero(as_tuple=True)[0][0] + row_reward_kwargs = { + key: value[nan_row_idx] + for key, value in reward_kwargs.items() + if key not in ("trainer_state", "log_extra", "log_metric") + } + row_reward_kwargs["prompt"] = prompts[nan_row_idx] + row_reward_kwargs["completion"] = completions[nan_row_idx] + logger.warning( + f"All reward functions returned None for the following kwargs:\n{row_reward_kwargs}\n" + "Please ensure that at least one reward function returns a valid reward." + ) + + # Gather the reward per function: this part is crucial, because the rewards are normalized per group and the + # completions may be distributed across processes + rewards_per_func = gather(rewards_per_func) + return rewards_per_func + + def _tokenize_prompts(self, prompts: list): + """Tokenize prompts and extract images/multimodal fields for generation.""" + if is_conversational({"prompt": prompts[0]}): + # Extract images from messages for VLM support + images = [] + has_images = False + for prompt in prompts: + prompt_images = [] + for message in prompt: + if isinstance(message["content"], list): + for part in message["content"]: + if part["type"] == "image": + prompt_images.append(part["image"]) + has_images = True + images.append(prompt_images if prompt_images else None) + images = images if has_images else None + + # Workaround for a bug in transformers 5.3.0 where some processors (e.g. Qwen2.5-VL) crash on + # batched unpadded input (transformers#44514). + # Fixed in transformers 5.4.0 (transformers#44563). + needs_padding_workaround = Version("5.3.0") <= Version(transformers.__version__) < Version("5.4.0") + tokenized = self.processing_class.apply_chat_template( + conversation=prompts, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + **({"padding": True} if needs_padding_workaround else {}), + **self.chat_template_kwargs, + ) + if needs_padding_workaround: + # Unpad input_ids: remove padding tokens using attention_mask to get per-sequence lists + prompt_ids = [ + [tok for tok, m in zip(ids, mask, strict=True) if m] + for ids, mask in zip(tokenized["input_ids"], tokenized["attention_mask"], strict=True) + ] + else: + prompt_ids = tokenized["input_ids"] + # For VLMs, the processor returns extra multimodal fields (pixel_values, image_grid_thw, etc.) + multimodal_fields = {k: v for k, v in tokenized.items() if k not in ("input_ids", "attention_mask")} + else: + prompt_ids = self.processing_class(text=prompts)["input_ids"] + images = None + multimodal_fields = {} + return prompt_ids, images, multimodal_fields + + def _generate_single_turn(self, prompt_ids, images, multimodal_fields): + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + + # Generate completions using either vLLM or regular generation + if self.use_vllm: + # Sync weights if training step changed + if self.state.global_step != self._last_loaded_step: + with profiling_context(self, "sync_weights"): + self.vllm_generation.sync_weights() + self._last_loaded_step = self.state.global_step + + # Generate using vLLM (note: RLOO doesn't use logprobs from generation, so we ignore them) + num_generations = self.num_generations if mode == "train" else self.num_generations_eval + _, completion_ids, _, _ = self.vllm_generation.generate( + prompts=prompt_ids, + images=images, + num_generations=num_generations, + profiler=profiling_context(self, "vLLM.generate"), + ) + + elif self.use_transformers_continuous_batching: + with ( + profiling_context(self, "transformers.generate_batch"), + unwrap_model_for_generation( + self.model_wrapped, self.accelerator, gather_deepspeed3_params=self.args.ds3_gather_for_generation + ) as unwrapped_model, + torch.no_grad(), + self._dist.summon_full_params(self.model_wrapped, recurse=False), + ): + # Cast to the appropriate dtype based on training configuration + if self.args.bf16: + unwrapped_model.to(torch.bfloat16) + elif self.args.fp16: + unwrapped_model.to(torch.float16) + all_outputs = unwrapped_model.generate_batch( + prompt_ids, + generation_config=self.generation_config, + continuous_batching_config=self.continuous_batching_config, + progress_bar=False, + ) + unwrapped_model.train() + completion_ids = [output.generated_tokens for output in all_outputs.values()] + + else: + # Regular generation path: left-pad token IDs into tensors + prompt_tensors = [torch.tensor(ids) for ids in prompt_ids] + padded_ids = pad(prompt_tensors, padding_value=self._tokenizer.pad_token_id, padding_side="left") + attention_mask = pad([torch.ones_like(t) for t in prompt_tensors], padding_value=0, padding_side="left") + generate_inputs = {"input_ids": padded_ids, "attention_mask": attention_mask} + # For VLMs, include multimodal fields as tensors (pixel_values, image_grid_thw, etc.) + for k, v in multimodal_fields.items(): + if isinstance(v, torch.Tensor): + generate_inputs[k] = v + elif isinstance(v, list) and v and isinstance(v[0], list): + # Per-token field (e.g., token_type_ids): left-pad like input_ids + generate_inputs[k] = pad([torch.tensor(x) for x in v], padding_value=0, padding_side="left") + else: + generate_inputs[k] = torch.tensor(np.array(v)) + generate_inputs = super()._prepare_inputs(generate_inputs) + + with ( + profiling_context(self, "transformers.generate"), + unwrap_model_for_generation( + self.model_wrapped, + self.accelerator, + gather_deepspeed3_params=self.args.ds3_gather_for_generation, + generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762 + ) as unwrapped_model, + torch.no_grad(), + self._dist.summon_full_params(self.model_wrapped, recurse=False), + ): + prompt_completion_ids = unwrapped_model.generate( + **generate_inputs, generation_config=self.generation_config + ) + # Compute prompt length and extract completion ids + prompt_length = generate_inputs["input_ids"].size(1) + completion_ids = prompt_completion_ids[:, prompt_length:] + + # Mask everything after the first EOS token + is_eos = completion_ids == self._tokenizer.eos_token_id + eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device) + eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)] + sequence_indices = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1) + completion_mask = (sequence_indices <= eos_idx.unsqueeze(1)).int() + completion_ids = [ + c[m].tolist() for c, m in zip(completion_ids.cpu(), completion_mask.bool().cpu(), strict=True) + ] + + return completion_ids + + def _generate(self, prompts: list): + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + + # Copy the prompts to avoid modifying the original list + prompts = copy.deepcopy(prompts) + + prompt_ids, images, multimodal_fields = self._tokenize_prompts(prompts) + completion_ids = self._generate_single_turn(prompt_ids, images, multimodal_fields) + + # Decode completions. It's important to use `parse_response` when possible, because it handles tool calls. + if is_conversational({"prompt": prompts[0]}): + contents = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + completions = [[{"role": "assistant", "content": content}] for content in contents] + else: + completions = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + + # Get completion length per sequence, used for logging + prompt_lengths = torch.tensor([len(ids) for ids in prompt_ids], device=device) + completion_lengths = torch.tensor([len(ids) for ids in completion_ids], device=device) + agg_prompt_lengths = self.accelerator.gather(prompt_lengths) + agg_completion_lengths = self.accelerator.gather(completion_lengths) + total_prompt_tokens = agg_prompt_lengths.sum() + total_completion_tokens = agg_completion_lengths.sum() # = num_items_in_batch, required for the DAPO loss + + # Log the metrics + if mode == "train": + self.state.num_input_tokens_seen += (total_prompt_tokens + total_completion_tokens).item() + self._metrics[mode]["num_tokens"] = [self.state.num_input_tokens_seen] + + # Log completion lengths, mean, min, max + self._metrics[mode]["completions/mean_length"].append(agg_completion_lengths.float().mean().item()) + self._metrics[mode]["completions/min_length"].append(agg_completion_lengths.float().min().item()) + self._metrics[mode]["completions/max_length"].append(agg_completion_lengths.float().max().item()) + + # Identify sequences that terminated with EOS and log their lengths + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids], device=device) + agg_is_truncated = self.accelerator.gather(is_truncated) + self._metrics[mode]["completions/clipped_ratio"].append(agg_is_truncated.float().mean().item()) + term_completion_lengths = agg_completion_lengths[~agg_is_truncated] + if len(term_completion_lengths) == 0: # edge case where no terminated sequences are found + term_completion_lengths = torch.zeros(1, device=device) + self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_lengths.float().mean().item()) + self._metrics[mode]["completions/min_terminated_length"].append(term_completion_lengths.float().min().item()) + self._metrics[mode]["completions/max_terminated_length"].append(term_completion_lengths.float().max().item()) + + return prompt_ids, completion_ids, completions + + def _generate_and_score_completions( + self, inputs: list[dict[str, torch.Tensor | Any]] + ) -> dict[str, torch.Tensor | Any]: + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + + prompts = [x["prompt"] for x in inputs] + + if "images" in inputs[0]: + images = [example.get("images") for example in inputs] + elif "image" in inputs[0]: + images = [[example.get("image")] if example.get("image") is not None else None for example in inputs] + else: + images = None + # Transformers requires at least one image in the batch, otherwise it throws an error + if images is not None and all(img_list == [] for img_list in images): + images = None + + # If the prompts are conversational and the inputs contain images, we need to convert the prompts from + # [{"role": "user", "content": "What color is the sky?"}] to + # [{"role": "user", "content": [{"type": "image", "image": }, {"type": "text", "text": "What color is the sky?"}]}] + if images is not None: + if not is_conversational(inputs[0]): + raise ValueError( + "Multimodal training requires conversational prompts. It looks like the dataset contains " + "non-conversational inputs, likely because a chat template was applied before passing the dataset " + "to the trainer. Please provide the raw conversational prompts and let the trainer apply the chat " + "template internally." + ) + prompts = [ + prepare_multimodal_messages(prompt, images=image_list) + for prompt, image_list in zip(prompts, images, strict=True) + ] + + prompt_ids_list, completion_ids_list, completions = self._generate(prompts) + + # Convert lists of token IDs to padded tensors + prompt_ids = [torch.tensor(ids) for ids in prompt_ids_list] + prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids] + prompt_ids = pad( + prompt_ids, + padding_value=self._tokenizer.pad_token_id, + padding_side="left", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + prompt_mask = pad( + prompt_mask, padding_value=0, padding_side="left", pad_to_multiple_of=self.pad_to_multiple_of + ).to(device=device) + completion_ids = [torch.tensor(ids) for ids in completion_ids_list] + completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids] + completion_ids = pad( + completion_ids, + padding_value=self._tokenizer.pad_token_id, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + completion_mask = pad( + completion_mask, padding_value=0, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of + ).to(device=device) + + # If mask_truncated_completions is enabled, zero out truncated completions in completion_mask + if self.mask_truncated_completions: + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + # Mask completion_mask for attention masking + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device) + completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int() + + # Concatenate prompt_mask with completion_mask for logit computation + prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) # (B, P+C) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P+C) + + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + batch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size + + num_images = [len(img_list) if img_list else 0 for img_list in images] if images is not None else None + + # Get forward_kwargs for models with multimodal inputs + if images is not None: + prompts_text = [ + apply_chat_template({"prompt": prompt}, self.processing_class, **self.chat_template_kwargs)["prompt"] + for prompt in prompts + ] + prompt_inputs = self.processing_class(images=images, text=prompts_text, padding=True, return_tensors="pt") + prompt_inputs = super()._prepare_inputs(prompt_inputs) + forward_kwargs = {k: v for k, v in prompt_inputs.items() if k not in ["input_ids", "attention_mask"]} + else: + forward_kwargs = {} + + # Recover LFM2-VL tile counts; the full processor drops row/column metadata. + num_tiles = None + if images is not None and "spatial_shapes" in forward_kwargs: + image_info = self.processing_class.image_processor( + images=images, return_tensors="pt", return_row_col_info=True + ) + tiles_per_image = image_info["image_rows"] * image_info["image_cols"] + if self.processing_class.image_processor.use_thumbnail: + tiles_per_image = tiles_per_image + (tiles_per_image > 1).to(tiles_per_image.dtype) + num_tiles = [group.sum().item() for group in torch.split(tiles_per_image, num_images)] + + # If token_type_ids are used, extend them with zeros for the completion part + if "token_type_ids" in forward_kwargs: + token_type_ids = forward_kwargs["token_type_ids"] + if self.pad_to_multiple_of is not None: + # Needed only with pad_to_multiple_of: otherwise prompt_ids and token_type_ids must have equal len + padding_size = prompt_ids.size(1) - token_type_ids.size(1) + if padding_size > 0: + token_type_ids = torch.cat( + [token_type_ids.new_zeros((token_type_ids.size(0), padding_size)), token_type_ids], dim=1 + ) + forward_kwargs["token_type_ids"] = torch.cat( + [token_type_ids, token_type_ids.new_zeros(completion_ids.shape)], dim=1 + ) + # If mm_token_type_ids are used, extend them with zeros for the completion part + if "mm_token_type_ids" in forward_kwargs: + mm_token_type_ids = forward_kwargs["mm_token_type_ids"] + if self.pad_to_multiple_of is not None: + # Needed only with pad_to_multiple_of: otherwise prompt_ids and mm_token_type_ids must have equal len + padding_size = prompt_ids.size(1) - mm_token_type_ids.size(1) + if padding_size > 0: + mm_token_type_ids = torch.cat( + [mm_token_type_ids.new_zeros((mm_token_type_ids.size(0), padding_size)), mm_token_type_ids], + dim=1, + ) + forward_kwargs["mm_token_type_ids"] = torch.cat( + [mm_token_type_ids, mm_token_type_ids.new_zeros(completion_ids.shape)], dim=1 + ) + + # When gradient checkpointing is enabled with use_reentrant=True (non default), calling the model inside a + # torch.no_grad() block triggers a harmless PyTorch warning ("None of the inputs have requires_grad=True"). + # Temporarily disable checkpointing to avoid this warning during inference. + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + # Compute the per-token log probabilities for the current model + old_per_token_logps, _, _ = self._get_per_token_logps_and_entropies( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size, + num_images=num_images, + num_tiles=num_tiles, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask, spatial_shapes, image_sizes, image_position_ids + ) + old_logps = (old_per_token_logps * completion_mask).sum(1) # mask out padding and tokens after EOS + + # Compute the per-token log probabilities for the reference model + if self.beta != 0.0: + if self.ref_model is not None: + ref_per_token_logps, _, _ = self._get_per_token_logps_and_entropies( + self.ref_model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size=batch_size, + num_images=num_images, + num_tiles=num_tiles, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask, spatial_shapes, image_sizes, image_position_ids + ) + else: + # When training a PEFT adapter, how we obtain the reference depends on the setup: + # - New adapter: disabling adapters yields the base model. + # - Re-training an existing adapter: an initial copy is loaded under the name "ref". + model = self.accelerator.unwrap_model(self.model) + with use_adapter(model, adapter_name="ref" if "ref" in model.peft_config else None): + ref_per_token_logps, _, _ = self._get_per_token_logps_and_entropies( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size=batch_size, + num_images=num_images, + num_tiles=num_tiles, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask, spatial_shapes, image_sizes, image_position_ids + ) + else: + ref_per_token_logps = None + + # Decode + prompts_text = self.processing_class.batch_decode(prompt_ids, skip_special_tokens=True) + completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + + # Calculate rewards for each reward function. rewards_per_func aggregates rewards across all processes. This is + # important because rewards will be normalized per group, and completions are distributed. We will later slice + # rewards_per_func to extract each process's subset. + rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list) + num_generations = self.num_generations if mode == "train" else self.num_generations_eval + + # A completion for which every reward function returned None is unscorable. nansum would collapse it to 0, + # which both biases the leave-one-out baseline and hands the completion a spurious advantage. Mark these rows + # NaN so they're excluded from the (nan-aware) baseline below; their advantage is forced to 0 afterwards. + unscorable_mask = torch.isnan(rewards_per_func).all(dim=1) + + # Apply weights to each reward function's output and sum + rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1) + rewards[unscorable_mask] = torch.nan + + # Apply reward clipping if specified + if self.reward_clip_range: + rewards = rewards.clamp(min=self.reward_clip_range[0], max=self.reward_clip_range[1]) + + # Include the KL penalty in the reward + if self.beta != 0.0: + # RLOO uses the first-order log ratio for the per-token KL estimate, following the original RLOO paper + # (Ahmadian et al., 2024, https://huggingface.co/papers/2405.14782). Unlike GRPOTrainer's Schulman + # approximation (always >= 0), this can be negative per token. The divergence is intentional: RLOO applies + # KL as a reward penalty (summed across tokens per sequence), while GRPO adds it to the per-token loss. + per_token_kl = old_per_token_logps - ref_per_token_logps + # Apply sequence-level KL penalty to rewards (sum KL across tokens first, then apply to each sequence) + kl = (per_token_kl * completion_mask).sum(-1) + kl = gather(kl) # rewards are gathered, so kl must be too + rewards = rewards - self.beta * kl + + grouped_rewards = rewards.view(-1, num_generations) + mean_grouped_rewards = torch.nanmean(grouped_rewards, dim=1) + if num_generations > 1: + std_rewards = nanstd(grouped_rewards, dim=1) + else: # doesn't occur during training, but could occur in eval when num_generations_eval=1 + std_rewards = torch.zeros_like(mean_grouped_rewards) + + # RLOO advantages computation. The leave-one-out baseline averages over scorable siblings only: nansum drops + # unscorable rewards and the divisor is (scorable count − 1). A group with a single scorable completion yields + # 0/0 = NaN, and unscorable rows stay NaN; both are zeroed by nan_to_num below. + scorable_counts = (~torch.isnan(grouped_rewards)).sum(dim=1, keepdim=True) # (num_prompts, 1) + grouped_sum = torch.nansum(grouped_rewards, dim=1, keepdim=True) # (num_prompts, 1) + if num_generations > 1: + baselines = (grouped_sum - grouped_rewards) / (scorable_counts - 1) # (num_prompts, num_generations) + baselines = baselines.view(-1) # Flatten back to match rewards shape + advantages = rewards - baselines + else: # this case doesn't occur during training, but could in eval when num_generations_eval=1 + advantages = torch.zeros_like(rewards) + + # Normalize advantages over the scorable subset only (unscorable advantages are still NaN here). + if self.normalize_advantages: + advantages = (advantages - torch.nanmean(advantages)) / (nanstd(advantages) + 1e-4) + + # Unscorable completions carry no learning signal: zero their advantage to keep them from moving the policy. + advantages = torch.nan_to_num(advantages, nan=0.0) + + is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards)) # for logging + + # Slice to keep only the local part of the data + process_slice = slice( + self.accelerator.process_index * len(prompts), + (self.accelerator.process_index + 1) * len(prompts), + ) + all_process_advantages = advantages.clone() # keep the aggregated advantages for logging + advantages = advantages[process_slice] + + # Calculate and log the mean KL divergence between current and reference model + if self.beta != 0.0: + mean_kl = (per_token_kl * completion_mask).sum() / completion_mask.sum().clamp(min=1.0) + self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item()) + + # Calculate mean reward per function, but only for samples where the function was applied (non-NaN values) + for i, reward_func_name in enumerate(self.reward_func_names): + mean_rewards = torch.nanmean(rewards_per_func[:, i]).item() + self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards) + std_func_rewards = nanstd(rewards_per_func[:, i]).item() + self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_func_rewards) + rewards = (rewards_per_func * self.reward_weights.to(rewards_per_func.device).unsqueeze(0)).nansum(dim=1) + rewards[unscorable_mask] = torch.nan # exclude unscorable rows from the logged reward stats + self._metrics[mode]["reward"].append(torch.nanmean(rewards).item()) + self._metrics[mode]["reward_std"].append(nanstd(rewards).item()) + self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item()) + + # Log prompt and completion texts + self._logs["prompt"].extend(gather_object(prompts_text)) + self._logs["completion"].extend(gather_object(completions_text)) + for i, name in enumerate(self.reward_func_names): + self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist()) + self._logs["advantages"].extend(all_process_advantages.tolist()) + + # Flush user-logged extra columns (from log_extra), gathering across processes. + # Keys must be sorted so that all ranks call gather_object in the same order, otherwise values + # get mis-attributed across columns (dict insertion order may differ between processes). + for column in sorted(self._pending_extra_logs): + self._logs["extra"][column].extend(gather_object(self._pending_extra_logs[column])) + self._pending_extra_logs.clear() + + # Flush user-logged metrics (from log_metric), averaging across processes. + # Keys must be sorted so that all ranks call accelerator.gather in the same order, otherwise values + # get mis-attributed across metrics (dict insertion order may differ between processes). + for name in sorted(self._pending_metrics): + values = self._pending_metrics[name] + local_mean = sum(values) / len(values) + global_mean = self.accelerator.gather(torch.tensor(local_mean, device=device)).mean().item() + self._metrics[mode][name].append(global_mean) + self._pending_metrics.clear() + + if images is not None: + self._logs["images"].extend(gather_object(images)) + + output = { + "prompt_ids": prompt_ids, + "prompt_mask": prompt_mask, + "completion_ids": completion_ids, + "completion_mask": completion_mask, + "old_logps": old_logps, + "advantages": advantages, + } + if "pixel_values" in forward_kwargs: + output["pixel_values"] = forward_kwargs["pixel_values"] + if "image_grid_thw" in forward_kwargs: + output["image_grid_thw"] = forward_kwargs["image_grid_thw"] + if "pixel_attention_mask" in forward_kwargs: + output["pixel_attention_mask"] = forward_kwargs["pixel_attention_mask"] + if "spatial_shapes" in forward_kwargs: + output["spatial_shapes"] = forward_kwargs["spatial_shapes"] + if "image_sizes" in forward_kwargs: + output["image_sizes"] = forward_kwargs["image_sizes"] + if "token_type_ids" in forward_kwargs: + output["token_type_ids"] = forward_kwargs["token_type_ids"] + if "mm_token_type_ids" in forward_kwargs: + output["mm_token_type_ids"] = forward_kwargs["mm_token_type_ids"] + if "image_position_ids" in forward_kwargs: + output["image_position_ids"] = forward_kwargs["image_position_ids"] + if images is not None: + output["num_images"] = num_images + if num_tiles is not None: + output["num_tiles"] = num_tiles + return output + + @profiling_decorator + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + if return_outputs: + raise ValueError("The RLOOTrainer does not support returning outputs") + return self._compute_loss(model, inputs) + + def _compute_loss(self, model, inputs): + # Compute the per-token log probabilities for the model + prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"] + completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"] + input_ids = torch.cat([prompt_ids, completion_ids], dim=1) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + + # Compute the per_token_logps and the entropy at each position in the completion + per_token_logps, entropies, aux_loss = self._get_per_token_logps_and_entropies( + model, + input_ids, + attention_mask, + logits_to_keep, + compute_entropy=True, + compute_aux_loss=self.aux_loss_enabled, + pixel_values=inputs.get("pixel_values"), + image_grid_thw=inputs.get("image_grid_thw"), + num_images=inputs.get("num_images"), + pixel_attention_mask=inputs.get("pixel_attention_mask"), + spatial_shapes=inputs.get("spatial_shapes"), + num_tiles=inputs.get("num_tiles"), + image_sizes=inputs.get("image_sizes"), + token_type_ids=inputs.get("token_type_ids"), + mm_token_type_ids=inputs.get("mm_token_type_ids"), + image_position_ids=inputs.get("image_position_ids"), + ) + + logps = (per_token_logps * completion_mask).sum(1) # mask out padding and tokens after EOS + old_logps = inputs["old_logps"] + log_ratio = logps - old_logps + + # Compute the loss + advantages = inputs["advantages"] + coef_1 = torch.exp(log_ratio) + coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high) + per_sequence_loss1 = coef_1 * advantages + per_sequence_loss2 = coef_2 * advantages + per_sequence_loss = -torch.min(per_sequence_loss1, per_sequence_loss2) + loss = per_sequence_loss.mean() + + # Log the metrics + mode = "train" if self.model.training else "eval" + + # RLOO returns an unscaled loss (the HF Trainer divides by gradient accumulation), so add the aux term unscaled + if self.aux_loss_enabled: + loss = loss + self.router_aux_loss_coef * aux_loss + self._metrics[mode]["aux_loss"].append(self.accelerator.gather_for_metrics(aux_loss).mean().item()) + + # Entropy + mean_entropy = (entropies * completion_mask).sum() / completion_mask.sum().clamp(min=1.0) + self._metrics[mode]["entropy"].append(self.accelerator.gather(mean_entropy).nanmean().item()) + + # Compute the clipped probability ratios + is_low_clipped = (coef_1 < 1 - self.epsilon_low) & (advantages < 0) + is_high_clipped = (coef_1 > 1 + self.epsilon_high) & (advantages > 0) + is_region_clipped = is_low_clipped | is_high_clipped + gathered_low_clip = self.accelerator.gather(is_low_clipped.float().mean()) + self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item()) + self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item()) + gathered_high_clip = self.accelerator.gather(is_high_clipped.float().mean()) + self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item()) + self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item()) + gathered_clip_ratio = self.accelerator.gather(is_region_clipped.float().mean()) + self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item()) + return loss + + # During eval, Trainer calls prediction_step. If no labels are present in the inputs, it only runs forward and + # returns logits. We override prediction_step to force compute_loss, because this trainer doesn't involve labels. + def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys: list[str] | None = None): + inputs = self._prepare_inputs(inputs) + with torch.no_grad(): + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + loss = loss.mean().detach() + return loss, None, None + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + # Average the metrics + metrics = {} + for key, val in self._metrics[mode].items(): + # Filter out NaN values before averaging. A reward function that returns None for all samples + # in a batch produces NaN for that batch's metric. With logging_steps > 1, a naive sum()/len() + # would let a single NaN contaminate valid data from other batches. Only return None when no + # valid values remain (e.g. JSON loggers crash on float NaN). + valid = [v for v in val if not math.isnan(v)] + metrics[key] = sum(valid) / len(valid) if valid else None + + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + if self.accelerator.is_main_process and self.log_completions: + if is_rich_available(): + print_prompt_completions_sample( + self._logs["prompt"], + self._logs["completion"], + self._logs["rewards"], + self._logs["advantages"], + self.state.global_step, + self.num_completions_to_print, + extra=dict(self._logs["extra"]), + ) + + logging_backends = [] + if self.args.report_to and "wandb" in self.args.report_to and wandb.run is not None: + logging_backends.append(wandb) + if self.args.report_to and "trackio" in self.args.report_to: + logging_backends.append(trackio) + + table = { + "step": [self.state.global_step] * len(self._logs["prompt"]), + "prompt": self._logs["prompt"], + "completion": self._logs["completion"], + **self._logs["rewards"], + **self._logs["extra"], + "advantage": self._logs["advantages"], + } + + df_base = pd.DataFrame(table) + images_raw = self._logs["images"] or [] + + for logging_backend in logging_backends: + if images_raw: + images = [] + for image_list in self._logs["images"]: + images.append([logging_backend.Image(image) for image in image_list]) + df = pd.concat( + [df_base, pd.Series(images, name="image")], + axis=1, + copy=False, + ) + else: + df = df_base + + if self.log_unique_prompts: + df = df.drop_duplicates(subset=["prompt"]) + + logging_backend.log({"completions": logging_backend.Table(dataframe=df)}) + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/sft_config.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/sft_config.py new file mode 100644 index 0000000000000000000000000000000000000000..de1b554bbbe88d8c1693519f517224c223760b59 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/sft_config.py @@ -0,0 +1,336 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass, field +from typing import Any + +from .base_config import _BaseConfig + + +@dataclass +class SFTConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`SFTTrainer`]. + + This class includes only the parameters that are specific to SFT training. For a full list of training arguments, + please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may + differ from those in [`~transformers.TrainingArguments`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + > Parameters that control the model + + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model` + argument of the [`SFTTrainer`] is provided as a string. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to + [`~transformers.AutoModelForCausalLM.from_pretrained`] and + [`~transformers.AutoProcessor.from_pretrained`]. + router_aux_loss_coef (`float`, *optional*, defaults to `0.001`): + Coefficient of the load-balancing auxiliary loss. Only has an effect when training a Mixture-of-Experts + (MoE) model; for other models it does nothing. The auxiliary loss is added to the training loss with this + weight. Set to `0.0` to disable it. + chat_template_path (`str`, *optional*): + If specified, sets the model's chat template. This can either be the path to a tokenizer (local directory + or Hugging Face Hub model) or a direct path to a Jinja template file. When using a Jinja file, you must + ensure that any special tokens referenced in the template are added to the tokenizer and that the model's + embedding layer is resized accordingly. + + > Parameters that control the data preprocessing + + dataset_text_field (`str`, *optional*, defaults to `"text"`): + Name of the column that contains text data in the dataset. + dataset_kwargs (`dict[str, Any]`, *optional*): + Dictionary of optional keyword arguments for the dataset preparation. The only supported key is + `skip_prepare_dataset`. When the model is a VLM, `skip_prepare_dataset` is automatically treated as `True` + regardless of the provided value, since preprocessing is done on the fly. + dataset_num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + eos_token (`str`, *optional*): + Token used to indicate the end of a turn or sequence. If `None`, it defaults to + `processing_class.eos_token`. + max_length (`int` or `None`, *optional*, defaults to `1024`): + Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from the left + or right depending on `truncation_mode`. If `None`, no truncation is applied. When packing is enabled, + this value sets the sequence length. + truncation_mode (`str`, *optional*, defaults to `"keep_start"`): + Truncation mode to use when the sequence exceeds `max_length`. The only supported value is + `"keep_start"`. The `"keep_end"` value is deprecated and will be removed in v2.0.0. + shuffle_dataset (`bool`, *optional*, defaults to `False`): + Whether to shuffle the dataset. + packing (`bool`, *optional*, defaults to `False`): + Whether to group multiple sequences into fixed-length blocks to improve computational efficiency and reduce + padding. Uses `max_length` to define sequence length. + packing_strategy (`str`, *optional*, defaults to `"bfd"`): + Strategy for packing sequences. Can be `"bfd"` (best-fit decreasing, truncates overflow), `"bfd_split"` + (best-fit decreasing, splits overflow sequences), or `"wrapped"` (aggressive, cuts mid-sequence). + padding_free (`bool`, *optional*, defaults to `False`): + Whether to perform forward passes without padding by flattening all sequences in the batch into a single + continuous sequence. This reduces memory usage by eliminating padding overhead. Currently, this is only + supported with the FlashAttention 2 or 3, which can efficiently handle the flattened batch structure. When + packing is enabled with strategy `"bfd"`, padding-free is enabled, regardless of the value of this + parameter. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + eval_packing (`bool`, *optional*): + Whether to pack the eval dataset. If `None`, uses the same value as `packing`. + + > Parameters that control the training + + completion_only_loss (`bool`, *optional*): + Whether to compute loss only on the completion part of the sequence. If set to `True`, loss is computed + only on the completion, which is supported only for [prompt-completion](#prompt-completion) datasets. If + `False`, loss is computed on the entire sequence. If `None` (default), the behavior depends on the dataset: + loss is computed on the completion for [prompt-completion](#prompt-completion) datasets, and on the full + sequence for [language modeling](#language-modeling) datasets. + assistant_only_loss (`bool`, *optional*, defaults to `False`): + Whether to compute loss only on the assistant part of the sequence. If set to `True`, loss is computed only + on the assistant responses, which is supported only for [conversational](#conversational) datasets. If + `False`, loss is computed on the entire sequence. + loss_type (`str`, *optional*, defaults to `"chunked_nll"`): + Type of loss to use. When left unset, it defaults to `"chunked_nll"`, except when `use_liger_kernel=True`, + in which case it defaults to `"nll"`. Possible values are: + + - `"nll"`: standard negative log-likelihood. + - `"dft"`: Dynamic Fine-Tuning, as described in + [this paper](https://huggingface.co/papers/2508.05629). + - `"chunked_nll"`: same math as `"nll"`, but the `lm_head` projection is computed on non-ignored tokens + only (positions with `labels == -100` are dropped before the matmul) and the cross-entropy is processed + in chunks of tokens to reduce peak activation memory. Not compatible with `use_liger_kernel`. + + activation_offloading (`bool`, *optional*, defaults to `False`): + Whether to offload the activations to the CPU. + + > Deprecated parameters + + pad_token: + + + + Parameter `pad_token` is deprecated and will be removed in version v2.0.0. Set `tokenizer.pad_token` + directly and pass it as `processing_class` to the trainer instead. + + + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `2e-5` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=2e-5, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + # Parameters that control the model + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of " + "the `SFTTrainer` is provided as a string." + }, + ) + router_aux_loss_coef: float = field( + default=0.001, + metadata={ + "help": "Coefficient of the load-balancing auxiliary loss. Only has an effect when training a " + "Mixture-of-Experts (MoE) model; for other models it does nothing. The auxiliary loss is added to the " + "training loss with this weight. Set to `0.0` to disable it." + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. " + "Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoProcessor.from_pretrained`." + }, + ) + chat_template_path: str | None = field( + default=None, + metadata={ + "help": "If specified, sets the model's chat template. This can either be the path to a tokenizer (local " + "directory or Hugging Face Hub model) or a direct path to a Jinja template file. When using a Jinja file, " + "you must ensure that any special tokens referenced in the template are added to the tokenizer and " + "that the model's embedding layer is resized accordingly." + }, + ) + + # Parameters that control the data preprocessing + dataset_text_field: str = field( + default="text", + metadata={"help": "Name of the column that contains text data in the dataset."}, + ) + dataset_kwargs: dict[str, Any] | None = field( + default=None, + metadata={ + "help": "Dictionary of optional keyword arguments for the dataset preparation. The only supported key is " + "`skip_prepare_dataset`. If the model is a VLM, `skip_prepare_dataset` value is ignored. When the model " + "is a VLM, `skip_prepare_dataset` is automatically treated as `True` regardless of the provided value, " + "since preprocessing is done on the fly." + }, + ) + dataset_num_proc: int | None = field( + default=None, + metadata={"help": "Number of processes to use for processing the dataset."}, + ) + eos_token: str | None = field( + default=None, + metadata={ + "help": "Token used to indicate the end of a turn or sequence. If `None`, it defaults to `processing_class.eos_token`." + }, + ) + max_length: int | None = field( + default=1024, + metadata={ + "help": "Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from " + "the left or right depending on the `truncation_mode`. If `None`, no truncation is applied. When packing " + "is enabled, this value sets the sequence length." + }, + ) + truncation_mode: str = field( + default="keep_start", + metadata={ + "help": "Truncation mode to use when the sequence exceeds `max_length`. The only supported value is " + "`'keep_start'`. The `'keep_end'` value is deprecated and will be removed in v2.0.0.", + "choices": ["keep_end", "keep_start"], + }, + ) + shuffle_dataset: bool = field( + default=False, + metadata={"help": "Whether to shuffle the dataset."}, + ) + packing: bool = field( + default=False, + metadata={ + "help": "Whether to group multiple sequences into fixed-length blocks to improve computational efficiency " + "and reduce padding. Uses `max_length` to define sequence length." + }, + ) + packing_strategy: str = field( + default="bfd", + metadata={ + "help": "Strategy for packing sequences. Can be `'bfd'` (best-fit decreasing, truncates overflow), " + "`'bfd_split'` (best-fit decreasing, splits overflow sequences), or `'wrapped'` (aggressive, cuts " + "mid-sequence).", + "choices": ["bfd", "bfd_split", "wrapped"], + }, + ) + padding_free: bool = field( + default=False, + metadata={ + "help": "Whether to perform forward passes without padding by flattening all sequences in the batch into " + "a single continuous sequence. This reduces memory usage by eliminating padding overhead. Currently, this " + "is only supported with the FlashAttention 2 or 3, which can efficiently handle the flattened batch " + "structure. When packing is enabled with strategy `'bfd'`, padding-free is enabled, regardless of the " + "value of this parameter." + }, + ) + pad_to_multiple_of: int | None = field( + default=None, + metadata={"help": "If set, the sequences will be padded to a multiple of this value."}, + ) + eval_packing: bool | None = field( + default=None, + metadata={"help": "Whether to pack the eval dataset. If `None`, uses the same value as `packing`."}, + ) + + # Parameters that control the training + completion_only_loss: bool | None = field( + default=None, + metadata={ + "help": ( + "Whether to compute loss only on the completion part of the sequence. If set to `True`, loss is " + "computed only on the completion, which is supported only for prompt-completion datasets. If `False`, " + "loss is computed on the entire sequence. If `None` (default), the behavior depends on the dataset: " + "loss is computed on the completion for prompt-completion datasets, and on the full sequence for " + "language modeling datasets." + ) + }, + ) + assistant_only_loss: bool = field( + default=False, + metadata={ + "help": ( + "Whether to compute loss only on the assistant part of the sequence. If set to `True`, loss is " + "computed only on the assistant responses, which is supported only for conversational datasets. If `False`, " + "loss is computed on the entire sequence." + ) + }, + ) + loss_type: str | None = field( + default=None, + metadata={ + "help": "Type of loss to use. When left unset, it defaults to `'chunked_nll'`, except when " + "`use_liger_kernel=True`, in which case it defaults to `'nll'`. Possible values are `'nll'` (standard " + "negative log-likelihood), `'dft'` (Dynamic Fine-Tuning, https://huggingface.co/papers/2508.05629), and " + "`'chunked_nll'` (same math as `'nll'`, but the `lm_head` projection is computed on non-ignored tokens " + "only — positions with `labels == -100` are dropped before the matmul — and the cross-entropy is " + "processed in chunks of tokens to reduce peak activation memory; not compatible with `use_liger_kernel`; " + "the patched `lm_head` path covers standard causal LMs and VLMs whose language model exposes a top-level " + "`lm_head`, architectures with a non-standard head are not supported)." + }, + ) + activation_offloading: bool = field( + default=False, + metadata={"help": "Whether to offload the activations to the CPU."}, + ) + + # Deprecated parameters + pad_token: str | None = field( + default=None, + metadata={ + "help": "Deprecated. Set `tokenizer.pad_token` directly and pass it as `processing_class` to the trainer instead." + }, + ) + + def __post_init__(self): + super().__post_init__() + if self.pad_token is not None: + warnings.warn( + "`pad_token` is deprecated and will be removed in v2.0.0. " + "Set `tokenizer.pad_token` directly and pass it as `processing_class` to the trainer instead.", + FutureWarning, + stacklevel=3, + ) + if self.truncation_mode == "keep_end": + warnings.warn( + "The `'keep_end'` truncation mode is deprecated and will be removed in v2.0.0. " + "Use `truncation_mode='keep_start'` (the default) instead.", + FutureWarning, + stacklevel=3, + ) + if self.packing_strategy == "bfd-requeue": + warnings.warn( + "The `bfd-requeue` packing strategy has been renamed to `bfd_split`. Please update your configuration accordingly. " + "The `bfd-requeue` strategy is deprecated and will be removed in v2.0.0.", + FutureWarning, + stacklevel=3, + ) + self.packing_strategy = "bfd_split" + + # When unset, default to "chunked_nll" unless `use_liger_kernel=True`, in which case default to "nll". + if self.loss_type is None: + self.loss_type = "nll" if self.use_liger_kernel else "chunked_nll" diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/sft_trainer.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/sft_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..9f2c27344d9e57dc4f70544d2ef51f35ba8f9e08 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/sft_trainer.py @@ -0,0 +1,1848 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import contextlib +import json +import os +import types +import warnings +from collections import defaultdict +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import torch +import torch.nn as nn +import torch.nn.functional as F +import transformers +from accelerate import PartialState +from accelerate.logging import get_logger +from accelerate.utils import is_peft_model +from datasets import Dataset, IterableDataset +from packaging.version import Version +from transformers import ( + AutoProcessor, + DataCollator, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainingArguments, +) +from transformers.data.data_collator import DataCollatorMixin +from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast +from transformers.trainer_callback import TrainerCallback +from transformers.trainer_utils import EvalPrediction +from transformers.utils import is_peft_available + +from ..chat_template_utils import ( + clone_chat_template, + get_training_chat_template, + has_generation_markers, + is_chat_template_stop_token_trained, +) +from ..data_utils import ( + apply_chat_template, + is_conversational, + is_conversational_from_value, + maybe_convert_to_chatml, + pack_dataset, + prepare_multimodal_messages, +) +from ..models import get_act_offloading_ctx_manager +from .base_trainer import _BaseTrainer +from .sft_config import SFTConfig +from .utils import ( + create_model_from_path, + entropy_from_logits, + flush_left, + get_config_model_id, + pad, + selective_log_softmax, +) + + +_CHUNKED_LM_HEAD_CHUNK_SIZE = 256 + + +if is_peft_available(): + import peft + from peft import PeftConfig, PeftModel, PeftType, get_peft_model + + +@dataclass +class _ChunkedCELMHeadOutput(CausalLMOutputWithPast): + """`CausalLMOutputWithPast` with extra fields populated by the chunked-CE path.""" + + num_correct_tokens: torch.Tensor | None = None + entropy_sum: torch.Tensor | None = None + num_valid_tokens: torch.Tensor | None = None + aux_loss: torch.Tensor | None = None + + +def _maybe_gather_lm_head_ctx(w, b): + # Allgather ZeRO-3 partitioned `lm_head` weight/bias for the chunked matmul. No-op if not ZeRO-3, or if the + # param is already gathered (tied embeddings: `embed_tokens` shares the weight and keeps it `AVAILABLE`, so + # partitioning on our exit would collide with its active-submodule tracking). + from transformers.integrations.deepspeed import is_deepspeed_zero3_enabled + + if not is_deepspeed_zero3_enabled(): + return contextlib.nullcontext() + + import deepspeed + from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus + + params = [w] if b is None else [w, b] + if all(p.ds_status == ZeroParamStatus.AVAILABLE for p in params): + return contextlib.nullcontext() + return deepspeed.zero.GatheredParameters(params) + + +def _chunk(h, w, b, lbl, logit_scale, final_logit_softcapping): + with _maybe_gather_lm_head_ctx(w, b): + logits = h.float() @ w.float().t() + if b is not None: + logits = logits + b.float() + if logit_scale != 1.0: + logits = logits * logit_scale + if final_logit_softcapping is not None: + logits = final_logit_softcapping * torch.tanh(logits / final_logit_softcapping) + log_p = F.log_softmax(logits, dim=-1) + chunk_loss = F.nll_loss(log_p, lbl, reduction="sum") + chunk_correct = (logits.argmax(dim=-1) == lbl).sum().float() + chunk_entropy = -(log_p.exp() * log_p).sum(dim=-1).sum() + return chunk_loss, chunk_correct, chunk_entropy + + +def _chunked_cross_entropy_loss( + hidden_states: torch.Tensor, + lm_head_weight: torch.Tensor, + chunk_size: int, + labels: torch.Tensor | None = None, + shift_labels: torch.Tensor | None = None, + num_items_in_batch: torch.Tensor | int | None = None, + logit_scale: float = 1.0, + final_logit_softcapping: float | None = None, + lm_head_bias: torch.Tensor | None = None, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Memory-efficient next-token cross-entropy over hidden states and an `lm_head` weight. + + The full `lm_head` projection is never materialized. Positions where labels equal `-100` are dropped before the + matmul, and the remaining tokens are processed in chunks of `chunk_size`. Each chunk's `[chunk_size, vocab_size]` + logits tensor is kept alive only during its own forward/backward pass via gradient checkpointing, so peak + logits-activation memory is `chunk_size * vocab_size` instead of `batch_size * seq_len * vocab_size`. + + At least one of `labels` or `shift_labels` must be provided. Passing `labels` alone is the standard path and + triggers the internal `labels[..., 1:]` / `hidden_states[..., :-1, :]` shift. Passing `shift_labels` skips the + shift and assumes the caller has already aligned labels with hidden states — this is the contract used under + context / sequence parallelism, where labels are shifted before being sharded. If both are provided, `shift_labels` + wins (matching [`~transformers.loss.ForCausalLMLoss`]). + + Args: + hidden_states (`torch.Tensor`): + Base decoder output of shape `(B, S, H)`, i.e. before the `lm_head` projection. + lm_head_weight (`torch.Tensor`): + Weight of the `lm_head` linear layer, shape `(V, H)`. + chunk_size (`int`): + Number of valid tokens processed per chunk. Peak memory scales linearly with this. + labels (`torch.Tensor`, *optional*): + Labels of shape `(B, S)`. Positions equal to `-100` are excluded from both the `lm_head` matmul and the + loss. Mutually exclusive with `shift_labels`. + shift_labels (`torch.Tensor`, *optional*): + Pre-shifted labels of shape `(B, S)`, aligned with `hidden_states` (position `i` predicts + `shift_labels[i]`). Mutually exclusive with `labels`. + num_items_in_batch (`torch.Tensor`, `int` or `None`, *optional*): + Total number of valid tokens across the global batch, as plumbed by [`~transformers.Trainer`]. When + provided, the loss is reduced as `sum / num_items_in_batch`, matching the gradient-accumulation-correct + behavior of HF's default cross-entropy. When `None`, reduction is `mean` over local valid tokens. + logit_scale (`float`, *optional*, defaults to `1.0`): + Multiplier applied to each chunk's logits before the cross-entropy, matching the `logit_scale` behavior of + Cohere-style models. + final_logit_softcapping (`float`, *optional*): + If set, applies `softcap * tanh(logits / softcap)` to each chunk's logits before the cross-entropy, + matching the `final_logit_softcapping` behavior of Gemma-style models. Applied after `logit_scale`. + lm_head_bias (`torch.Tensor`, *optional*): + Bias of the `lm_head` linear layer, shape `(V,)`. Added to each chunk's logits when provided. + + Returns: + `tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]`: scalar loss, number of correctly-predicted + tokens (count), sum of per-token Shannon entropy (in nats), and number of valid (non-`-100`) target tokens — + all over the local batch. Raw sums are returned so callers can reduce correctly across ranks. + """ + if labels is None and shift_labels is None: + raise ValueError("At least one of `labels` or `shift_labels` must be provided.") + + if shift_labels is not None: + hidden = hidden_states.reshape(-1, hidden_states.size(-1)) + labels = shift_labels.reshape(-1) + else: + hidden = hidden_states[..., :-1, :].reshape(-1, hidden_states.size(-1)) + labels = labels[..., 1:].reshape(-1) + + valid = labels != -100 + hidden = hidden[valid] + labels = labels[valid] + n_valid = hidden.size(0) + + correct = hidden.new_zeros((), dtype=torch.float32) + entropy_sum = hidden.new_zeros((), dtype=torch.float32) + n_valid_tensor = torch.tensor(n_valid, device=hidden.device, dtype=torch.long) + if n_valid == 0: + # Whole micro-batch masked (e.g. completion-only loss + truncation). Keep the loss connected + # to the autograd graph through every trainable parameter so `.backward()` succeeds and DDP / + # FSDP gradient sync doesn't hang on a missing param. + with _maybe_gather_lm_head_ctx(lm_head_weight, lm_head_bias): + loss = (hidden_states.float().sum() + lm_head_weight.float().sum()) * 0.0 + if lm_head_bias is not None: + loss = loss + lm_head_bias.float().sum() * 0.0 + return loss, correct, entropy_sum, n_valid_tensor + + loss = hidden.new_zeros((), dtype=torch.float32) + + for start in range(0, n_valid, chunk_size): + h_chunk = hidden[start : start + chunk_size] + lbl_chunk = labels[start : start + chunk_size] + chunk_loss, chunk_correct, chunk_entropy = torch.utils.checkpoint.checkpoint( + _chunk, + h_chunk, + lm_head_weight, + lm_head_bias, + lbl_chunk, + logit_scale, + final_logit_softcapping, + use_reentrant=False, + ) + loss = loss + chunk_loss + correct = correct + chunk_correct + entropy_sum = entropy_sum + chunk_entropy + + if num_items_in_batch is None: + loss = loss / n_valid + else: + if isinstance(num_items_in_batch, torch.Tensor): + num_items_in_batch = num_items_in_batch.to(loss.device) + loss = loss / num_items_in_batch + return loss, correct, entropy_sum, n_valid_tensor + + +def _patch_chunked_ce_lm_head(model: torch.nn.Module, chunk_size: int, is_vlm: bool = False) -> None: + """ + Patch `model.forward` to compute the LM loss via [`_chunked_cross_entropy_loss`]. + + When `labels` (or pre-shifted `shift_labels`, for CP/SP) are provided, the patched forward runs the decoder up to + `last_hidden_state` (skipping the `lm_head` matmul), drops `labels == -100` positions, and computes the + cross-entropy in chunks of `chunk_size` valid tokens. Returns a [`_ChunkedCELMHeadOutput`] with `loss` set, + `logits=None`, and `num_correct_tokens` / `entropy_sum` / `num_valid_tokens` over non-ignored tokens. For MoE + models (`output_router_logits=True`), the load-balancing aux loss is added with the same coefficient and formula as + the model's reference forward. + + Without labels, the original forward runs unchanged — generation and labels-free eval preserve any per-model logits + post-processing (`logit_scale`, `final_logit_softcapping`, `logits_to_keep` slicing). + + Args: + model (`torch.nn.Module`): + Model to patch. For PEFT, pass `peft_model.get_base_model()` rather than the `PeftModel` wrapper, so + prompt-learning variants (PromptTuning, PrefixTuning, PTuning) keep their virtual-token injection in + `PeftModel.forward` before delegating into the patched forward. + chunk_size (`int`): + Number of valid tokens processed per CE chunk. + is_vlm (`bool`): + Set to `True` for VLMs. Only used to read `logit_scale` / `final_logit_softcapping` / + `output_router_logits` from `model.config.text_config` instead of the top-level config. + """ + # VLM scaling configs (`logit_scale`, `final_logit_softcapping`, MoE `output_router_logits`) live on `text_config`; + # text-only models keep them on the top-level config. + text_config = model.config.text_config if is_vlm else model.config + final_logit_softcapping = getattr(text_config, "final_logit_softcapping", None) + logit_scale = getattr(text_config, "logit_scale", 1.0) + original_forward = model.forward + lm_head = model.get_output_embeddings() + + def _chunked_ce_forward( + self: torch.nn.Module, + input_ids: torch.Tensor | None = None, + attention_mask: torch.Tensor | None = None, + labels: torch.Tensor | None = None, + num_items_in_batch: torch.Tensor | int | None = None, + shift_labels: torch.Tensor | None = None, + output_router_logits: bool | None = None, + **kwargs, + ) -> CausalLMOutputWithPast: + # Without labels, fall back to the original forward so generation and labels-free evaluation + # preserve any per-model logits post-processing (e.g. Cohere `logit_scale`, Gemma + # `final_logit_softcapping`, `logits_to_keep` slicing). + if labels is None and shift_labels is None: + # MoE models: request router logits so the model returns `outputs.aux_loss`. VLM wrappers honor this only + # as a forward kwarg (not from the model config), so it must be passed here. + if output_router_logits is not None: + kwargs["output_router_logits"] = output_router_logits + return original_forward(input_ids=input_ids, attention_mask=attention_mask, **kwargs) + + if output_router_logits is None: + output_router_logits = getattr(text_config, "output_router_logits", False) + + kwargs.pop("use_cache", None) + decoder_kwargs = {} + # MoE models: request router logits so the model returns `outputs.aux_loss`. VLM wrappers honor this only + # as a forward kwarg (not from the model config), so it must be passed here. + if output_router_logits: + decoder_kwargs["output_router_logits"] = True + # `base_model` gives the backbone model (skipping `lm_head`) — text decoder for LMs, multimodal wrapper + # for VLMs (so vision-token injection runs before the text decoder). `get_decoder()` won't do: on VLMs it + # returns just the text stack and feeds image-placeholder IDs through it. + # Pre-5.0 transformers VLMs set `base_model_prefix = ""` so `self.base_model is self` (re-runs `lm_head`). + # Fall back to `self.model` there. + if is_vlm and Version(transformers.__version__) < Version("5.0.0"): + backbone = self.model + else: + backbone = self.base_model + outputs: BaseModelOutputWithPast = backbone( + input_ids=input_ids, attention_mask=attention_mask, use_cache=False, **decoder_kwargs, **kwargs + ) + hidden_states = outputs.last_hidden_state + + lm_head_weight = lm_head.weight + lm_head_bias = lm_head.bias + # Under FSDP2, lm_head.weight is a DTensor (Shard(0) or Replicate). Passing it directly + # into the gradient-checkpointed chunk loop causes FSDP2 to re-gather it once per chunk + # during backward recomputation. full_tensor() converts it to a plain tensor once; all + # chunks reference that tensor, so only one all-gather occurs (in full_tensor()'s backward). + if isinstance(lm_head_weight, torch.distributed.tensor.DTensor): + lm_head_weight = lm_head_weight.full_tensor() + if lm_head_bias is not None: + lm_head_bias = lm_head_bias.full_tensor() + loss, num_correct_tokens, entropy_sum, num_valid_tokens = _chunked_cross_entropy_loss( + hidden_states, + lm_head_weight, + chunk_size, + labels=labels, + shift_labels=shift_labels, + num_items_in_batch=num_items_in_batch, + logit_scale=logit_scale, + final_logit_softcapping=final_logit_softcapping, + lm_head_bias=lm_head_bias, + ) + + aux_loss = None + if output_router_logits: + # Mirror the per-family MoE forward: add `router_aux_loss_coef * load_balancing_loss_func(...)` to + # the main loss. Mixtral is the source of truth — every MoE family (Qwen3Moe, GptOss, OLMoE, + # Qwen2Moe, DBRX, JetMoE, PhiMoE, …) pulls this function from mixtral via the modular system, so a + # single import keeps us in lockstep with upstream for every family we test. + from transformers.models.mixtral.modeling_mixtral import load_balancing_loss_func + + if Version(transformers.__version__) < Version("5.0.0") and not is_vlm: + num_experts = self.num_experts + num_experts_per_tok = self.num_experts_per_tok + router_aux_loss_coef = self.router_aux_loss_coef + else: + # Upstream bug AttributeError: 'GptOssConfig' object has no attribute 'num_experts'; see #5754 + if text_config.model_type == "gpt_oss" and Version("5.0.0") <= Version( + transformers.__version__ + ) < Version("5.6.0"): + num_experts = self.num_experts + else: + num_experts = text_config.num_experts + num_experts_per_tok = text_config.num_experts_per_tok + router_aux_loss_coef = text_config.router_aux_loss_coef + aux_loss = load_balancing_loss_func( + outputs.router_logits, num_experts, num_experts_per_tok, attention_mask + ) + loss = loss + router_aux_loss_coef * aux_loss.to(loss.device) + + return _ChunkedCELMHeadOutput( + loss=loss, + logits=None, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + num_correct_tokens=num_correct_tokens, + entropy_sum=entropy_sum, + num_valid_tokens=num_valid_tokens, + aux_loss=aux_loss, + ) + + model.forward = types.MethodType(_chunked_ce_forward, model) + + +logger = get_logger(__name__) + + +FLASH_ATTENTION_VARIANTS = { + "flash_attention_2", + "flash_attention_3", + "kernels-community/flash-attn2", + "kernels-community/flash-attn3", + "kernels-community/vllm-flash-attn3", +} + + +def get_dataset_column_names(dataset: Dataset | IterableDataset) -> list[str]: + return list(next(iter(dataset)).keys()) if dataset.column_names is None else dataset.column_names + + +@dataclass +class DataCollatorForLanguageModeling(DataCollatorMixin): + """ + Data collator used for language modeling data. Inputs are dynamically padded to the maximum length of a batch. + + This collator expects each example in the input list to be a dictionary containing at least the `"input_ids"` key. + If the input contains `"labels"`, they are used as is (truncated and padded like the input IDs); otherwise the + labels default to the input IDs. Tokens that shouldn't contribute to the loss are expected to be already set to + `-100` in the labels; the [`SFTTrainer`] takes care of this during dataset preparation. The collator returns a + dictionary containing the following keys: + - `"input_ids"`: Tensor of input IDs, padded to the maximum length of the batch. + - `"labels"`: Tensor of labels, padded with `-100` to the maximum length of the batch. If `padding_free` is set + to `False`, the following key is also returned: + - `"attention_mask"`: Tensor of attention masks, padded to the maximum length of the batch. + If `padding_free` is set to `True`, the following key is also returned: + - `"position_ids"`: Tensor of position IDs, padded to the maximum length of the batch. + + Args: + pad_token_id (`int`): + Token ID to use for padding. + max_length (`int`, *optional*): + Maximum length of the sequences in the batch. Sequences longer than `max_length` are truncated to + `max_length`. + truncation_mode (`str`, *optional*, defaults to `"keep_start"`): + Truncation mode to use when the sequence exceeds `max_length`. Possible values are `"keep_end"` and + `"keep_start"`. + padding_free (`bool`, *optional*, defaults to `False`): + If set to `True`, the sequences will be flattened into a single sequence, and the position IDs will be + generated accordingly and returned instead of the attention mask. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + return_tensors (`str`, *optional*, defaults to `"pt"`): + Type of Tensor to return. Only `"pt"` is currently supported. + + Examples: + ```python + >>> from trl.trainer.sft_trainer import DataCollatorForLanguageModeling + + >>> collator = DataCollatorForLanguageModeling(pad_token_id=0) + >>> examples = [{"input_ids": [1, 2, 3]}, {"input_ids": [4, 5]}] + >>> collator(examples) + {'input_ids': tensor([[ 1, 2, 3], + [ 4, 5, 0]]), + 'attention_mask': tensor([[ 1, 1, 1], + [ 1, 1, 0]]), + 'labels': tensor([[ 1, 2, 3], + [ 4, 5, -100]])} + + >>> # With prebuilt labels + >>> examples = [ + ... {"input_ids": [1, 2, 3], "labels": [-100, 2, 3]}, + ... {"input_ids": [4, 5], "labels": [-100, 5]}, + ... ] + >>> collator(examples) + {'input_ids': tensor([[ 1, 2, 3], + [ 4, 5, 0]]), + 'attention_mask': tensor([[ 1, 1, 1], + [ 1, 1, 0]]), + 'labels': tensor([[-100, 2, 3], + [-100, 5, -100]])} + + >>> # With padding_free + >>> collator = DataCollatorForLanguageModeling(pad_token_id=0, padding_free=True) + >>> collator(examples) + {'input_ids': tensor([[ 1, 2, 3, 4, 5]]), + 'position_ids': tensor([[0, 1, 2, 0, 1]]), + 'labels': tensor([[-100, 2, 3, -100, 5]])} + ``` + """ + + pad_token_id: int + max_length: int | None = None + truncation_mode: str = "keep_start" + padding_free: bool = False + pad_to_multiple_of: int | None = None + return_tensors: str = "pt" + + def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + input_ids = [example["input_ids"] for example in examples] + batch_seq_lengths = [example["seq_lengths"] for example in examples] if "seq_lengths" in examples[0] else None + labels = [example.get("labels", example["input_ids"]) for example in examples] + + # Truncate per sequence if necessary + if self.max_length is not None and not self.padding_free: + if self.truncation_mode == "keep_start": + sl = slice(None, self.max_length) + elif self.truncation_mode == "keep_end": + sl = slice(-self.max_length, None) + else: + raise ValueError( + f"Unsupported truncation mode: {self.truncation_mode}, expected 'keep_start' or 'keep_end'" + ) + input_ids = [ids[sl] for ids in input_ids] + labels = [lbl[sl] for lbl in labels] + + # Convert to tensor + input_ids = [torch.tensor(ids) for ids in input_ids] + labels = [torch.tensor(lbl) for lbl in labels] + + # For padding-free, we should NOT create attention_mask as it causes FlashAttention to ignore position_ids and + # compute wrong cu_seq_lens from the all-1s mask + if self.padding_free: + if batch_seq_lengths is not None: + position_ids = self.get_position_ids_from_packed_seq_lengths(batch_seq_lengths) + else: + position_ids = [torch.arange(len(ids)) for ids in input_ids] + else: + attention_mask = [torch.ones_like(ids) for ids in input_ids] + + # If padding_free, flatten everything into a single sequence + output = {} + if self.padding_free: + input_ids = [torch.cat(input_ids, dim=0)] + labels = [torch.cat(labels, dim=0)] + position_ids = [torch.cat(position_ids, dim=0)] + + # Pad + output["input_ids"] = pad( + input_ids, + padding_value=self.pad_token_id, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + output["labels"] = pad( + labels, padding_value=-100, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of + ) + if self.padding_free: + output["position_ids"] = pad( + position_ids, padding_value=0, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of + ) + output["labels"][output["position_ids"] == 0] = -100 + else: + output["attention_mask"] = pad( + attention_mask, padding_value=0, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of + ) + return output + + @staticmethod + def get_position_ids_from_packed_seq_lengths(batch_seq_lengths: list[list[int]]) -> list[torch.Tensor]: + """ + Get position IDs for packed sequences. + + Args: + batch_seq_lengths (`list[list[int]]`): + A list of lists containing the lengths of each individual document in the packed batch. + + Return: + `list[torch.Tensor]`: + A list of tensors containing the position IDs for each packed sequence. + """ + # Get lengths per row + example_lengths = [sum(seq_lengths) for seq_lengths in batch_seq_lengths] + # Flat list of lengths + batch_seq_lengths = torch.tensor( + [seq_length for seq_lengths in batch_seq_lengths for seq_length in seq_lengths] + ) + position_ids = torch.ones(sum(example_lengths), dtype=batch_seq_lengths.dtype) + position_ids[0] = 0 + # Reset position ids to 0 at the start of each sequence + position_ids[batch_seq_lengths[:-1].cumsum(0)] = -(batch_seq_lengths[:-1] - 1) + position_ids = position_ids.cumsum(0) + # Split back into one tensor per example + return list(position_ids.split(example_lengths)) + + +@dataclass +class DataCollatorForVisionLanguageModeling(DataCollatorMixin): + """ + Data collator for vision-language modeling tasks. + + Unlike text-only datasets, where the collator typically receives pre-tokenized inputs ready for batching, + vision-language data processing involves converting images into pixel values. This conversion is disk-intensive, + making upfront preprocessing of the entire dataset impractical. Therefore, this collator performs tokenization and + image processing on-the-fly to efficiently prepare batches. + + Each input example should be a dictionary containing at least: + - An `"images"` key holding a list of images, or an `"image"` key holding a single image. + - [language modeling](#language-modeling) type: either a `"messages"` key for conversational inputs or a `"text"` + key for standard text inputs. + - [prompt-completion](#prompt-completion) type: keys `"prompt"` and `"completion"` for the prompt and completion. + + The collator outputs a dictionary including: + - `"input_ids"`: Tensor of token IDs. + - `"attention_mask"`: Tensor indicating attention mask. + - `"pixel_values"`: Tensor representing image pixel values. + - `"labels"`: Tensor for training labels. + + Additional keys may be present depending on the processor, such as `"image_grid_thw"` or `"image_position_ids"`. + + Args: + processor ([`~transformers.ProcessorMixin`]): + The processor used to tokenize text and process images. It must be a subclass of + [`~transformers.ProcessorMixin`] and include a `tokenizer` with a defined `pad_token_id`. + max_length (`int`, *optional*): + Maximum sequence length for input tokens. If `None`, no truncation is applied. + completion_only_loss (`bool`, *optional*, defaults to `False`): + Whether to compute loss only on the completion part of the sequence. When `True`, the labels for the prompt + part are set to -100. It requires the dataset type to be prompt-completion. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + dataset_text_field (`str`, *optional*, defaults to `"text"`): + Name of the column that contains text data in the dataset. This parameter is only relevant for [standard + datasets format](dataset_formats#standard). + return_tensors (`str`, *optional*, defaults to `"pt"`): + The tensor type to return. Currently, only `"pt"` (PyTorch tensors) is supported. + + Example: + ```python + >>> from trl.trainer.sft_trainer import DataCollatorForVisionLanguageModeling + >>> from transformers import AutoProcessor + + >>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct") + >>> collator = DataCollatorForVisionLanguageModeling(processor) + >>> examples = [ + ... {"images": [Image.open("image_0.png")], "messages": [{"role": "user", "content": "What is this?"}]}, + ... {"images": [Image.open("image_1.png")], "messages": [{"role": "user", "content": "Describe this image."}]}, + ... ] + >>> collator(examples) + {'input_ids': tensor([[151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, + 151644, 872, 198, 151652, 151655, 151655, 151655, 151655, 151653, 3838, 374, + 419, 30, 151645, 198], + [151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, + 151644, 872, 198, 151652, 151655, 151655, 151655, 151655, 151653, 74785, 419, + 2168, 13, 151645, 198]]), + 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), + 'pixel_values': tensor([[-0.9893, 0.1785, 1.5362, ..., -0.0582, 0.8661, -0.2431], + [-0.2302, 0.9522, -1.1061, ..., 0.0555, 1.3354, -0.6412], + [ 1.2150, 0.9084, 0.7041, ..., 0.2404, -0.8403, -0.5133], + ..., + [ 0.6895, 0.2807, 0.2515, ..., -0.2004, -1.2100, 0.0555], + [ 0.8209, -0.9748, 1.5654, ..., 1.6055, -0.4706, 0.5817], + [-1.0915, 0.4559, 0.9230, ..., 0.5106, 0.0982, -0.1720]]), + 'image_grid_thw': tensor([[1, 4, 4], + [1, 4, 4]]), + 'labels': tensor([[151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, + 151644, 872, 198, 151652, 151655, 151655, 151655, 151655, 151653, 3838, 374, + 419, 30, 151645, 198], + [151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, + 151644, 872, 198, 151652, 151655, 151655, 151655, 151655, 151653, 74785, 419, + 2168, 13, 151645, 198]])} + ``` + """ + + processor: ProcessorMixin + max_length: int | None = None + completion_only_loss: bool = False # default not used in practice; SFTTrainer always passes the relevant value + pad_to_multiple_of: int | None = None + dataset_text_field: str = "text" + return_tensors: str = "pt" + + def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + if "messages" in examples[0] or self.dataset_text_field in examples[0]: + if self.completion_only_loss: + raise ValueError( + "The `completion_only_loss` argument is not supported for language modeling datasets." + ) + return self._collate_language_modeling(examples) + elif "prompt" in examples[0] and "completion" in examples[0]: + return self._collate_prompt_completion(examples) + else: + raise KeyError(f"Unexpected input keys in examples: {list(examples[0].keys())}.") + + def _collate_language_modeling(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + if "image" in examples[0]: + for example in examples: + example["images"] = [example.pop("image")] + images = [example["images"] for example in examples] + # Transformers requires at least one image in the batch, otherwise it throws an error + if all(img_list == [] for img_list in images): + images = None + + if "messages" in examples[0]: # conversational case + messages = [ + prepare_multimodal_messages(example["messages"], images=example["images"]) for example in examples + ] + texts = self.processor.apply_chat_template(messages) + elif self.dataset_text_field in examples[0]: # standard case + texts = [example[self.dataset_text_field] for example in examples] + else: + raise KeyError( + "The input examples must contain either 'messages' for conversational data or 'text' for standard " + "data." + ) + + output = self.processor( + images=images, + text=texts, + padding=True, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + truncation=self.max_length is not None, + max_length=self.max_length, + return_tensors=self.return_tensors, + add_special_tokens=False, # to avoid adding the BOS, twice see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens + ) + labels = output["input_ids"].clone() + labels[output["attention_mask"] == 0] = -100 + # We mask only padding tokens (-100) in the labels. Vision tokens are left unchanged because their handling in + # loss computation has to be done by the model, and masking them here would be infeasible in practice as vision + # token definitions vary across architectures. + output["labels"] = labels + return output + + def _collate_prompt_completion(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + if self.pad_to_multiple_of is not None: + raise NotImplementedError( + "Padding to a multiple of a value is not yet implemented for vision-language modeling and " + "prompt-completion data." + ) + if "image" in examples[0]: + for example in examples: + example["images"] = [example.pop("image")] + images = [example["images"] for example in examples] + # Transformers requires at least one image in the batch, otherwise it throws an error + if all(img_list == [] for img_list in images): + images = None + if is_conversational(examples[0]): # conversational case + for example in examples: + example["prompt"] = prepare_multimodal_messages(example["prompt"], images=example["images"]) + example["completion"] = prepare_multimodal_messages(example["completion"]) + examples = [apply_chat_template(example, self.processor) for example in examples] + + prompts = [example["prompt"] for example in examples] + completions = [example["completion"] for example in examples] + + processed_prompts = self.processor( + images=images, + text=prompts, + padding=True, + padding_side="left", + return_tensors=self.return_tensors, + add_special_tokens=False, # to avoid adding the BOS, twice see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens + ) + processed_completions = self.processor( + text=completions, + padding=True, + padding_side="right", + return_tensors=self.return_tensors, + add_special_tokens=False, # to avoid adding the BOS, twice see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens + ) + + # Concatenate prompts and completions + prompt_ids, prompt_mask = processed_prompts["input_ids"], processed_prompts["attention_mask"] + completion_ids, completion_mask = processed_completions["input_ids"], processed_completions["attention_mask"] + input_ids = torch.cat((prompt_ids, completion_ids), dim=1) + attention_mask = torch.cat((prompt_mask, completion_mask), dim=1) + completion_mask = torch.cat((torch.zeros_like(prompt_mask), completion_mask), dim=1) + if "token_type_ids" in processed_prompts: # special case for Gemma + prompt_token_type_ids = processed_prompts["token_type_ids"] + completion_token_type_ids = processed_completions["token_type_ids"] + token_type_ids = torch.cat((prompt_token_type_ids, completion_token_type_ids), dim=1) + if "mm_token_type_ids" in processed_prompts: # special case for ERNIE-VL + prompt_mm_token_type_ids = processed_prompts["mm_token_type_ids"] + completion_mm_token_type_ids = processed_completions.get( + "mm_token_type_ids", torch.zeros_like(completion_ids) + ) + mm_token_type_ids = torch.cat((prompt_mm_token_type_ids, completion_mm_token_type_ids), dim=1) + + # Flush left to reduce padding + if "token_type_ids" in processed_prompts and "mm_token_type_ids" in processed_prompts: + attention_mask, input_ids, completion_mask, token_type_ids, mm_token_type_ids = flush_left( + attention_mask, input_ids, completion_mask, token_type_ids, mm_token_type_ids + ) + elif "token_type_ids" in processed_prompts: + attention_mask, input_ids, completion_mask, token_type_ids = flush_left( + attention_mask, input_ids, completion_mask, token_type_ids + ) + elif "mm_token_type_ids" in processed_prompts: + attention_mask, input_ids, completion_mask, mm_token_type_ids = flush_left( + attention_mask, input_ids, completion_mask, mm_token_type_ids + ) + else: + attention_mask, input_ids, completion_mask = flush_left(attention_mask, input_ids, completion_mask) + + # Truncate if necessary + if self.max_length is not None: + input_ids = input_ids[:, : self.max_length] + attention_mask = attention_mask[:, : self.max_length] + completion_mask = completion_mask[:, : self.max_length] + if "token_type_ids" in processed_prompts: + token_type_ids = token_type_ids[:, : self.max_length] + if "mm_token_type_ids" in processed_prompts: + mm_token_type_ids = mm_token_type_ids[:, : self.max_length] + + # Create labels and mask padding tokens + labels = input_ids.clone() + labels[attention_mask == 0] = -100 + if self.completion_only_loss: + labels[completion_mask == 0] = -100 + + # Build the output dictionary + output = processed_prompts # we take processed_prompts because it contains the images + output["input_ids"] = input_ids + output["attention_mask"] = attention_mask + output["labels"] = labels + if "token_type_ids" in processed_prompts: + output["token_type_ids"] = token_type_ids + if "mm_token_type_ids" in processed_prompts: + output["mm_token_type_ids"] = mm_token_type_ids + return output + + +def dft_loss(outputs, labels, num_items_in_batch=None): + """ + DFT loss function, as presented in [On the Generalization of SFT: A Reinforcement Learning Perspective with Reward + Rectification](https://huggingface.co/papers/2508.05629) + """ + labels = nn.functional.pad(labels, (0, 1), value=-100) + shift_labels = labels[..., 1:] + loss_mask = shift_labels != -100 + shift_labels[~loss_mask] = 0 + logprobs = selective_log_softmax(outputs.logits, shift_labels) + per_token_loss = -logprobs.exp().detach() * logprobs + if num_items_in_batch is None: + num_items_in_batch = loss_mask.sum() + loss = (per_token_loss * loss_mask).sum() / num_items_in_batch + return loss + + +class SFTTrainer(_BaseTrainer): + """ + Trainer for Supervised Fine-Tuning (SFT) method. + + This class is a wrapper around the [`~transformers.Trainer`] class and inherits all of its attributes and methods. + + Example: + + ```python + >>> from trl import SFTTrainer + >>> from datasets import load_dataset + + >>> dataset = load_dataset("roneneldan/TinyStories", split="train[:1%]") + + >>> trainer = SFTTrainer( + ... model="Qwen/Qwen2.5-0.5B-Instruct", + ... train_dataset=dataset, + ... ) + >>> trainer.train() + ``` + + Args: + model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]): + Model to be trained. Can be either: + + - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using `.from_pretrained` (where `` is derived from the model + config) with the keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported. + - A [`~peft.PeftModel`] object. Only causal language models are supported. + args ([`SFTConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + data_collator ([`~transformers.DataCollator`], *optional*): + Function to use to form a batch from a list of elements of the processed `train_dataset` or `eval_dataset`. + Will default to [`~trainer.sft_trainer.DataCollatorForLanguageModeling`] if the model is a language model + and [`~trainer.sft_trainer.DataCollatorForVisionLanguageModeling`] if the model is a vision-language model. + Custom collators must truncate sequences before padding; the trainer does not apply post-collation + truncation. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + Dataset to use for training. This trainer supports both [language modeling](#language-modeling) type and + [prompt-completion](#prompt-completion) type. The format of the samples can be either: + + - [Standard](dataset_formats#standard): Each sample contains plain text. + - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role + and content). + + The trainer also supports processed datasets (tokenized) as long as they contain an `input_ids` field. + eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`): + Dataset to use for evaluation. It must meet the same requirements as `train_dataset`. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. If `None`, the processing class is loaded from the model's name + with [`~transformers.AutoProcessor.from_pretrained`]. A padding token, `tokenizer.pad_token`, must be set. + If the processing class has not set a padding token, `tokenizer.eos_token` will be used as the default. + compute_loss_func (`Callable`, *optional*): + A function that accepts the raw model outputs, labels, and the number of items in the entire accumulated + batch (batch_size * gradient_accumulation_steps) and returns the loss. For example, see the default [loss + function](https://github.com/huggingface/transformers/blob/052e652d6d53c2b26ffde87e039b723949a53493/src/transformers/trainer.py#L3618) + used by [`Trainer`]. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function that will be used to compute metrics at evaluation. Must take a + [`~transformers.EvalPrediction`] and return a dictionary string to metric values. When passing + [`SFTConfig`] with `batch_eval_metrics` set to `True`, your `compute_metrics` function must take a boolean + `compute_result` argument. This will be triggered after the last eval batch to signal that the function + needs to calculate and return the global summary statistics rather than accumulating the batch-level + statistics. + callbacks (list of [`~transformers.TrainerCallback`], *optional*): + List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed + in [here](https://huggingface.co/docs/transformers/main_classes/callback). + + If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`] + method. + optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`): + A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your + model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`. + optimizer_cls_and_kwargs (`tuple[Type[torch.optim.Optimizer], Dict[str, Any]]`, *optional*): + A tuple containing the optimizer class and keyword arguments to use. Overrides `optim` and `optim_args` in + `args`. Incompatible with the `optimizers` argument. + + Unlike `optimizers`, this argument avoids the need to place model parameters on the correct devices before + initializing the Trainer. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`, *optional*): + A function that preprocess the logits right before caching them at each evaluation step. Must take two + tensors, the logits and the labels, and return the logits once processed as desired. The modifications made + by this function will be reflected in the predictions received by `compute_metrics`. + + Note that the labels (second parameter) will be `None` if the dataset does not have them. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration used to wrap the model. If `None`, the model is not wrapped. + formatting_func (`Callable`, *optional*): + Formatting function applied to the dataset before tokenization. Applying the formatting function explicitly + converts the dataset into a [language modeling](#language-modeling) type. + """ + + _tag_names = ["trl", "sft"] + _name = "SFT" + + def __init__( + self, + model: "str | PreTrainedModel | PeftModel", + args: SFTConfig | TrainingArguments | None = None, + data_collator: DataCollator | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + compute_loss_func: Callable | None = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + optimizer_cls_and_kwargs: tuple[type[torch.optim.Optimizer], dict[str, Any]] | None = None, + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + peft_config: "PeftConfig | None" = None, + formatting_func: Callable[[dict], str] | None = None, + ): + # Args + if args is None: + model_name = model if isinstance(model, str) else get_config_model_id(model.config) + model_name = model_name.split("/")[-1] + args = SFTConfig(f"{model_name}-SFT") + elif isinstance(args, TrainingArguments) and not isinstance(args, SFTConfig): + dict_args = args.to_dict() + dict_args["hub_token"] = args.hub_token # to_dict hides the hub_token + if Version(transformers.__version__) < Version("5.0.0"): + dict_args.pop("push_to_hub_token") + args = SFTConfig(**dict_args) + + if train_dataset is None: + raise ValueError("`train_dataset` is required") + elif isinstance(train_dataset, IterableDataset): + # IterableDataset requires dispatch_batches=False because Accelerate's dispatch mode may try to concatenate + # batches from multiple processes, leading to mismatch errors. + if args.accelerator_config.dispatch_batches is True: + logger.warning( + "You are using an `IterableDataset` for training with `dispatch_batches=True`. `dispatch_batches` " + "is forced to `False` when using an `IterableDataset`. To remove this warning, unset " + "`dispatch_batches` in `SFTConfig` or set it to `False`." + ) + args.accelerator_config.dispatch_batches = False + + # Model + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) + model = create_model_from_path(model, **model_init_kwargs) + else: + if args.model_init_kwargs is not None: + logger.warning( + "You passed `model_init_kwargs` to the `SFTConfig`, but your model is already instantiated. " + "The `model_init_kwargs` will be ignored." + ) + # Non-quantized models do not have the `is_loaded_in_{8,4}bit` attributes, whereas quantized models do + _is_quantized_model = getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False) + + # Processing class + if processing_class is None: + processing_class = AutoProcessor.from_pretrained( + get_config_model_id(model.config), trust_remote_code=args.trust_remote_code + ) + + # Handle pad token for processors or tokenizers + if isinstance(processing_class, ProcessorMixin): + self._tokenizer = processing_class.tokenizer + self._is_vlm = True + elif isinstance(processing_class, PreTrainedTokenizerBase): + self._tokenizer = processing_class + self._is_vlm = False + else: + raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`") + + if args.eos_token is not None: + if args.eos_token not in self._tokenizer.get_vocab(): + raise ValueError( + f"The specified `eos_token` ('{args.eos_token}') is not found in the vocabulary of the given " + f"`processing_class` ({processing_class.__class__.__name__}). Ensure that the `eos_token` exists " + "in the vocabulary before using it as an EOS token." + ) + self._tokenizer.eos_token = args.eos_token + + if args.chat_template_path is not None: + if os.path.isfile(args.chat_template_path) and args.chat_template_path.endswith((".jinja", ".j2")): + with open(args.chat_template_path, encoding="utf-8") as chat_template_file: + processing_class.chat_template = chat_template_file.read() + added_tokens = [] + else: + model, processing_class, added_tokens = clone_chat_template( + model, processing_class, args.chat_template_path + ) + else: + added_tokens = [] + + # Catch some wrong configurations related to VLMs + if self._is_vlm and args.packing: + raise ValueError( + "Packing is not supported for vision-language models. Please set `packing=False` in the SFTConfig." + ) + if self._is_vlm and args.padding_free: + raise ValueError( + "Padding-free training is yet not supported for vision-language models. Please set " + "`padding_free=False` in the `SFTConfig`." + ) + if self._is_vlm and args.assistant_only_loss: + raise ValueError( + "Assistant-only loss is not yet supported for vision-language models. Please set " + "`assistant_only_loss=False` in the `SFTConfig`." + ) + if self._is_vlm and args.max_length is not None and args.truncation_mode == "keep_end": + raise ValueError( + "truncation_mode='keep_end' is not supported for vision-language models. Image tokens reside " + "inside the prompt portion of the sequence; depending on the example, keep_end may silently " + "drop them, causing pixel_values to be forwarded to the model with no corresponding visual " + "tokens in input_ids. Use truncation_mode='keep_start' (the default) or set max_length=None." + ) + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge " + "and unload the existing adapter, save the resulting base model, and then pass that base model along " + "with the new `peft_config` to the trainer." + ) + if added_tokens: + # Ensure that the added tokens are trainable + if peft_config.trainable_token_indices is None: + peft_config.trainable_token_indices = {"embed_tokens": added_tokens} + elif "embed_tokens" not in peft_config.trainable_token_indices: + peft_config.trainable_token_indices["embed_tokens"] = added_tokens + else: + peft_config.trainable_token_indices["embed_tokens"].extend(added_tokens) + # Ensure that the lm_head is trainable + if peft_config.modules_to_save is None or "lm_head" not in peft_config.modules_to_save: + logger.warning( + "Cloning chat template added new tokens to the tokenizer, but 'lm_head' is not in PEFT's " + "`modules_to_save`. As a result, the model may not learn to generate outputs with these new " + "tokens, leading to degraded generation quality. To fix this, add " + "`modules_to_save=['lm_head']` to your PEFT configuration." + ) + + if peft_config.modules_to_save is None: + peft_config.modules_to_save = ["lm_head"] + else: + peft_config.modules_to_save.append("lm_head") + # Create PEFT model + # ZeRO-3 + PEFT for non-quantized models: + # - PEFT's default autocast_adapter_dtype=True upcasts LoRA adapter params to fp32 even when the base model is bf16. + # - ZeRO-3's _allgather_params_coalesced allocates output buffers using the dtype of the first persistent parameter, + # so mixed-dtype persistent_parameters (bf16 base + fp32 LoRA) cause a TypeError on the first optimizer step. + # - Passing autocast_adapter_dtype=False keeps adapter params in the base model dtype (bf16), fixing the mismatch. + # - This is safe: the fp32 upcast is a QLoRA-specific concern (low-bit quantized base models), not needed for + # non-quantized bf16 training. + # - See: + # - TRL issue: https://github.com/huggingface/trl/issues/6089 + # - Upstream issue: https://github.com/deepspeedai/DeepSpeed/issues/8072 + # - autocast_adapter_dtype was introduced in PEFT 0.12.0; before, no upcast existed: no need to pass the kwarg + get_peft_model_kwargs = {} + if ( + args.deepspeed_plugin is not None + and args.deepspeed_plugin.zero_stage == 3 + and not _is_quantized_model + and Version(peft.__version__) >= Version("0.12.0") + ): + get_peft_model_kwargs["autocast_adapter_dtype"] = False + model = get_peft_model(model, peft_config, **get_peft_model_kwargs) + + # PEFT + DeepSpeed ZeRO-3 requires reentrant checkpointing. For more details, see + # https://github.com/huggingface/trl/issues/2514#issuecomment-2692152703 + if ( + is_peft_model(model) + and args.deepspeed_plugin is not None + and args.deepspeed_plugin.zero_stage == 3 + and args.gradient_checkpointing + ): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + use_reentrant = args.gradient_checkpointing_kwargs.get("use_reentrant") + if use_reentrant is False: + logger.warning( + "You are using PEFT with DeepSpeed ZeRO-3 and gradient checkpointing with `use_reentrant=False`. " + "`use_reentrant` is forced to `True` in this configuration to ensure correct training. To remove " + "this warning, unset `use_reentrant` in `gradient_checkpointing_kwargs` or set it to `True`." + ) + args.gradient_checkpointing_kwargs["use_reentrant"] = True + + # When using gradient checkpointing with PEFT, we need to enable input gradients. transformers.Trainer normally + # handles this, but a bug currently prevents it; see https://github.com/huggingface/transformers/issues/42489 + if is_peft_model(model) and args.gradient_checkpointing: + model.enable_input_require_grads() + + # When using QLoRA, the PEFT adapter weights are converted to bf16 to follow the recommendations from the + # original paper (see https://huggingface.co/papers/2305.14314, paragraph 3). Normally, this can be done by + # passing `autocast_adapter_dtype=False` to `get_peft_model`, but this option is not yet supported for + # quantized models. See: https://github.com/huggingface/peft/issues/2889 + if _is_quantized_model: + for param in model.parameters(): + if param.requires_grad: + param.data = param.data.to(torch.bfloat16) + + # In Prompt Tuning a small set of trainable virtual tokens (continuous prompt embeddings) is prepended to the + # input. We store the number of these tokens so we can account for them correctly when calculating accuracy. + self.num_virtual_tokens = 0 + if is_peft_model(model): + if model.active_adapter in model.peft_config: + peft_model_config = model.peft_config[model.active_adapter] + self.num_virtual_tokens = getattr(peft_model_config, "num_virtual_tokens", 0) + + # Data collator + # BFD packing requires padding-free mode; otherwise, the collator outputs padded attention masks, causing + # FlashAttention to ignore position_ids and recompute them incorrectly from the padded attention mask. + self.padding_free = args.padding_free or (args.packing and args.packing_strategy in {"bfd", "bfd_split"}) + use_flash_attention = model.config._attn_implementation in FLASH_ATTENTION_VARIANTS + if self.padding_free: + if data_collator is not None: + raise ValueError("Passing a custom data collator is not supported when using padding-free.") + if args.packing and args.packing_strategy == "wrapped": + logger.warning( + "You are passing `padding_free=True` with the 'wrapped' packing strategy, which is not " + "recommended. Please refer to the documentation to understand why this is not recommended." + ) + if not use_flash_attention: + logger.warning( + "Padding-free training is enabled, but the attention implementation is not set to a supported " + "Flash Attention variant. Padding-free training flattens batches into a single sequence, and only " + "the following implementations are known to reliably support this: " + f"{', '.join(sorted(FLASH_ATTENTION_VARIANTS))}. Using other implementations may lead to " + "unexpected behavior. To ensure compatibility, set `attn_implementation` in the model " + "configuration to one of these supported options or verify that your attention mechanism can " + "handle flattened sequences." + ) + + if args.per_device_train_batch_size == 1 and not args.packing: + logger.warning( + "You are using a per_device_train_batch_size of 1 with padding-free training. Using a batch size " + "of 1 annihilate the benefits of padding-free training. Please consider increasing the batch size " + "to at least 2." + ) + + # Decide whether to use completion-only loss: if not specified, then it is set to True if the dataset format + # is prompt-completion, and False if the dataset format is language modeling. + dataset_sample = next(iter(train_dataset)) + if args.completion_only_loss is None: + self.completion_only_loss = "prompt" in dataset_sample and "completion" in dataset_sample + else: + self.completion_only_loss = args.completion_only_loss + + self._is_vision_dataset = "image" in dataset_sample or "images" in dataset_sample + if self._is_vision_dataset and not self._is_vlm: + raise ValueError( + "The dataset appears to be vision-related (contains 'image' or 'images' keys), but the provided " + "model does not seem to be a vision-language model. Please check your model and dataset." + ) + + if data_collator is None and not self._is_vision_dataset: + # Get the pad token: if not provided, use the one from the processing class or the eos token + # if the processing class does not have a pad token. + pad_token = args.pad_token or self._tokenizer.pad_token or self._tokenizer.eos_token + if pad_token not in self._tokenizer.get_vocab(): + raise ValueError( + f"The specified `pad_token` ('{pad_token}') is not found in the vocabulary of the given " + f"`processing_class` ({processing_class.__class__.__name__}). Ensure that the `pad_token` exists " + "in the vocabulary before using it as a padding token." + ) + self._tokenizer.pad_token = pad_token + data_collator = DataCollatorForLanguageModeling( + pad_token_id=self._tokenizer.pad_token_id, + max_length=None if self.padding_free else args.max_length, + truncation_mode=args.truncation_mode, + padding_free=self.padding_free, + pad_to_multiple_of=args.pad_to_multiple_of, + ) + elif data_collator is None and self._is_vision_dataset: + data_collator = DataCollatorForVisionLanguageModeling( + processor=processing_class, + max_length=args.max_length, + completion_only_loss=self.completion_only_loss, + pad_to_multiple_of=args.pad_to_multiple_of, + dataset_text_field=args.dataset_text_field, + ) + + if args.packing and args.packing_strategy in {"bfd", "bfd_split"} and not use_flash_attention: + logger.warning( + "You are using packing, but the attention implementation is not set to a supported Flash Attention " + "variant. Packing gathers multiple samples into a single sequence, and only the following " + f"implementations are known to reliably support this: {', '.join(sorted(FLASH_ATTENTION_VARIANTS))}. " + "Using other implementations may lead to cross-contamination between samples. To avoid this, either " + "disable packing by setting `packing=False`, or set `attn_implementation` in the model configuration " + "to one of these supported options." + ) + if args.assistant_only_loss and not is_conversational(dataset_sample): + raise ValueError( + "You set `assistant_only_loss=True`, but the dataset is not conversational. This option is only " + "supported for conversational datasets." + ) + + # When assistant_only_loss is enabled, swap in a training chat template with {% generation %} markers + # if the current template doesn't already have them. + if args.assistant_only_loss and not has_generation_markers(processing_class.chat_template): + self.chat_template = get_training_chat_template(processing_class) + else: + self.chat_template = None + + # A template can define generation markers and still attribute the assistant's end-of-turn token to the next + # message, leaving it out of the assistant mask so the model is never trained to stop. + if args.assistant_only_loss and not is_chat_template_stop_token_trained( + processing_class, chat_template=self.chat_template + ): + logger.warning( + "The chat template does not include the assistant turn's end-of-turn token in the loss mask; " + "the model may not learn to stop." + ) + + # Dataset + if self.padding_free and not args.packing and args.max_length is not None and not self._is_vision_dataset: + raise ValueError( + "When `padding_free=True` without packing, `max_length` is not enforced. Either enable packing " + "(e.g., `packing=True, packing_strategy='bfd'`), provide already truncated inputs, or set " + "`max_length=None`." + ) + # Skip dataset preparation if `skip_prepare_dataset=True` in `dataset_kwargs`, or if it's a VLM, where + # preprocessing (e.g., image-to-pixel conversion) is too costly and done on the fly instead. + self._skip_prepare_dataset = ( + args.dataset_kwargs is not None + and args.dataset_kwargs.get("skip_prepare_dataset", False) + or self._is_vision_dataset + ) + # Kept on the instance so that `evaluate` can preprocess freshly-passed eval datasets the same way. + self._formatting_func = formatting_func + eval_datasets = ( + eval_dataset if isinstance(eval_dataset, dict) else {"eval": eval_dataset} if eval_dataset else {} + ) + self._reject_skip_prepare_without_labels({"train": train_dataset, **eval_datasets}, data_collator) + if not self._skip_prepare_dataset: + if self.completion_only_loss and formatting_func: + raise ValueError( + "A formatting function was provided while `completion_only_loss=True`, which is incompatible. " + "Using a formatter converts the dataset to a language modeling type, conflicting with " + "completion-only loss. To resolve this, apply your formatting function before passing the " + "dataset, or disable `completion_only_loss` in `SFTConfig`." + ) + train_dataset = self._prepare_dataset( + train_dataset, processing_class, args, args.packing, formatting_func, "train" + ) + if eval_dataset is not None: + packing = args.packing if args.eval_packing is None else args.eval_packing + if isinstance(eval_dataset, dict): + eval_dataset = { + key: self._prepare_dataset(dataset, processing_class, args, packing, formatting_func, key) + for key, dataset in eval_dataset.items() + } + else: + eval_dataset = self._prepare_dataset( + eval_dataset, processing_class, args, packing, formatting_func, "eval" + ) + + # Loss function + if not args.use_liger_kernel: # liger supports dft loss by just passing use_token_scaling=True + if args.loss_type == "nll": + pass # use the default loss + elif args.loss_type == "dft": + if compute_loss_func is not None: + raise ValueError( + "You passed a `compute_loss_func` together with `loss_type='dft'` to the `SFTTrainer`. " + "When using `loss_type='dft'`, the loss function is internally set to the DFT loss, so " + "passing a `compute_loss_func` is not allowed." + ) + compute_loss_func = dft_loss + elif args.loss_type == "chunked_nll": + # Same math as `"nll"` but the `lm_head` matmul is skipped on ignored tokens and the CE is computed in + # chunks of tokens. Implemented by patching the model's forward before `super().__init__` so accelerate + # wraps the patched forward. + # For PEFT, patch the inner causal LM rather than the `PeftModel` wrapper. LoRA / IA³ / + # `modules_to_save` adapters live in the module tree, so they're hit even when we bypass + # `PeftModel.forward`. Prompt-learning variants need `PeftModel.forward` to run first (to inject + # virtual tokens), then it delegates into the patched inner forward. + target = model.get_base_model() if is_peft_model(model) else model + # The chunked path reads the output projection weight directly, which would silently drop the + # adapter delta (and starve its parameters of gradients) if the head itself is a PEFT tuner layer. + if is_peft_model(model): + from peft.tuners.tuners_utils import BaseTunerLayer + + if isinstance(target.get_output_embeddings(), BaseTunerLayer): + raise ValueError( + "`loss_type='chunked_nll'` is not supported when `lm_head` is wrapped by a PEFT adapter " + "(e.g. `target_modules='all-linear'` or explicitly including `'lm_head'`). Either remove " + "`lm_head` from `target_modules`, or switch to `loss_type='nll'`. If this is a real use " + "case for you, please open an issue at https://github.com/huggingface/trl/issues." + ) + _patch_chunked_ce_lm_head(target, chunk_size=_CHUNKED_LM_HEAD_CHUNK_SIZE, is_vlm=self._is_vlm) + else: + raise ValueError( + f"Invalid `loss_type` {args.loss_type} passed. Supported values are 'nll', 'dft', and " + "'chunked_nll'." + ) + elif args.loss_type == "chunked_nll": + raise ValueError("`loss_type='chunked_nll'` is not compatible with `use_liger_kernel=True`.") + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + compute_loss_func=compute_loss_func, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + optimizer_cls_and_kwargs=optimizer_cls_and_kwargs, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Initialize activation offloading context + if self.args.activation_offloading: + self.maybe_activation_offload_context = get_act_offloading_ctx_manager(model=self.model) + else: + self.maybe_activation_offload_context = contextlib.nullcontext() + + # MoE load-balancing auxiliary loss, applied to Mixture-of-Experts models (no effect otherwise) + text_config = model.config.get_text_config() + is_moe = getattr(text_config, "output_router_logits", None) is not None + self.aux_loss_enabled = is_moe and self.args.router_aux_loss_coef != 0.0 + if is_moe: + # The native and chunked forwards add the aux loss from the model config, so keep the config in sync with + # the coef: enable it (and propagate the coef) when non-zero, disable it otherwise. This overrides any + # `output_router_logits` the model was loaded with, so `router_aux_loss_coef=0.0` reliably turns it off. + text_config.output_router_logits = self.aux_loss_enabled + text_config.router_aux_loss_coef = self.args.router_aux_loss_coef + + # Initialize the metrics + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + self._total_train_tokens = 0 + + # Add tags to the model + self.model.add_model_tags(self._tag_names) + + def _tokenize( + self, + processing_class: PreTrainedTokenizerBase | ProcessorMixin, + input: str | list, + **kwargs, + ) -> dict[str, list]: + """Tokenize a single example for dataset preprocessing. + + Dispatches to `apply_chat_template` for conversational input (list of message dicts) and to `__call__` for + non-conversational input (str). For VLMs, normalizes the batch dimension that processors emit even for single + examples. + + Args: + processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`]): + The tokenizer or processor to use. + input (`str` or `list`): + A string for non-conversational input, or a list of message dicts for conversational input. + **kwargs: + Forwarded to `apply_chat_template` (e.g. `add_generation_prompt`, `return_assistant_tokens_mask`). + + Returns: + `dict` with at least an `"input_ids"` key mapping to a flat `list[int]`. + """ + if isinstance(input, list): # conversational: list of message dicts + if self._is_vlm: + input = prepare_multimodal_messages(input) + result = processing_class.apply_chat_template( + input, tokenize=True, return_dict=True, chat_template=self.chat_template, **kwargs + ) + else: # non-conversational: plain text string + result = processing_class(text=input) + # VLMs emit a batch dimension even for single examples; unwrap it + if self._is_vlm: + return {k: v[0] for k, v in result.items()} + return result + + def _prepare_dataset( + self, + dataset: Dataset | IterableDataset, + processing_class: PreTrainedTokenizerBase | ProcessorMixin, + args: SFTConfig, + packing: bool, + formatting_func: Callable[[dict], str] | None, + dataset_name: str, + ) -> Dataset | IterableDataset: + if isinstance(dataset, Dataset) and dataset.format["type"] == "custom": + raise ValueError( + "SFTTrainer cannot prepare a dataset that uses `Dataset.with_transform()`. The preparation pipeline " + "calls `Dataset.map()`, which reads through the transform and can bake a random or stateful transform " + "into the tokenized columns. Pass `dataset_kwargs={'skip_prepare_dataset': True}` and make the " + "transform return trainer-ready examples, including tokenized fields, or materialize deterministic " + "transforms with `Dataset.map()` before constructing the trainer." + ) + + # If the dataset is already preprocessed (tokenized), skip the processing steps. + column_names = get_dataset_column_names(dataset) + is_processed = "input_ids" in column_names + + # Build the kwargs for the `map` function + map_kwargs = {} + if isinstance(dataset, Dataset): # IterableDataset does not support num_proc + map_kwargs["num_proc"] = args.dataset_num_proc + + with PartialState().main_process_first(): + # Apply the formatting function if any + if formatting_func is not None and is_processed: + logger.warning( + "You passed a dataset that is already processed (contains an `input_ids` field) together with a " + "formatting function. Therefore `formatting_func` will be ignored. Either remove the " + "`formatting_func` or pass a dataset that is not already processed.", + ) + + if formatting_func is not None and not is_processed: + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Applying formatting function to {dataset_name} dataset" + + def _func(example): + return {"text": formatting_func(example)} + + dataset = dataset.map(_func, batched=False, **map_kwargs) + + if not is_processed: + # Convert the dataset to ChatML if needed + first_example = next(iter(dataset)) + if is_conversational_from_value(first_example): + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Converting {dataset_name} dataset to ChatML" + column_names = get_dataset_column_names(dataset) + dataset = dataset.map( + maybe_convert_to_chatml, + remove_columns="conversations" if "conversations" in column_names else None, + **map_kwargs, + ) + + # Add EOS token if needed: non-conversational only + first_example = next(iter(dataset)) + if not is_conversational(first_example): + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Adding EOS to {dataset_name} dataset" + + def add_eos(example, eos_token): + if "text" in example and not example["text"].endswith(eos_token): # language modeling case + example["text"] = example["text"] + eos_token + elif "completion" in example and not example["completion"].endswith(eos_token): + example["completion"] = example["completion"] + eos_token + return example + + dataset = dataset.map( + add_eos, + fn_kwargs={"eos_token": self._tokenizer.eos_token}, + remove_columns="messages" if "messages" in column_names else None, # renamed to "text" + **map_kwargs, + ) + + # Tokenize the dataset + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Tokenizing {dataset_name} dataset" + + def tokenize_fn(example, processing_class, dataset_text_field, assistant_only_loss): + tools = example.get("tools") + tools = json.loads(tools) if isinstance(tools, str) else tools + if "prompt" in example: # prompt-completion case + output = {} + if is_conversational(example): + prompt_ids = self._tokenize( + processing_class, + example["prompt"], + tools=tools, + add_generation_prompt=True, + **example.get("chat_template_kwargs", {}), + )["input_ids"] + prompt_completion_processed = self._tokenize( + processing_class, + example["prompt"] + example["completion"], + tools=tools, + return_assistant_tokens_mask=assistant_only_loss, + **example.get("chat_template_kwargs", {}), + ) + prompt_completion_ids = prompt_completion_processed["input_ids"] + if "assistant_masks" in prompt_completion_processed: + output["assistant_masks"] = prompt_completion_processed["assistant_masks"] + else: + prompt_ids = self._tokenize(processing_class, example["prompt"])["input_ids"] + prompt_completion_ids = self._tokenize( + processing_class, example["prompt"] + example["completion"] + )["input_ids"] + + # Check if the tokenized prompt starts with the tokenized prompt+completion + if not prompt_completion_ids[: len(prompt_ids)] == prompt_ids: + logger.warning( + "Mismatch between tokenized prompt and the start of tokenized prompt+completion. " + "This may be due to unexpected tokenizer behavior, whitespace issues, or special " + "token handling. Verify that the tokenizer is processing text consistently." + ) + + # Create completion mask + completion_mask = [0] * len(prompt_ids) + [1] * (len(prompt_completion_ids) - len(prompt_ids)) + output["input_ids"] = prompt_completion_ids + output["completion_mask"] = completion_mask + + else: # language modeling case + if is_conversational(example): + processed = self._tokenize( + processing_class, + example["messages"], + tools=tools, + return_assistant_tokens_mask=assistant_only_loss, + **example.get("chat_template_kwargs", {}), + ) + output = {k: processed[k] for k in ("input_ids", "assistant_masks") if k in processed} + else: + output = { + "input_ids": self._tokenize(processing_class, example[dataset_text_field])["input_ids"] + } + + if "assistant_masks" in output and 1 not in output["assistant_masks"]: + raise RuntimeError( + "You're using `assistant_only_loss=True`, but at least one example has no assistant " + "tokens. This usually means the tokenizer's chat template doesn't generate assistant " + "masks — it may be missing the `{% generation %}` keyword. Please check the template and " + "ensure it's correctly configured to support assistant masking." + ) + return output + + dataset = dataset.map( + tokenize_fn, + fn_kwargs={ + "processing_class": processing_class, + "dataset_text_field": args.dataset_text_field, + "assistant_only_loss": args.assistant_only_loss, + }, + **map_kwargs, + ) + + # Build a "labels" column, setting tokens that shouldn't contribute to the loss to -100 based on the + # available masks: "assistant_masks" always applies, "completion_mask" only when completion_only_loss + # is enabled. With no applicable mask, every token contributes (labels == input_ids). A dataset that + # already provides a "labels" column is left as is. + column_names = get_dataset_column_names(dataset) + if "labels" not in column_names: + mask_columns = [] + if self.completion_only_loss and "completion_mask" in column_names: + mask_columns.append("completion_mask") + if "assistant_masks" in column_names: + mask_columns.append("assistant_masks") + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Building labels for {dataset_name} dataset" + + def build_labels(example, mask_columns): + masks = [example[column] for column in mask_columns] + labels = [ + token_id if all(bits) else -100 + for token_id, *bits in zip(example["input_ids"], *masks, strict=False) + ] + return {"labels": labels} + + dataset = dataset.map(build_labels, fn_kwargs={"mask_columns": mask_columns}, **map_kwargs) + + # Pack + if packing: + if args.max_length is None: + raise ValueError("When packing is enabled, `max_length` can't be `None`.") + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Packing {dataset_name} dataset" + + dataset = dataset.select_columns(["input_ids", "labels"]) + + # Shuffle the dataset before packing. When using wrapped packing, it's important to shuffle before + # packing as well to avoid correlations between sequences packed together. + if args.shuffle_dataset: + dataset = dataset.shuffle(seed=args.seed) + + # Packing adds new column "seq_lengths" needed for document aware FlashAttention + dataset = pack_dataset(dataset, args.max_length, args.packing_strategy, map_kwargs) + # For Liger kernel, ensure only the essential columns + if args.use_liger_kernel: + collator_expected_keys = {"input_ids", "seq_lengths", "labels"} + column_names = get_dataset_column_names(dataset) + dataset = dataset.select_columns(collator_expected_keys.intersection(column_names)) + + if args.shuffle_dataset: + dataset = dataset.shuffle(seed=args.seed) + + return dataset + + def _set_signature_columns_if_needed(self): + # If `self.args.remove_unused_columns` is True, non-signature columns are removed. + # By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids", + # "attention_mask" and "labels"). Dataset preparation also produces a "seq_lengths" column (for packing / + # padding-free), so we override the default signature columns to keep it alongside the model inputs. + if self._signature_columns is None: + if self._is_vision_dataset: + self._signature_columns = ["messages", "prompt", "completion", "image", "images"] + else: + self._signature_columns = ["input_ids", "labels", "seq_lengths"] + + def _reject_skip_prepare_without_labels(self, datasets: dict[str, Dataset], data_collator) -> None: + # This guard may look defensive, but it covers a behavior change introduced when label building moved from + # the collator to dataset preparation: the collator used to consume the mask columns directly, so a + # skipped-preparation dataset carrying masks trained correctly. Now labels are built during preparation, which + # is skipped here, and the collator ignores the mask columns. Without a "labels" column, such a dataset would + # silently optimize the loss over the full sequence, so we fail loudly instead. Checked both at init and in + # `evaluate`, since a dataset passed directly to `evaluate` also skips preparation. + if not ( + self._skip_prepare_dataset + and not self._is_vision_dataset + and isinstance(data_collator, DataCollatorForLanguageModeling) + ): + return + for name, dataset in datasets.items(): + cols = get_dataset_column_names(dataset) + if "labels" not in cols and ("completion_mask" in cols or "assistant_masks" in cols): + raise ValueError( + f"The {name} dataset has mask columns but no 'labels', and `skip_prepare_dataset=True` skips " + "label building, so it would train on the full sequence. Add a 'labels' column (-100 for " + "non-loss tokens) or drop `skip_prepare_dataset`." + ) + + def evaluate( + self, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + ignore_keys: list[str] | None = None, + metric_key_prefix: str = "eval", + ) -> dict[str, float]: + # When a dataset is passed directly to `evaluate` (e.g. a held-out test set), preprocess it the same way + # `__init__` does, so that `evaluate` accepts the same dataset types as the trainer (language modeling, + # prompt-completion, etc.). `_prepare_dataset` is idempotent: it skips datasets that are already tokenized. A + # `str` selects a dataset that was already prepared at init time, so it's left untouched. + if not self._skip_prepare_dataset and eval_dataset is not None and not isinstance(eval_dataset, str): + packing = self.args.packing if self.args.eval_packing is None else self.args.eval_packing + if isinstance(eval_dataset, dict): + eval_dataset = { + key: self._prepare_dataset( + dataset, self.processing_class, self.args, packing, self._formatting_func, key + ) + for key, dataset in eval_dataset.items() + } + else: + eval_dataset = self._prepare_dataset( + eval_dataset, self.processing_class, self.args, packing, self._formatting_func, "eval" + ) + eval_datasets = ( + eval_dataset + if isinstance(eval_dataset, dict) + else {"eval": eval_dataset} + if eval_dataset is not None and not isinstance(eval_dataset, str) + else {} + ) + self._reject_skip_prepare_without_labels(eval_datasets, self.data_collator) + return super().evaluate( + eval_dataset=eval_dataset, ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix + ) + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + mode = "train" if self.model.training else "eval" + prediction_loss_only = inputs.pop("_prediction_loss_only", None) + + # Set aside labels as it will be dropped by super().compute_loss() if a custom `compute_loss_func` is used. + # This can be removed when this issue is fixed. + # When using CP or SP, labels are pre-shifted, we must use shift_labels instead. + labels = inputs["labels"] if "shift_labels" not in inputs else None + + # If not set, defaults from model config and may warn since cache isn't compatible with gradient checkpointing + inputs["use_cache"] = False + + # MoE models: request router logits so the model returns `outputs.aux_loss`. VLM wrappers honor this only + # as a forward kwarg (not from the model config), so it must be passed here. + if self.aux_loss_enabled: + inputs["output_router_logits"] = True + + # Request token accuracy from Liger kernel and set token scaling if using DFT loss + if self.args.use_liger_kernel: + # Avoid materializing full logits during eval unless explicitly needed. + # By default, liger kernel only skips logits during training (self.training=True). + # When only loss is needed for eval (no compute_metrics), we can safely skip logits. + # prediction_step communicates whether logits are expected via `_prediction_loss_only`; + # this prevents skipping logits during `predict()` where outputs are requested. + # Keep logits when preprocess_logits_for_metrics is set, even if compute_metrics is None. + # to prevent massive vRAM spikes from the lm_head projection. + # See: https://github.com/huggingface/trl/issues/4679 + inputs["skip_logits"] = ( + self.model.training + or self.args.prediction_loss_only + or ( + self.compute_metrics is None + and self.preprocess_logits_for_metrics is None + and prediction_loss_only is not False + ) + ) + inputs["return_token_accuracy"] = True + inputs["use_token_scaling"] = self.args.loss_type == "dft" + + try: + (loss, outputs) = super().compute_loss( + model, inputs, return_outputs=True, num_items_in_batch=num_items_in_batch + ) + except ValueError as e: + if "Image features and image tokens do not match" in str(e) and self.args.max_length is not None: + raise ValueError( + f"The current `max_length` ({self.args.max_length}) is too short and causes image placeholder " + f"tokens in `input_ids` to be truncated, while the corresponding image features remain intact. " + f"Please increase `max_length` or set it to `None` to disable truncation." + ) from e + raise + + # Compute entropy + if self.args.loss_type == "chunked_nll": + # Use `num_valid_tokens` from the patched forward rather than recomputing from `labels`. Prompt-learning + # PEFT (PromptTuning, P-Tuning) prepends `-100`-padded virtual tokens before delegating into the patched + # forward, so the valid-token count over the padded labels can differ from the un-padded `labels[..., 1:]` + # count by up to one per sequence; using the patched output keeps numerator and denominator aligned. + num_valid = self.accelerator.gather_for_metrics(outputs.num_valid_tokens).sum() + entropy_sum = self.accelerator.gather_for_metrics(outputs.entropy_sum).sum() + entropy = (entropy_sum / num_valid).item() if num_valid > 0 else 0.0 + self._metrics[mode]["entropy"].append(entropy) + elif not self.args.use_liger_kernel: # liger doesn't return logits + with torch.no_grad(): + if "shift_labels" in inputs: + # When using CP or SP, labels are pre-shifted. + shift_logits = outputs.logits + shift_labels = inputs["shift_labels"] + else: + shift_logits = outputs.logits[..., :-1, :] + shift_labels = labels[..., 1:] + + # Prompt Tuning and P-Tuning output logits for virtual tokens but Prefix-Tuning does not. + if ( + self.num_virtual_tokens > 0 + and model.peft_config[model.active_adapter].peft_type != PeftType.PREFIX_TUNING + ): + shift_logits = shift_logits[:, self.num_virtual_tokens :, :] + + per_token_entropy = entropy_from_logits(shift_logits) + predictions = shift_logits.argmax(dim=-1) + mask = shift_labels != -100 + + entropy_sum = (per_token_entropy * mask).sum() + total_tokens = mask.sum() + correct_predictions = (predictions == shift_labels) & mask + correct_tokens = correct_predictions.sum() + + # Gather counts across ranks and weight-average + entropy_sum = self.accelerator.gather_for_metrics(entropy_sum).sum() + total_tokens = self.accelerator.gather_for_metrics(total_tokens).sum() + correct_tokens = self.accelerator.gather_for_metrics(correct_tokens) + entropy = (entropy_sum / total_tokens).item() if total_tokens > 0 else 0.0 + + total_sum = total_tokens.sum() + accuracy = (correct_tokens.sum() / total_sum).item() if total_sum > 0 else 0.0 + self._metrics[mode]["entropy"].append(entropy) + self._metrics[mode]["mean_token_accuracy"].append(accuracy) + + if mode == "train": + # When using padding-free, the attention_mask is not present in the inputs, instead we have cu_seq_lens_q, + # cu_seq_lens_k, and max_length_k, max_length_q and position_ids. + if "attention_mask" in inputs: + num_tokens_in_batch = self.accelerator.gather_for_metrics(inputs["attention_mask"].sum()).sum().item() + elif "position_ids" in inputs: + local_num_tokens = torch.tensor(inputs["position_ids"].size(1), device=inputs["position_ids"].device) + num_tokens_in_batch = self.accelerator.gather_for_metrics(local_num_tokens).sum().item() + else: + raise ValueError("Expected 'attention_mask' or 'position_ids' in inputs.") + self._total_train_tokens += num_tokens_in_batch + self._metrics[mode]["num_tokens"] = [self._total_train_tokens] + + if self.args.loss_type == "chunked_nll": + correct = self.accelerator.gather_for_metrics(outputs.num_correct_tokens).sum() + accuracy = (correct / num_valid).item() if num_valid > 0 else 0.0 + self._metrics[mode]["mean_token_accuracy"].append(accuracy) + elif self.args.use_liger_kernel: + if hasattr(outputs, "token_accuracy") and outputs.token_accuracy is not None: + token_accuracy = self.accelerator.gather_for_metrics(outputs.token_accuracy).mean().item() + self._metrics[mode]["mean_token_accuracy"].append(token_accuracy) + else: + warnings.warn( + "liger-kernel did not return token_accuracy when requested. The mean_token_accuracy metric will " + "not be logged. This is unexpected; please report it to the liger-kernel repository.", + stacklevel=2, + ) + # Log auxiliary loss if enabled (applies to both Liger and non-Liger) + if self.aux_loss_enabled: + aux_loss = outputs.aux_loss + aux_loss = self.accelerator.gather_for_metrics(aux_loss).mean().item() + self._metrics[mode]["aux_loss"].append(aux_loss) + + return (loss, outputs) if return_outputs else loss + + def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys=None): + # Preserve the eval loop intent so compute_loss can decide whether logits are needed. + inputs["_prediction_loss_only"] = prediction_loss_only + return super().prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys) + + # Override training step to add activation offloading context. + def training_step(self, *args, **kwargs): + with self.maybe_activation_offload_context: + return super().training_step(*args, **kwargs) + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} # average the metrics + + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/utils.py b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0e3753e4fdc56de8811254bc3e7716f5bdac18ba --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/environment/source/trl/trainer/utils.py @@ -0,0 +1,1525 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import asyncio +import hashlib +import importlib.resources as pkg_resources +import os +import random +import socket +import threading +import types +from collections.abc import Mapping, Sequence, Sized +from contextlib import contextmanager +from importlib.metadata import version +from itertools import accumulate +from typing import TypeVar + +import numpy as np +import pandas as pd +import torch +import torch.nn.functional as F +import transformers +from accelerate import PartialState +from accelerate.logging import get_logger +from huggingface_hub import ModelCard, ModelCardData +from packaging.version import Version +from torch.utils.data import Sampler +from transformers import ( + AutoConfig, + AutoModelForCausalLM, + AutoModelForImageTextToText, + BitsAndBytesConfig, + PretrainedConfig, + PreTrainedModel, + is_comet_available, + is_trackio_available, +) +from transformers.models.auto.auto_factory import _BaseAutoModelClass +from transformers.utils import ( + is_peft_available, + is_rich_available, + is_torch_xpu_available, +) + +from ..trainer.model_config import ModelConfig + + +if is_rich_available(): + from rich.console import Console + from rich.panel import Panel + from rich.table import Table + from rich.text import Text + +if is_comet_available(): + import comet_ml + +if is_peft_available(): + from peft import LoraConfig, PeftConfig, PeftModel + + +logger = get_logger(__name__) + + +def _is_port_free(port: int, host: str = "127.0.0.1") -> bool: + try: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + s.bind((host, port)) + return True + except OSError: + return False + + +def _find_free_port() -> int: + candidates = (29500, 23456, 12355, 12345) + for p in candidates: + if _is_port_free(p): + return p + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("", 0)) + return s.getsockname()[1] + + +def ensure_master_addr_port(addr: str | None = None, port: int | None = None) -> None: + """ + Ensure `MASTER_ADDR`/`MASTER_PORT` are set safely. + + - Respects existing environment variables. + - Defaults `MASTER_ADDR` to localhost if unset. + - Chooses a free TCP port if `MASTER_PORT` is unset to avoid collisions. + - If `MASTER_PORT` is set to `"0"` or `"auto"`, it is resolved to a free port. + """ + os.environ["MASTER_ADDR"] = os.environ.get("MASTER_ADDR") or addr or "localhost" + + env_port = os.environ.get("MASTER_PORT", "").strip().lower() + if port is None and env_port not in {"", "0", "auto"}: + try: + port = int(env_port) + except ValueError: + pass + + os.environ["MASTER_PORT"] = str(_find_free_port() if port in (None, 0) else port) + + +def pad( + tensors: list[torch.Tensor], + padding_value: int = 0, + padding_side: str = "right", + pad_to_multiple_of: int | None = None, +) -> torch.Tensor: + """ + Pads a list of tensors to the same shape along the first dimension. + + Args: + tensors (`list[torch.Tensor]`): + List of input tensors to pad. + padding_value (`int`): + Value to use for padding. Default is 0. + padding_side (`str`): + Side on which to add padding. Must be 'left' or 'right'. Default is 'right'. + pad_to_multiple_of (`int`, *optional*): + If set will pad the sequence to a multiple of the provided value. + + Returns: + `torch.Tensor`: + A single tensor containing the padded tensors. + + Examples: + ```python + >>> import torch + + >>> pad([torch.tensor([1, 2, 3]), torch.tensor([4, 5])]) + tensor([[1, 2, 3], + [4, 5, 0]]) + + >>> pad([torch.tensor([[1, 2], [3, 4]]), torch.tensor([[5, 6]])]) + tensor([[[1, 2], + [3, 4]], + [[5, 6], + [0, 0]]]) + ``` + """ + # Determine the maximum shape for each dimension + output_shape = np.max([t.shape for t in tensors], 0).tolist() + + # Apply pad_to_multiple_of to the first (sequence) dimension + if pad_to_multiple_of is not None: + remainder = output_shape[0] % pad_to_multiple_of + if remainder != 0: + output_shape[0] += pad_to_multiple_of - remainder + + # Create an output tensor filled with the padding value + output = torch.full((len(tensors), *output_shape), padding_value, dtype=tensors[0].dtype, device=tensors[0].device) + + for i, t in enumerate(tensors): + if padding_side == "left": + seq_start = output_shape[0] - t.shape[0] + elif padding_side == "right": + seq_start = 0 + else: + raise ValueError("padding_side must be 'left' or 'right'") + + # Define the slices + seq_slice = slice(seq_start, seq_start + t.shape[0]) + slices = (seq_slice,) + tuple(slice(0, s) for s in t.shape[1:]) + output[i][slices] = t + + return output + + +def disable_dropout_in_model(model: torch.nn.Module) -> None: + for module in model.modules(): + if isinstance(module, torch.nn.Dropout): + module.p = 0 + + +def get_quantization_config(model_args: ModelConfig) -> BitsAndBytesConfig | None: + if model_args.load_in_4bit: + quantization_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_compute_dtype=model_args.dtype, # For consistency with model weights, we use the same value as `dtype` + bnb_4bit_quant_type=model_args.bnb_4bit_quant_type, + bnb_4bit_use_double_quant=model_args.use_bnb_nested_quant, + bnb_4bit_quant_storage=model_args.bnb_4bit_quant_storage, + ) + elif model_args.load_in_8bit: + quantization_config = BitsAndBytesConfig( + load_in_8bit=True, + ) + else: + quantization_config = None + + return quantization_config + + +def get_kbit_device_map() -> dict[str, int] | None: + if torch.cuda.is_available() or is_torch_xpu_available(): + return {"": PartialState().local_process_index} + else: + return None + + +def get_peft_config(model_args: ModelConfig) -> "PeftConfig | None": + if model_args.use_peft is False: + return None + + if not is_peft_available(): + raise ValueError( + "You need to have PEFT library installed in your environment, make sure to install `peft`. " + "Make sure to run `pip install -U peft`." + ) + + peft_config = LoraConfig( + task_type=model_args.lora_task_type, + r=model_args.lora_r, + target_modules=model_args.lora_target_modules, + target_parameters=model_args.lora_target_parameters, + lora_alpha=model_args.lora_alpha, + lora_dropout=model_args.lora_dropout, + bias="none", + use_rslora=model_args.use_rslora, + use_dora=model_args.use_dora, + modules_to_save=model_args.lora_modules_to_save, + ) + + return peft_config + + +def generate_model_card( + base_model: str | None, + model_name: str, + hub_model_id: str, + dataset_name: str | None, + tags: list[str], + wandb_url: str | None, + trackio_url: str | None, + trainer_name: str, + trainer_citation: str | None = None, + template_file: str | None = None, + paper_title: str | None = None, + paper_id: str | None = None, + comet_url: str | None = None, +) -> ModelCard: + """ + Generate a [`~huggingface_hub.ModelCard`] from a template. + + Args: + base_model (`str` or `None`): + Base model name. + model_name (`str`): + Model name. + hub_model_id (`str`): + Hub model ID as `username/model_id`. + dataset_name (`str` or `None`): + Dataset name. + tags (`list[str]`): + Tags. + wandb_url (`str` or `None`): + Weights & Biases run URL. + trackio_url (`str` or `None`): + Trackio Space URL. + comet_url (`str` or `None`): + Comet experiment URL. + trainer_name (`str`): + Trainer name. + trainer_citation (`str` or `None`, defaults to `None`): + Trainer citation as a BibTeX entry. + template_file (`str` *optional*): + Template file name located in the `trl/templates` directory. Defaults to `lm_model_card.md`. + paper_title (`str` or `None`, defaults to `None`): + Paper title. + paper_id (`str` or `None`, defaults to `None`): + ArXiv paper ID as `YYMM.NNNNN`. + + Returns: + [`~huggingface_hub.ModelCard`]: + A ModelCard object. + """ + card_data = ModelCardData( + base_model=base_model, + datasets=dataset_name, + library_name="transformers", + licence="license", + model_name=model_name, + tags=["generated_from_trainer", *tags], + ) + template_file = template_file or "lm_model_card.md" + card = ModelCard.from_template( + card_data, + template_path=str(pkg_resources.files("trl").joinpath(f"templates/{template_file}")), + base_model=base_model, + model_name=model_name, + hub_model_id=hub_model_id, + dataset_name=dataset_name, + wandb_url=wandb_url, + trackio_url=trackio_url, + comet_url=comet_url, + trainer_name=trainer_name, + trainer_citation=trainer_citation, + paper_title=paper_title, + paper_id=paper_id, + trl_version=version("trl"), + transformers_version=version("transformers"), + pytorch_version=version("torch"), + datasets_version=version("datasets"), + tokenizers_version=version("tokenizers"), + ) + return card + + +def get_comet_experiment_url() -> str | None: + """ + If Comet integration is enabled, return the URL of the current Comet experiment; otherwise, return `None`. + """ + if not is_comet_available(): + return None + + if comet_ml.get_running_experiment() is not None: + return comet_ml.get_running_experiment().url + + return None + + +def get_trackio_space_url() -> str | None: + """ + If Trackio integration is enabled, return the URL of the current Trackio Space; otherwise, return `None`. + """ + if not is_trackio_available(): + return None + + from trackio import context_vars + + run = context_vars.current_run.get() + if run is None: + return None + space_id = run._space_id + if space_id is None: + return None + space_id = space_id.replace("/", "-") + project = run.project + name = run.name + return f"https://{space_id}.hf.space?project={project}&runs={name}&sidebar=collapsed" + + +def log_table_to_comet_experiment(name: str, table: pd.DataFrame) -> None: + """ + If Comet integration is enabled logs a table to the Comet experiment if it is currently running. + + Args: + name (`str`): + Table name. + table (`pandas.DataFrame`): + The Pandas DataFrame containing the table to log. + """ + if not is_comet_available(): + raise ModuleNotFoundError("The comet-ml is not installed. Please install it first: pip install comet-ml") + + experiment = comet_ml.get_running_experiment() + if experiment is not None: + experiment.log_table(tabular_data=table, filename=name) + + +def flush_left(mask: torch.Tensor, *tensors: torch.Tensor) -> torch.Tensor | tuple[torch.Tensor, ...]: + """ + Shift non-zero elements in the mask and corresponding tensors to the left. + + This function operates on a binary mask and any number of additional tensors with the same dimensions as the mask. + For each row, non-zero values are shifted to the leftmost positions. Then, columns that contain only zeros across + all rows are truncated from the mask and tensors. Visually, this operation can be represented as follows: + + ``` + [[0, 0, x, x, x, x], -> [[x, x, x, x], + [0, x, x, x, 0, 0]] [x, x, x, 0]] + ``` + + Args: + mask (`torch.Tensor`): + 2D tensor (binary mask) with shape `(N, M)`. + *tensors (`torch.Tensor`): + One or more 2D tensors with the same shape as `mask`. These tensors will be processed alongside `mask`, + with non-zero values shifted and excess zero columns truncated in the same manner. + + Returns: + `torch.Tensor`: + Updated binary mask with non-zero values flushed to the left and trailing zero columns removed. + `*torch.Tensor` + Updated tensors, processed in the same way as the mask. + + Example: + ```python + >>> mask = torch.tensor([[0, 0, 1, 1, 1], [0, 1, 1, 0, 0]]) + >>> tensor = torch.tensor([[9, 9, 2, 3, 4], [9, 5, 6, 9, 9]]) + >>> new_mask, new_tensor = flush_left(mask, tensor) + >>> print(new_mask) + tensor([[1, 1, 1], + [1, 1, 0]]) + + >>> print(new_tensor) + tensor([[2, 3, 4], + [5, 6, 0]]) + ``` + """ + _, M = mask.shape + + # Create copy of mask and tensors + mask_copy = mask.clone() + tensors = [t.clone() for t in tensors] + + # Shift non-zero values to the left + first_non_zero = mask_copy.argmax(dim=1) + pos = torch.arange(M, device=mask_copy.device).unsqueeze(0) + idx_roll = (pos + first_non_zero.unsqueeze(1)) % M + mask_roll = mask_copy.gather(1, idx_roll) + rolled_tensors = [t.gather(1, idx_roll) for t in tensors] + + # Truncate trailing columns that are all zeros in mask_roll + col_sums = mask_roll.sum(dim=0) + empty_cols = col_sums == 0 + first_empty_col = int(empty_cols.to(torch.int8).argmax()) if empty_cols.any() else M + flushed_mask = mask_roll[:, :first_empty_col] + flushed_tensors = [t[:, :first_empty_col] for t in rolled_tensors] + + if not flushed_tensors: + return flushed_mask + return flushed_mask, *flushed_tensors + + +def selective_log_softmax(logits, index) -> torch.Tensor: + """ + A memory-efficient implementation of the common `log_softmax -> gather` operation. + + This function is equivalent to the following naive implementation: + ```python + # for index with shape (...): + logps = torch.gather(logits.log_softmax(-1), dim=-1, index=index.unsqueeze(-1)).squeeze(-1) + # for index with shape (..., K): + logps = torch.gather(logits.log_softmax(-1), dim=-1, index=index) + ``` + + Args: + logits (`torch.Tensor`): + Logits tensor of shape `(..., num_classes)`. + index (`torch.Tensor`): + Index tensor of shape `(..., K)` or `(...)`, specifying the positions to gather from the log-softmax + output. When the last case is used, `K` log-probabilities are gathered per position (e.g. for top-K) + + Returns: + `torch.Tensor`: + Gathered log probabilities with the same shape as `index`. + """ + squeeze = index.ndim == logits.ndim - 1 + if squeeze: + index = index.unsqueeze(-1) + + if logits.dtype in [torch.float32, torch.float64]: + selected_logits = torch.gather(logits, dim=-1, index=index) + # loop to reduce peak mem consumption + logsumexp_values = torch.stack([torch.logsumexp(lg, dim=-1) for lg in logits]) + per_token_logps = selected_logits - logsumexp_values.unsqueeze(-1) # log_softmax(x_i) = x_i - logsumexp(x) + else: + # logsumexp approach is unstable with bfloat16, fall back to slightly less efficient approach + per_token_logps = [] + for row_logits, row_labels in zip(logits, index, strict=True): # loop to reduce peak mem consumption + row_logps = F.log_softmax(row_logits, dim=-1) + row_per_token_logps = row_logps.gather(dim=-1, index=row_labels) + per_token_logps.append(row_per_token_logps) + per_token_logps = torch.stack(per_token_logps) + + if squeeze: + per_token_logps = per_token_logps.squeeze(-1) + + return per_token_logps + + +def entropy_from_logits(logits: torch.Tensor, chunk_size: int = 128) -> torch.Tensor: + """ + Compute the Shannon entropy (in nats) for each row of *logits* in a memory-efficient way. + + Instead of materializing the full softmax for all rows at once, the logits are flattened to shape (N, num_classes), + where N is the product of all leading dimensions. Computation is then performed in chunks of size `chunk_size` + along this flattened dimension, reducing peak memory usage. The result is reshaped back to match the input's + leading dimensions. + + Args: + logits (`torch.Tensor`): + Logits tensor of shape `(..., num_classes)`. Entropy is taken along the last axis; all leading dimensions + are preserved in the output. + chunk_size (`int`, *optional*, defaults to `128`): + Number of rows from the flattened logits to process per iteration. Smaller values reduce memory usage at + the cost of more iterations. + + Returns: + `torch.Tensor`: + Entropy values with shape `logits.shape[:-1]`. + """ + original_shape = logits.shape[:-1] # all dims except num_classes + num_classes = logits.shape[-1] + + # Flatten all leading dimensions into one + flat_logits = logits.reshape(-1, num_classes) + + entropies = [] + for chunk in flat_logits.split(chunk_size, dim=0): + logps = F.log_softmax(chunk, dim=-1) + chunk_entropy = -(torch.exp(logps) * logps).sum(-1) + entropies.append(chunk_entropy) + + entropies = torch.cat(entropies, dim=0) + return entropies.reshape(original_shape) + + +def print_prompt_completions_sample( + prompts: list, + completions: list, + rewards: dict[str, list[float]], + advantages: list[float], + step: int, + num_samples: int = None, + extra: dict[str, list] | None = None, +) -> None: + """ + Print out a sample of model completions to the console with multiple reward metrics. + + This function creates a nicely formatted table showing prompt-completion pairs, useful for monitoring model outputs + during training. It requires the `rich` library to be installed. + + Args: + prompts (`list`): + List of prompts. Can be either strings or lists of messages. + completions (`list`): + List of completions corresponding to the prompts. Can be either strings or lists of messages. + rewards (`dict[str, list[float]]`): + Dictionary where keys are reward names and values are lists of rewards. + advantages (`list[float]`): + List of advantages corresponding to the prompts and completions. + step (`int`): + Current training step number, used in the output title. + num_samples (`int`, *optional*): + Number of random samples to display. If `None` (default), all items will be displayed. + extra (`dict[str, list]`, *optional*): + Additional columns to display after the advantage column. Keys are column names and values are lists of + per-completion data (strings or any value convertible to string). Typically populated via `log_extra` in + reward functions. If `None` (default), no extra columns are shown. + + Example: + ```python + >>> from trl.trainer.utils import print_prompt_completions_sample + + >>> prompts = ["The sky is", "The sun is"] + >>> completions = [" blue.", " in the sky."] + >>> rewards = {"Correctness": [0.123, 0.456], "Format": [0.789, 0.101]} + >>> advantages = [0.987, 0.654] + >>> extra = {"source": ["dataset_A", "dataset_B"]} + >>> print_prompt_completions_sample(prompts, completions, rewards, advantages, 42, extra=extra) + ╭────────────────────────────────── Step 42 ───────────────────────────────────╮ + │ ┏━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━┓ │ + │ ┃ Prompt ┃ Completion ┃ Correctness ┃ Format ┃ Advantage ┃ source ┃ │ + │ ┡━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━┩ │ + │ │ The sky is │ blue. │ 0.12 │ 0.79 │ 0.99 │ dataset_A │ │ + │ ├────────────┼──────────────┼─────────────┼────────┼───────────┼───────────┤ │ + │ │ The sun is │ in the sky. │ 0.46 │ 0.10 │ 0.65 │ dataset_B │ │ + │ └────────────┴──────────────┴─────────────┴────────┴───────────┴───────────┘ │ + ╰──────────────────────────────────────────────────────────────────────────────╯ + ``` + """ + if not is_rich_available(): + raise ImportError( + "The function `print_prompt_completions_sample` requires the `rich` library. Please install it with " + "`pip install rich`." + ) + console = Console() + table = Table(show_header=True, header_style="bold white", expand=True) + + extra = extra or {} + + # Add columns + table.add_column("Prompt", style="bright_yellow") + table.add_column("Completion", style="bright_green") + for reward_name in rewards.keys(): + table.add_column(reward_name, style="bold cyan", justify="right") + table.add_column("Advantage", style="bold magenta", justify="right") + for extra_name in extra.keys(): + table.add_column(extra_name, style="bright_white") + + def format_entry(entry) -> Text: + t = Text() + if isinstance(entry, list) and all(isinstance(m, dict) for m in entry): + for j, msg in enumerate(entry): + role = msg.get("role", "") + if "content" in msg or "reasoning_content" in msg or "thinking" in msg: + # Chat message + t.append(f"{role.upper()}\n", style="bold red") + reasoning = msg.get("reasoning_content") or msg.get("thinking") + if reasoning: + t.append(reasoning, style="italic dim white") + t.append("\n") + if "content" in msg: + t.append(msg["content"]) + elif "name" in msg and "args" in msg: + # Tool call + t.append(f"{role.upper()}\n", style="bold red") + t.append(f"{msg['name']}({msg['args']})") + else: + # Fallback + t.append(str(msg)) + if j < len(entry) - 1: + t.append("\n\n") + else: + t.append(str(entry)) + return t + + # Some basic input validation + if num_samples is not None: + if num_samples >= len(prompts): + num_samples = None + elif num_samples <= 0: + return + + # Subsample data if num_samples is specified + if num_samples is not None: + indices = random.sample(range(len(prompts)), num_samples) + prompts = [prompts[i] for i in indices] + completions = [completions[i] for i in indices] + rewards = {key: [val[i] for i in indices] for key, val in rewards.items()} + advantages = [advantages[i] for i in indices] + extra = {key: [val[i] for i in indices] for key, val in extra.items()} + + for i in range(len(prompts)): + reward_values = [f"{rewards[key][i]:.2f}" for key in rewards.keys()] # 2 decimals + extra_values = [format_entry(extra[key][i]) for key in extra.keys()] + table.add_row( + format_entry(prompts[i]), + format_entry(completions[i]), + *reward_values, + f"{advantages[i]:.2f}", + *extra_values, + ) + table.add_section() # Adds a separator between rows + + panel = Panel(table, expand=False, title=f"Step {step}", border_style="bold white") + console.print(panel) + + +class RepeatSampler(Sampler): + """ + Sampler that repeats the indices of a dataset in a structured manner. + + Args: + data_source (`Sized`): + Dataset to sample from. + mini_repeat_count (`int`): + Number of times to repeat each index per batch. + batch_size (`int`, *optional*, defaults to `1`): + Number of unique indices per batch. + repeat_count (`int`, *optional*, defaults to `1`): + Number of times to repeat the full sampling process. + shuffle (`bool`, *optional*, defaults to `True`): + Whether to shuffle the dataset. + seed (`int`, *optional*): + Random seed for reproducibility (only affects this sampler). + + Example: + ```python + >>> sampler = RepeatSampler(["a", "b", "c", "d", "e", "f", "g"], mini_repeat_count=2, batch_size=3, repeat_count=4) + >>> list(sampler) + [4, 4, 3, 3, 0, 0, + 4, 4, 3, 3, 0, 0, + 4, 4, 3, 3, 0, 0, + 4, 4, 3, 3, 0, 0, + 1, 1, 2, 2, 6, 6, + 1, 1, 2, 2, 6, 6, + 1, 1, 2, 2, 6, 6, + 1, 1, 2, 2, 6, 6] + ``` + + ```txt + mini_repeat_count = 3 + - - - + [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, | + 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, | + 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, | + repeat_count = 2 + 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, | + 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, | + 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, ...] | + --------- --------- --------- --------- + --------- --------- --------- --------- + --------- --------- --------- --------- + batch_size = 12 + ``` + """ + + def __init__( + self, + data_source: Sized, + mini_repeat_count: int, + batch_size: int = 1, + repeat_count: int = 1, + shuffle: bool = True, + seed: int | None = None, + ): + self.data_source = data_source + self.mini_repeat_count = mini_repeat_count + self.batch_size = batch_size + self.repeat_count = repeat_count + self.num_samples = len(data_source) + self.shuffle = shuffle + self.seed = seed + + if shuffle: + self.generator = torch.Generator() # Create a local random generator + if seed is not None: + self.generator.manual_seed(seed) + + def __iter__(self): + if self.shuffle: + # E.g., [2, 4, 3, 1, 0, 6, 5] (num_samples = 7) + indexes = torch.randperm(self.num_samples, generator=self.generator).tolist() + else: + indexes = list(range(self.num_samples)) + + # [2, 4, 3, 1, 0, 6, 5] + # -> [[2, 4, 3], [1, 0, 6], [5]] (batch_size = 3) + indexes = [indexes[i : i + self.batch_size] for i in range(0, len(indexes), self.batch_size)] + + # [[2, 4, 3], [1, 0, 6], [5]] + # -> [[2, 4, 3], [1, 0, 6]] + indexes = [chunk for chunk in indexes if len(chunk) == self.batch_size] + + for chunk in indexes: + for _ in range(self.repeat_count): + for index in chunk: + for _ in range(self.mini_repeat_count): + yield index + + def __len__(self) -> int: + return (self.num_samples // self.batch_size) * self.batch_size * self.mini_repeat_count * self.repeat_count + + +# torch.nanstd doesn't exist, so we define it here +def nanstd(tensor: torch.Tensor, dim: int | tuple[int, ...] | None = None, keepdim: bool = False) -> torch.Tensor: + """ + Compute the standard deviation of a tensor, ignoring NaNs. + + Args: + tensor (`torch.Tensor`): + Input tensor. + dim (`int` or `tuple[int, ...]`, *optional*): + Dimension(s) to reduce. Defaults to all dimensions. + keepdim (`bool`, *optional*, defaults to `False`): + Whether to keep reduced dimensions. + + Returns: + `torch.Tensor`: + Standard deviation of the tensor, ignoring NaNs. + """ + # Compute variance ignoring NaNs + mean = torch.nanmean(tensor, dim=dim, keepdim=True) + variance = torch.nanmean((tensor - mean) ** 2, dim=dim, keepdim=True) + count = torch.sum(~torch.isnan(tensor), dim=dim, keepdim=True) # count of non-NaN values + correction = count / (count - 1) + correction = torch.where(count > 1, correction, torch.full_like(correction, float("nan"))) + variance *= correction # Bessel's correction + std = torch.sqrt(variance) + if keepdim: + return std + if dim is None: + return std.squeeze() + if isinstance(dim, int): + return std.squeeze(dim) + dims = [(d if d >= 0 else d + std.ndim) for d in dim] + for d in sorted(dims, reverse=True): + std = std.squeeze(d) + return std + + +def split_tensor_dict( + tensor_dict: dict[str, torch.Tensor | None], num_chunks: int +) -> list[dict[str, torch.Tensor | None]]: + """ + Splits a dictionary of tensors along the first dimension into `num_chunks` equal parts. + + Example: + ```python + >>> x = torch.arange(12).reshape(6, 2) + >>> y = torch.arange(6).reshape(6, 1) + >>> tensor_dict = {"x": x, "y": y} + >>> split_tensor_dict(tensor_dict, 3) + [ + {"x": tensor([[0, 1], [2, 3]]), "y": tensor([[0], [1]])}, + {"x": tensor([[4, 5], [6, 7]]), "y": tensor([[2], [3]])}, + {"x": tensor([[ 8, 9], [10, 11]]), "y": tensor([[4], [5]])} + ] + ``` + """ + first_tensor = next(tensor for tensor in tensor_dict.values() if tensor is not None) + chunk_size = first_tensor.shape[0] // num_chunks + chunks = [] + for i in range(num_chunks): + chunk_dict = {} + for key, tensor in tensor_dict.items(): + if tensor is not None and (isinstance(tensor, list) or tensor.ndim > 0): + chunk_dict[key] = tensor[i * chunk_size : (i + 1) * chunk_size] + elif tensor is not None and tensor.ndim == 0: + chunk_dict[key] = tensor + else: + chunk_dict[key] = None + chunks.append(chunk_dict) + return chunks + + +def shuffle_sequence_dict(seq_dict: dict[str, Sequence | None]) -> dict[str, Sequence | None]: + """ + Shuffles all sequence-like values in a dictionary along the first dimension in unison. + + Example: + ```python + >>> x = torch.arange(6).reshape(3, 2) + >>> y = ["a", "b", "c"] + >>> seq_dict = {"x": x, "y": y} + >>> shuffle_sequence_dict(seq_dict) + {'x': tensor([[2, 3], + [0, 1], + [4, 5]]), + 'y': ['b', 'a', 'c']} + ``` + """ + # Determine batch size from the first non-None sequence + batch_size = len(next(v for v in seq_dict.values() if v is not None)) + permutation = torch.randperm(batch_size) + + def permute(v: Sequence | None) -> Sequence | None: + if v is None: + return None + if isinstance(v, torch.Tensor) and v.ndim == 0: + return v + if isinstance(v, torch.Tensor) and v.ndim >= 1: + return v[permutation] + return [v[i] for i in permutation] + + return {key: permute(val) for key, val in seq_dict.items()} + + +def nanmin(tensor: torch.Tensor) -> torch.Tensor: + """ + Compute the minimum value of a tensor, ignoring NaNs. This function only supports 1D tensors. + + Args: + tensor (`torch.Tensor`): Input tensor of shape `(N,)`. + + Returns: + `torch.Tensor`: Minimum value of the tensor, ignoring NaNs. Returns NaN if all values are NaN. + """ + if torch.isnan(tensor).all(): + return torch.tensor(float("nan"), dtype=tensor.dtype, device=tensor.device) + return torch.min(tensor[~torch.isnan(tensor)]) + + +def nanmax(tensor: torch.Tensor) -> torch.Tensor: + """ + Compute the maximum value of a tensor, ignoring NaNs. This function only supports 1D tensors. + + Args: + tensor (`torch.Tensor`): Input tensor of shape `(N,)`. + + Returns: + `torch.Tensor`: Maximum value of the tensor, ignoring NaNs. Returns NaN if all values are NaN. + """ + if torch.isnan(tensor).all(): + return torch.tensor(float("nan"), dtype=tensor.dtype, device=tensor.device) + return torch.max(tensor[~torch.isnan(tensor)]) + + +def identity(x): + """Do we really need docs for this?""" + return x + + +def split_pixel_values_by_grid(batch: dict[str, torch.Tensor]) -> dict[str, torch.Tensor | list[torch.Tensor]]: + """ + Splits `batch["pixel_values"]` into a list of tensors, one per sample, based on `batch["num_images"]`. + + For models with `image_grid_thw` (e.g. Qwen), the grid dimensions determine how many rows of `pixel_values` belong + to each image. For models with `image_position_ids` instead (e.g. Gemma), `pixel_values` is indexed directly by + image count. For models with `spatial_shapes` (e.g. LFM2-VL), tile-indexed tensors are split using `num_tiles`. + """ + if "pixel_values" not in batch or "num_images" not in batch: + return batch + + num_images = batch["num_images"] + pixel_values = batch["pixel_values"] # [total, feature_dim] + + if "image_grid_thw" in batch: + lengths = batch["image_grid_thw"].prod(-1).tolist() # [num_images] + if sum(lengths) != pixel_values.size(0): + raise ValueError( + f"Mismatch: sum(lengths) = {sum(lengths)} != pixel_values.size(0) = {pixel_values.size(0)}" + ) + + boundaries = [0, *accumulate(num_images)] + image_grid_thw = batch["image_grid_thw"] # [total, 3] + sections = [sum(lengths[boundaries[i] : boundaries[i + 1]]) for i in range(len(num_images))] + split_pixel_values = list(torch.split(pixel_values, sections, dim=0)) + split_image_grid_thw = list(torch.split(image_grid_thw, num_images, dim=0)) + return {**batch, "pixel_values": split_pixel_values, "image_grid_thw": split_image_grid_thw} + + if "image_position_ids" in batch: + image_position_ids = batch["image_position_ids"] # [total] + split_pixel_values = list(torch.split(pixel_values, num_images, dim=0)) + split_image_position_ids = list(torch.split(image_position_ids, num_images, dim=0)) + return {**batch, "pixel_values": split_pixel_values, "image_position_ids": split_image_position_ids} + + if "spatial_shapes" in batch: + num_tiles = batch["num_tiles"] + pixel_attention_mask = batch["pixel_attention_mask"] + spatial_shapes = batch["spatial_shapes"] + split_pixel_values = list(torch.split(pixel_values, num_tiles, dim=0)) + split_pixel_attention_mask = list(torch.split(pixel_attention_mask, num_tiles, dim=0)) + split_spatial_shapes = list(torch.split(spatial_shapes, num_tiles, dim=0)) + return { + **batch, + "pixel_values": split_pixel_values, + "pixel_attention_mask": split_pixel_attention_mask, + "spatial_shapes": split_spatial_shapes, + } + + return batch + + +def unsplit_pixel_values_by_grid(batch: dict[str, torch.Tensor | list[torch.Tensor]]) -> dict[str, torch.Tensor]: + """ + Opposite of `split_pixel_values_by_grid`. Merges a list of tensors in `batch["pixel_values"]` back into a single + tensor along the first dimension. + """ + pixel_values = batch.get("pixel_values") + if isinstance(pixel_values, list): + merged = torch.cat(pixel_values, dim=0) + batch = {**batch, "pixel_values": merged} + + image_grid_thw = batch.get("image_grid_thw") + if isinstance(image_grid_thw, list): + merged = torch.cat(image_grid_thw, dim=0) + batch = {**batch, "image_grid_thw": merged} + + image_position_ids = batch.get("image_position_ids") + if isinstance(image_position_ids, list): + merged = torch.cat(image_position_ids, dim=0) + batch = {**batch, "image_position_ids": merged} + + pixel_attention_mask = batch.get("pixel_attention_mask") + if isinstance(pixel_attention_mask, list): + merged = torch.cat(pixel_attention_mask, dim=0) + batch = {**batch, "pixel_attention_mask": merged} + + spatial_shapes = batch.get("spatial_shapes") + if isinstance(spatial_shapes, list): + merged = torch.cat(spatial_shapes, dim=0) + batch = {**batch, "spatial_shapes": merged} + + return batch + + +TListOrMapping = TypeVar("TListOrMapping", list, Mapping) + + +# This function is intentionally not used internally. It is provided as a utility for users whose datasets contain +# `None` values inserted by tabular backends (e.g., Arrow/Parquet) for missing keys in nested structures. This +# situation arises when loading datasets created before `datasets` v4.7.0 (which introduced the Json dtype), or when +# datasets created after that version were saved without using the Json feature. In both cases, users can apply this +# function via `dataset = dataset.with_transform(remove_none_values)` before training to strip the spurious `None` +# values. See the migration guide for more details. +def remove_none_values(example: TListOrMapping) -> TListOrMapping: + """ + Recursively removes entries with `None` values from a nested structure (list or dictionary). + + Args: + example (`list` or `Mapping`): + Input nested structure (list or dictionary) from which to remove `None`. + + Examples: + ```python + >>> dataset = dataset.with_transform(remove_none_values) + ``` + ```python + >>> [ + ... { + ... "a": {"aa": None, "ab": 1}, + ... "b": "my_string", + ... } + ... ] + >>> remove_none_values(example) + [{'a': {'ab': 1}, 'b': 'my_string'}] + ``` + """ + if isinstance(example, list): + return [remove_none_values(value) if isinstance(value, (dict, list)) else value for value in example] + elif isinstance(example, Mapping): + return { + key: remove_none_values(value) if isinstance(value, (dict, list)) else value + for key, value in example.items() + if value is not None + } + else: + raise TypeError("Input must be a list or a dictionary.") + + +def create_model_from_path( + model_id: str, architecture: _BaseAutoModelClass | None = None, **kwargs +) -> PreTrainedModel: + """ + Create a model from a given path using the specified initialization arguments. + + Args: + model_id (`str`): + Path to the model. Can be either a local directory or a model identifier from the Hugging Face Hub. + architecture (`_BaseAutoModelClass` or `None`, *optional*): + Model architecture class to instantiate. The model is initialized using the `from_pretrained` method of + this class. If `None`, the architecture will be inferred from the model's configuration. + kwargs (`dict`): + Initialization keyword arguments to pass to the model's `from_pretrained` method. When `'dtype'` is + specified, it can be either a `torch.dtype` or one of the strings: `'bfloat16'`, `'float16'`, `'float32'`, + or `'auto'`. If not explicitly set, `dtype` defaults to `'float32'`. + + Returns: + [`~transformers.PreTrainedModel`]: + The instantiated model. + """ + dtype = kwargs.get("dtype", "float32") + if isinstance(dtype, torch.dtype) or dtype == "auto" or dtype is None: + pass # dtype is already a torch.dtype or "auto" or None + elif isinstance(dtype, str) and dtype in ["bfloat16", "float16", "float32"]: + kwargs["dtype"] = getattr(torch, dtype) + else: + raise ValueError( + "Invalid `dtype` passed to the config. Expected either 'auto' or a string representing " + f"a valid `torch.dtype` (e.g., 'float32'), but got {dtype}." + ) + kwargs["device_map"] = kwargs.get("device_map", "auto") + if architecture is None: + # Best effort to infer architecture from config, but we fall back to AutoModelForCausalLM if we can't find it + config = AutoConfig.from_pretrained(model_id, trust_remote_code=kwargs.get("trust_remote_code", False)) + architecture = getattr(transformers, config.architectures[0], None) + if architecture is None: + # Remote-code checkpoint: the architecture name lives in the dynamic module, not in + # `transformers`. Pick the most specific auto class declared in `config.auto_map`. + auto_map = config.auto_map or {} + for candidate in (AutoModelForImageTextToText, AutoModelForCausalLM): + if candidate.__name__ in auto_map: + architecture = candidate + break + else: + architecture = AutoModelForCausalLM + model = architecture.from_pretrained(model_id, **kwargs) + return model + + +def hash_module(module: torch.nn.Module) -> str: + h = hashlib.sha256() + for _, tensor in sorted(module.state_dict().items()): + tensor = tensor.cpu() + h.update(str(tensor.dtype).encode()) + if tensor.dtype in [torch.bfloat16, torch.float8_e4m3fn, torch.float8_e5m2]: + tensor = tensor.to(torch.float32) + h.update(tensor.numpy().tobytes()) + return h.hexdigest() + + +def get_config_model_id(config: PretrainedConfig) -> str: + """ + Retrieve the model identifier from a given model configuration. + + Args: + config ([`~transformers.PreTrainedConfig`]): + Configuration from which to extract the model identifier. + + Returns: + `str`: + The model identifier associated with the model configuration. + """ + return getattr(config, "_name_or_path", "") + + +@contextmanager +def use_adapter(model: "PeftModel", adapter_name: str | None): + """ + Context manager to temporarily set and reset the active adapter in a PEFT model. + + Args: + model ([`~peft.PeftModel`]): + PEFT model to manage. + adapter_name (`str` or `None`): + Name of the adapter to set as active. If `None`, the context manager will disable all adapters. + + Example: + ```python + >>> from trl.trainer.utils import use_adapter + >>> from peft import AutoPeftModelForCausalLM + >>> import torch + + >>> model = AutoPeftModelForCausalLM.from_pretrained("path/to/model") + >>> input_ids = torch.tensor([[1, 2, 3]]) + >>> with use_adapter(model, "adapter_name"): + ... outputs = model(input_ids) + ``` + """ + + if not is_peft_available(): + raise ImportError( + "You're trying to use a PEFT adapter but PEFT is not installed. Please install it with `pip install peft`." + ) + if adapter_name is None: + with model.disable_adapter(): + yield + else: + previous_adapter = model.active_adapter + model.set_adapter(adapter_name) + try: + yield + finally: + model.set_adapter(previous_adapter) + + +def start_event_loop_in_daemon( + name: str | None = None, +) -> tuple[threading.Thread, asyncio.AbstractEventLoop, threading.Event]: + """ + This function creates a new daemon thread that runs the provided event loop. + + Args: + name (`str`, *optional*): + Name of the thread. If `None`, the default thread naming will be used. + + Returns: + `threading.Thread`: + The thread running the event loop. + `asyncio.AbstractEventLoop`: + The event loop being run in the thread. + `threading.Event`: + An event that is set when the loop is ready. + """ + loop = asyncio.new_event_loop() + loop_ready_event = threading.Event() + + def run_loop(): + asyncio.set_event_loop(loop) + loop_ready_event.set() + loop.run_forever() + + thread = threading.Thread(target=run_loop, name=name, daemon=True) + thread.start() + return thread, loop, loop_ready_event + + +def shutdown_event_loop_in_daemon( + thread: threading.Thread | None, + loop: asyncio.AbstractEventLoop | None, +) -> None: + """ + Shutdown an asyncio event loop running in a separate thread. + + This function stops the event loop and waits for the associated thread to finish execution. + + Args: + thread (`threading.Thread`): + The thread running the event loop. + loop (`asyncio.AbstractEventLoop`): + The asyncio event loop to shut down. + """ + if loop is None or thread is None: + return + loop.call_soon_threadsafe(loop.stop) + thread.join(timeout=5) + + +class _ChunkedLogProbFunction(torch.autograd.Function): + """Compute per-token log-probs and entropy without materializing [N, V] logits. + + Processes the lm_head in chunks and uses online logsumexp + """ + + @staticmethod + def forward( + ctx, + last_hidden: torch.Tensor, # [N, H] + weight: torch.Tensor, # [V, H] + targets: torch.Tensor, # [N] + temperature: float, + chunk_size: int, + final_logit_softcapping: float | None = None, + logit_scale: float = 1.0, + ) -> tuple[torch.Tensor, torch.Tensor]: + device = last_hidden.device + N, _ = last_hidden.shape + vocab, _ = weight.shape + inv_t = 1 / temperature + + # NOTE(@aminediro): always acc in fp32 for stability + max_old = torch.full((N,), float("-inf"), device=device, dtype=torch.float32) + sum_exp = torch.zeros((N,), device=device, dtype=torch.float32) + x_sum_exp = torch.zeros((N,), device=device, dtype=torch.float32) + target_logit = torch.zeros((N,), device=device, dtype=torch.float32) + + # Pre-allocate reusable buffers to avoid per-chunk allocation + mm_buf = torch.empty((N, chunk_size), device=device, dtype=last_hidden.dtype) + logits_buf = torch.empty((N, chunk_size), device=device, dtype=torch.float32) + + for start in range(0, vocab, chunk_size): + end = min(start + chunk_size, vocab) + C = end - start + # using fp16=True, the model's hidden states get cast to float16 by autocast, but the mm_buf is allocated + # with last_hidden.dtype (float16) while w_chunk (the lm_head weights) is not auto casted + w_chunk = weight[start:end].to(last_hidden.dtype) # [C, H] + torch.mm(last_hidden, w_chunk.t(), out=mm_buf[:, :C]) + logits_chunk = logits_buf[:, :C] + logits_chunk.copy_(mm_buf[:, :C]) + + logits_chunk.mul_(logit_scale) + if final_logit_softcapping is not None: + logits_chunk.div_(final_logit_softcapping).tanh_().mul_(final_logit_softcapping) + + logits_chunk.mul_(inv_t) # [N, C] + + # Online logsumexp update + chunk_max = logits_chunk.amax(dim=-1) # [N] + max_new = torch.maximum(max_old, chunk_max) + rescale = torch.exp(max_old - max_new) + chunk_exp = torch.exp(logits_chunk - max_new.unsqueeze(-1)) # [N, C] + + sum_exp = sum_exp * rescale + chunk_exp.sum(dim=-1) + x_sum_exp = x_sum_exp * rescale + (chunk_exp * logits_chunk).sum(dim=-1) + max_old = max_new + + # Gather target logits for labels in this chunk + in_chunk_cond = (targets >= start) & (targets < end) + local_idx = torch.clamp(targets - start, 0, end - start - 1) + # take the new logit if target_idx is in this chunk bounds else 0 + target_logit += logits_chunk[torch.arange(N, device=device), local_idx] * in_chunk_cond + + log_z = max_old + torch.log(sum_exp) + logprobs = target_logit - log_z + entropy = log_z - x_sum_exp / sum_exp + + ctx.save_for_backward(last_hidden, weight, targets, log_z) + ctx.temperature = temperature + ctx.chunk_size = chunk_size + ctx.logit_scale = logit_scale + ctx.final_logit_softcapping = final_logit_softcapping + + return logprobs, entropy + + @staticmethod + def backward(ctx, grad_logprobs: torch.Tensor, grad_entropy: torch.Tensor): # type: ignore + hidden, weight, labels, log_z = ctx.saved_tensors + temperature: float = ctx.temperature + chunk_size: int = ctx.chunk_size + logit_scale: float = ctx.logit_scale + final_logit_softcapping: float = ctx.final_logit_softcapping + inv_t = 1 / temperature + + N, _ = hidden.shape + vocab = weight.shape[0] + + # NOTE(@aminediro): always acc in fp32 even if input is not + grad_hidden = torch.zeros(hidden.shape, device=hidden.device, dtype=torch.float32) + grad_weight = torch.zeros(weight.shape, device=weight.device, dtype=torch.float32) + + # Pre-allocate reusable buffers to avoid per-chunk allocation + mm_buf = torch.empty((N, chunk_size), device=hidden.device, dtype=hidden.dtype) + logits_buf = torch.empty((N, chunk_size), device=hidden.device, dtype=torch.float32) + + g = grad_logprobs.to(torch.float32) # [N] + row_idx = torch.arange(N, device=hidden.device) + + for start in range(0, vocab, chunk_size): + end = min(start + chunk_size, vocab) + C = end - start + w_chunk = weight[start:end] # [C, H] + + torch.mm(hidden, w_chunk.t(), out=mm_buf[:, :C]) + logits_chunk = logits_buf[:, :C] + logits_chunk.copy_(mm_buf[:, :C]) + + logits_chunk.mul_(logit_scale) + if final_logit_softcapping is not None: + tanh_scaled = torch.tanh(logits_chunk / final_logit_softcapping) + logits_chunk.copy_(tanh_scaled * final_logit_softcapping) + + logits_chunk.mul_(inv_t) # [N, C] + probs = torch.exp(logits_chunk - log_z.unsqueeze(-1)) # [N, C] + + # dL/d(logits) = g * (1_[label] - p) + grad_logits = (-g).unsqueeze(-1) * probs # [N, C] + + in_chunk_cond = (labels >= start) & (labels < end) + local_idx = torch.clamp(labels - start, 0, end - start - 1) + # If label in chunk add g to grad else it stays the same + grad_logits[row_idx, local_idx] += g * in_chunk_cond + + grad_logits = grad_logits * inv_t + if final_logit_softcapping is not None: + grad_logits.mul_(1 - tanh_scaled.pow(2)) + + grad_logits = grad_logits * logit_scale + + grad_hidden.add_(grad_logits @ w_chunk.float()) + grad_weight[start:end].add_(grad_logits.t() @ hidden.float()) + + return grad_hidden.to(hidden.dtype), grad_weight.to(weight.dtype), None, None, None, None, None + + +def patch_chunked_lm_head( + model: torch.nn.Module, chunk_size: int, temperature: float, output_router_logits: bool = False +) -> None: + final_logit_softcapping = getattr(model.config, "final_logit_softcapping", None) + + def _chunked_forward( + self: torch.nn.Module, + input_ids: torch.Tensor | None = None, + attention_mask: torch.Tensor | None = None, + labels: torch.Tensor | None = None, + completion_mask: torch.Tensor | None = None, + use_cache: bool = False, + **kwargs, + ) -> dict[str, torch.Tensor]: + assert labels is not None, "requires labels to not be None for logprob computation" + + decoder_kwargs = {"output_router_logits": True} if output_router_logits else {} + outputs = self.model( + input_ids=input_ids, attention_mask=attention_mask, use_cache=use_cache, **decoder_kwargs, **kwargs + ) + # NOTE(@aminediro): supporting Cohere2 models + logit_scale = getattr(self.config, "logit_scale", 1.0) + hidden_states = outputs.last_hidden_state # [B, S+1, H] + + # Shift: predict next token + hidden_states = hidden_states[:, :-1, :] # [B, S-1, H] + labels = labels[:, 1:] # [B, S-1] + + b, s, h = hidden_states.shape + hidden_flat = hidden_states.reshape(b * s, h) + targets_flat = labels.reshape(b * s) + + # Filter to completion tokens only to avoid expensive matmuls on prompt tokens and tool results + valid_mask = None + if completion_mask is not None: + completion_mask = completion_mask[:, 1:] # same shift as labels + valid_mask = completion_mask.bool().reshape(b * s) + hidden_flat = hidden_flat[valid_mask] # [N_valid, H] + targets_flat = targets_flat[valid_mask] # [N_valid] + + logprobs_valid, entropy_valid = _ChunkedLogProbFunction.apply( + hidden_flat, + self.lm_head.weight, + targets_flat, + temperature, + chunk_size, + final_logit_softcapping, + logit_scale, + ) + + if valid_mask is not None: + logprobs = torch.zeros(b * s, device=logprobs_valid.device, dtype=logprobs_valid.dtype) + entropy = torch.zeros(b * s, device=entropy_valid.device, dtype=entropy_valid.dtype) + logprobs[valid_mask] = logprobs_valid + entropy[valid_mask] = entropy_valid + else: + logprobs = logprobs_valid + entropy = entropy_valid + + aux_loss = None + if output_router_logits: + # Mirror the per-family MoE forward: add `router_aux_loss_coef * load_balancing_loss_func(...)` to + # the main loss. Mixtral is the source of truth — every MoE family (Qwen3Moe, GptOss, OLMoE, + # Qwen2Moe, DBRX, JetMoE, PhiMoE, …) pulls this function from mixtral via the modular system, so a + # single import keeps us in lockstep with upstream for every family we test. + from transformers.models.mixtral.modeling_mixtral import load_balancing_loss_func + + if Version(transformers.__version__) < Version("5.0.0"): + num_experts = self.num_experts + num_experts_per_tok = self.num_experts_per_tok + else: + # Upstream bug AttributeError: 'GptOssConfig' object has no attribute 'num_experts'; see #5754 + if self.config.model_type == "gpt_oss" and Version("5.0.0") <= Version( + transformers.__version__ + ) < Version("5.6.0"): + num_experts = self.num_experts + else: + num_experts = self.config.num_experts + num_experts_per_tok = self.config.num_experts_per_tok + # Padding-free packs all real tokens into a single row, so `attention_mask` is None and every token counts. + aux_loss = load_balancing_loss_func( + outputs.router_logits, num_experts, num_experts_per_tok, attention_mask + ) + + return { + "log_probs": logprobs.reshape(b, s), + "entropy": entropy.reshape(b, s), + "aux_loss": aux_loss, + } + + model.forward = types.MethodType(_chunked_forward, model) + + +def compute_flops_per_token(config: PretrainedConfig, seq_len: int) -> int: + """ + Estimate training FLOPs per token for a causal language model (forward + backward). + + Supports dense and MoE architectures. Backward is assumed to cost 2× the forward pass, so total training FLOPs = 3 + × forward FLOPs. The attention-score term uses the non-causal convention (every token attends to the full + `seq_len`, matching PaLM / Megatron / nanoGPT); pass the resulting MFU through [`adjusted_mfu`] for the Llama / + DeepSpeed Ulysses causal-corrected convention. + + Args: + config ([`~transformers.PretrainedConfig`]): + The model configuration. + seq_len (`int`): + The sequence length used for training. + + Returns: + `int`: Estimated training FLOPs per token. + """ + h = config.hidden_size + L = config.num_hidden_layers + V = config.vocab_size + n_heads = config.num_attention_heads + n_kv_heads = config.num_key_value_heads + head_dim = config.head_dim + + # Attention: Q/K/V/O projections + attention score (Q·Kᵀ and attn·V). + qkv_flops = 2 * h * (n_heads * head_dim + 2 * n_kv_heads * head_dim) + o_proj_flops = 2 * n_heads * head_dim * h + attn_score_flops = 2 * 2 * n_heads * head_dim * seq_len + attn_flops = qkv_flops + o_proj_flops + attn_score_flops + + # MoE dispatch: `num_experts_per_tok` is the canonical MoE marker — present on Mixtral, + # Qwen3-MoE, DeepSeek-V2, etc.; absent on dense configs. + num_experts_per_tok = getattr(config, "num_experts_per_tok", None) + if num_experts_per_tok is None: + mlp_flops = 2 * 3 * h * config.intermediate_size + total_layer_flops = L * (attn_flops + mlp_flops) + else: + # Routed experts (gate + up + down, 3 matmuls each) + router. + if Version(transformers.__version__) >= Version("5.1.0"): + num_experts = config.num_local_experts + else: + num_experts = config.num_experts + moe_mlp_flops = num_experts_per_tok * 2 * 3 * h * config.moe_intermediate_size + moe_mlp_flops += 2 * h * num_experts + dense_mlp_flops = 2 * 3 * h * config.intermediate_size # interspersed dense layers + sparse_step = config.decoder_sparse_step + total_layer_flops = sum( + attn_flops + (moe_mlp_flops if layer_idx % sparse_step == 0 else dense_mlp_flops) for layer_idx in range(L) + ) + + embed_flops = 2 * V * h + lm_head_flops = 0 if config.tie_word_embeddings else 2 * V * h + + forward_flops = total_layer_flops + embed_flops + lm_head_flops + return 3 * forward_flops + + +def compute_mfu( + flops_per_token: int, + tokens_per_second: float, + world_size: int, + peak_flops_per_device: float = 989.5e12, +) -> float: + """ + Compute Model FLOPs Utilization (MFU) as a percentage. + + The caller is responsible for correcting `tokens_per_second` for any parallelism dimension that causes the + trainer's token counter to over-count (e.g. context parallelism, sequence parallelism, tensor parallelism — every + rank in those dims sees the same input tokens). + + Args: + flops_per_token (`int`): + Training FLOPs per token (from [`compute_flops_per_token`]). + tokens_per_second (`float`): + Aggregate tokens per second across all devices, after any parallelism corrections. + world_size (`int`): + Number of devices (GPUs). + peak_flops_per_device (`float`, *optional*, defaults to `989.5e12`): + Theoretical peak FLOPs per device in bf16. Defaults to H100 SXM5. + + Returns: + `float`: MFU as a percentage (0-100). + """ + return 100 * (flops_per_token * tokens_per_second) / (peak_flops_per_device * world_size) + + +def adjusted_mfu(mfu: float, config: PretrainedConfig, seq_len: int) -> float: + """ + Apply a causal-masking correction to an MFU computed with [`compute_flops_per_token`]. + + [`compute_flops_per_token`] uses the non-causal attention convention (every token treated as attending to the full + `seq_len`, matching PaLM / Megatron / nanoGPT). With causal masking, only half of the attention-score FLOPs (`Q·Kᵀ` + and `attn·V`) are actually performed. This function subtracts that half from the per-token total and rescales `mfu` + accordingly. Use it to compare against reports that follow the Llama 2/3 / DeepSpeed Ulysses convention. + + Args: + mfu (`float`): + MFU as a percentage, computed via [`compute_mfu`] (i.e., using the non-causal [`compute_flops_per_token`]). + config ([`~transformers.PretrainedConfig`]): + The model configuration. + seq_len (`int`): + The sequence length used for training. + + Returns: + `float`: Causal-corrected MFU as a percentage. + """ + flops_full = compute_flops_per_token(config, seq_len) + # Half of the attention-score FLOPs (Q·Kᵀ and attn·V), per layer, ×3 for fwd+bwd. + half_attn_score = config.num_hidden_layers * 3 * 2 * config.num_attention_heads * config.head_dim * seq_len + return mfu * (flops_full - half_attn_score) / flops_full diff --git a/tasks/tasksmith-b3c12843c3fb/instruction.md b/tasks/tasksmith-b3c12843c3fb/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..65bf7624abd1b508c0f60e6d9ef2cdbbc1392c58 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/instruction.md @@ -0,0 +1,7 @@ +Fix an intermittent hang during GRPO generation with a PEFT/LoRA model and colocated vLLM tensor parallelism on multiple GPUs without NVLink. Adapter-training communication can still be completing when the inference engine begins its own collectives. + +Ensure the training workers have finished the relevant shared communication before colocated tensor-parallel inference begins. Keep generation results and per-rank prompt/completion slicing unchanged. Ordinary models and single-device tensor parallelism should keep their existing behavior without extra synchronization; preserve server mode as well. + +Use the existing offline repository and installed dependencies. A tiny locally configured model is sufficient for testing; no pretrained checkpoints or external inference service are needed. Two CUDA GPUs are available for distributed checks. Implement the fix under `trl`. + +Work in `/workspace`. Submit your fix in Python source files under `trl`. Preserve the other public behavior. The environment is offline; dependencies are preinstalled. Use `/opt/tasksmith-venv/bin/python` for the preinstalled Python environment. Grading runs the relevant repository tests in a fresh environment, using your submitted source files. diff --git a/tasks/tasksmith-b3c12843c3fb/solution/reference/trl/generation/vllm_generation.py b/tasks/tasksmith-b3c12843c3fb/solution/reference/trl/generation/vllm_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..c4407fb14defb79b0d2bd09c193a4055865a060e --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/solution/reference/trl/generation/vllm_generation.py @@ -0,0 +1,698 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""vLLM-based generation backend for TRL trainers.""" + +import logging +import math +import os +from contextlib import nullcontext +from typing import TYPE_CHECKING + +import torch +from accelerate.utils import broadcast_object_list, gather_object, is_peft_model +from torch import nn +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from transformers import PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin, is_bitsandbytes_available +from transformers.utils import ( + is_torch_mlu_available, + is_torch_mps_available, + is_torch_npu_available, + is_torch_xpu_available, +) + +from ..distributed import DistributedBackend +from ..extras.profiling import ProfilingContext +from ..import_utils import is_vllm_available +from ..trainer.utils import ensure_master_addr_port +from .vllm_client import VLLMClient + + +if is_vllm_available(): + from vllm import LLM, RequestOutput, SamplingParams + from vllm.sampling_params import StructuredOutputsParams + + +logger = logging.getLogger(__name__) + + +def empty_cache() -> None: + """Empties the cache of the available torch device. + + This function checks for the availability of different torch devices (CUDA, MLU, MPS, NPU, XPU) and empties the + cache of the first available device it finds. + + If none of the specific devices are available, it defaults to emptying the CUDA cache. + """ + if is_torch_mlu_available(): + torch.mlu.empty_cache() + elif is_torch_mps_available(): + torch.mps.empty_cache() + elif is_torch_npu_available(): + torch.npu.empty_cache() + elif is_torch_xpu_available(): + torch.xpu.empty_cache() + else: + torch.cuda.empty_cache() + + +def extract_logprobs(all_outputs: list["RequestOutput"]): + """ + Extract logprobs and token IDs from vLLM generation outputs. + + Returns logprobs and token IDs sorted by rank (most probable first). Each returned list has shape (num_sequences, + seq_len, num_logprobs), where num_logprobs is determined by the `logprobs` parameter passed to vLLM (1 when + `logprobs=0`, up to N+1 when `logprobs=N`). NaN logprob values are replaced with `None`. + + Args: + all_outputs (list of `RequestOutput`): + List of vLLM `RequestOutput` objects from generation. + + Returns: + Tuple of (logprobs, logprob_token_ids), each of shape (num_sequences, seq_len, num_logprobs). + """ + all_logprobs = [] + all_token_ids = [] + for outputs in all_outputs: + for output in outputs.outputs: + if output.logprobs is None: + return None, None + seq_logprobs = [] + seq_token_ids = [] + for lp in output.logprobs: + sorted_items = sorted(lp.items(), key=lambda x: x[1].rank) + seq_token_ids.append([token_id for token_id, _ in sorted_items]) + seq_logprobs.append([None if math.isnan(item.logprob) else item.logprob for _, item in sorted_items]) + all_logprobs.append(seq_logprobs) + all_token_ids.append(seq_token_ids) + return all_logprobs, all_token_ids + + +if TYPE_CHECKING: + from accelerate import Accelerator + from peft import PeftModel + + +if is_bitsandbytes_available(): + import bitsandbytes as bnb + + +class VLLMGeneration: + """Handles vLLM-based generation for trainers. + + Extracts all vLLM-specific logic (initialization, generation, weight sync) from trainers into a separate, testable + class. + + Args: + model ([`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]): + Model to use for generation. + accelerator ([`~accelerate.Accelerator`]): + Accelerator for distributed training. + processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`]): + Tokenizer or processor for the model. + + > Parameters for vLLM: + + mode (`str`, *optional*, defaults to `"colocate"`): + vLLM mode. Must be one of `"colocate"` or `"server"`. + + - `"colocate"`: vLLM will run in the same process and share the training GPUs. This avoids the need for a + separate server but may cause resource contention with training. + - `"server"`: The trainer will send generation requests to a separate vLLM server. Make sure a TRL vLLM + server is running (start with `trl vllm-serve`). + + structured_outputs_regex (`str`, *optional*): + Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled. + + > Parameters for "server" vLLM mode: + + server_base_url (`str`, *optional*): + Base URL for the vLLM server (e.g., `"http://localhost:8000"`). If provided, `server_host` and + `server_port` are ignored. + server_host (`str`, *optional*, defaults to `"0.0.0.0"`): + Host of the vLLM server to connect to. Ignored if `server_base_url` is provided. + server_port (`int`, *optional*, defaults to `8000`): + Port of the vLLM server to connect to. Ignored if `server_base_url` is provided. + server_timeout (`float`, *optional*, defaults to `240.0`): + Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up after the + timeout, a `ConnectionError` is raised. + group_port (`int`, *optional*, defaults to `51216`): + Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port + is occupied, there is no need to change it. + + > Parameters for "colocate" vLLM mode: + + tensor_parallel_size (`int`, *optional*, defaults to `1`): + The number of GPUs to use for distributed execution with tensor parallelism. This setting only applies when + `mode` is set to `"colocate"`. If you are using `mode="server"`, this parameter must be passed separately + when launching the vLLM server via the `--vllm_tensor_parallel_size` flag. + gpu_memory_utilization (`float`, *optional*, defaults to `0.9`): + Ratio (between 0 and 1) of GPU memory to reserve for the model weights, activations, and KV cache. Higher + values will increase the KV cache size and thus improve the model's throughput. However, if the value is + too high, it may cause out-of- memory (OOM) errors. This setting only applies when `mode` is set to + `"colocate"`. If you are using `mode="server"`, this parameter must be passed separately when launching the + vLLM server via the `--vllm_gpu_memory_utilization` flag. + max_model_length (`int`, *optional*): + Model context length (prompt and completion). Set it to at least the maximum prompt length in the dataset + plus `max_completion_length`; if omitted, it is inferred from the model config. + max_num_seqs (`int`, *optional*): + Maximum number of sequences to process in parallel, effectively capping the batch size. + enable_sleep_mode (`bool`, *optional*, defaults to `False`): + Whether to enable sleep mode for the engine to offload weights/cache during the optimizer step. Keeps GPU + memory usage low, but waking the engine adds host–device transfer latency. + model_impl (`str`, *optional*, defaults to `"auto"`): + Model implementation to use for vLLM. + - "auto" will try to use the vLLM implementation, if it exists, and fall back to the Transformers + implementation if no vLLM implementation is available. + - "vllm" will use the vLLM model implementation. + - "transformers" will use the Transformers model implementation. + - "terratorch" will use the TerraTorch model implementation. + + > Parameters for generation: + + repetition_penalty (`float`, *optional*, defaults to `1.0`): + Parameter for repetition penalty. It penalizes new tokens based on whether they appear in the prompt and + the generated text so far. Values > 1 encourage the model to use new tokens, while values < 1 encourage the + model to repeat tokens. Default `1.0` means no penalty. + temperature (`float`, *optional*, defaults to `1.0`): + Sampling temperature. It controls the randomness of the sampling. Lower values make the model more + deterministic, while higher values make the model more random and increase diversity. + top_p (`float`, *optional*, defaults to `1.0`): + Top-p sampling parameter. It controls the cumulative probability of the top tokens to consider. Defaults to + `1.0` to consider all tokens. + top_k (`int`, *optional*, defaults to `0`): + Top-k sampling parameter. It controls the number of top tokens to consider. Defaults to `0` to consider all + tokens. + min_p (`float`, *optional*, defaults to `0.0`): + Min-p sampling parameter. It represents the minimum probability for a token to be considered, relative to + the probability of the most likely token. Default `0.0` means min-p is disabled. + max_completion_length (`int`, *optional*, defaults to `16`): + Maximum number of tokens to generate for each prompt. + logprobs (`int` or `None`, *optional*, defaults to `0`): + Number of top logprobs to return per token. When 0 (default), only the sampled token's logprob is returned + (inner dimension = 1). When N>0, returns up to N+1 logprobs sorted by descending probability, because vLLM + always includes the sampled token's logprob alongside the top-N (the sampled token may or may not already + be in the top-N). + generation_kwargs (`dict`, *optional*): + Additional generation parameters to pass to the vLLM `SamplingParams`. This can include parameters like + `seed`, `frequency_penalty`, etc. If it contains keys that conflict with the other parameters, they will + override them. + + > Parameters for chat/tools: + + chat_template (`str`, *optional*): + Template to use for structuring the chat. If not provided, the model's default chat template will be used. + chat_template_kwargs (`dict`, *optional*): + Additional keyword arguments to customize the chat template used by the model. + tools (`list`, *optional*): + Tools available for tool calling during chat generation. + """ + + def __init__( + self, + model: "PreTrainedModel | PeftModel", + accelerator: "Accelerator", + processing_class: PreTrainedTokenizerBase | ProcessorMixin, + # vLLM configuration + mode: str = "colocate", + structured_outputs_regex: str | None = None, + # Server mode configuration + server_base_url: str | None = None, + server_host: str = "0.0.0.0", + server_port: int = 8000, + server_timeout: float = 240.0, + group_port: int = 51216, + # Colocate mode configuration + tensor_parallel_size: int = 1, + gpu_memory_utilization: float = 0.9, + max_model_length: int | None = None, + max_num_seqs: int | None = None, + enable_sleep_mode: bool = False, + model_impl: str = "auto", + # Generation configuration + repetition_penalty: float = 1.0, + temperature: float = 1.0, + top_p: float = 1.0, + top_k: int = 0, + min_p: float = 0.0, + max_completion_length: int = 16, + logprobs: int | None = 0, + generation_kwargs: dict | None = None, + ): + self.model = model + self.accelerator = accelerator + self._dist = DistributedBackend(accelerator) + self.processing_class = processing_class + + # vLLM configuration + self.mode = mode + self.structured_outputs_regex = structured_outputs_regex + + # Server mode configuration + self.server_base_url = server_base_url + self.server_host = server_host + self.server_port = server_port + self.group_port = group_port + self.server_timeout = server_timeout + + # Colocate mode configuration + self.tensor_parallel_size = tensor_parallel_size + self.gpu_memory_utilization = gpu_memory_utilization + self.max_model_length = max_model_length + self.max_num_seqs = max_num_seqs + self.enable_sleep_mode = enable_sleep_mode + self.model_impl = model_impl + + # Generation configuration + self.repetition_penalty = repetition_penalty + self.temperature = temperature + self.top_p = top_p + self.top_k = top_k + self.min_p = min_p + self.max_completion_length = max_completion_length + self.logprobs = logprobs + self.generation_kwargs = generation_kwargs or {} + + self._init_vllm() + + def _init_vllm(self): + """Initialize vLLM in server or colocate mode.""" + model = self.model + accelerator = self.accelerator + + if not is_vllm_available(): + raise ImportError( + "vLLM is not available and `use_vllm` is set to True. Please install vLLM with " + "`pip install trl[vllm]` to use it." + ) + + if self.mode == "server": + if accelerator.is_main_process: + if self.server_base_url is not None: + base_url = self.server_base_url + else: + base_url = f"http://{self.server_host}:{self.server_port}" + self.vllm_client = VLLMClient( + base_url=base_url, group_port=self.group_port, connection_timeout=self.server_timeout + ) + self.vllm_client.init_communicator(device=torch.cuda.current_device()) + + elif self.mode == "colocate": + # Make sure tensor_parallel_size group size evenly divides the world size - each group should have + # the same number of ranks + if not accelerator.num_processes % self.tensor_parallel_size == 0: + raise ValueError( + f"tensor_parallel_size ({self.tensor_parallel_size}) must divide world size " + f"({accelerator.num_processes}) evenly." + ) + + if self.tensor_parallel_size > 1: + # Create subgroups of ranks for TP, each group with `tensor_parallel_size` ranks. + # For example, if world_size=8 and tensor_parallel_size=2 → groups: [0,1], [2,3], [4,5], [6,7] + self.tp_group, _ = torch.distributed.new_subgroups_by_enumeration( + [ + list(range(i * self.tensor_parallel_size, (i + 1) * self.tensor_parallel_size)) + for i in range(accelerator.num_processes // self.tensor_parallel_size) + ] + ) + + # vLLM requires the environment variables to be set for distributed training. + os.environ["RANK"] = str(accelerator.process_index) + os.environ["LOCAL_RANK"] = str(accelerator.local_process_index) + os.environ["WORLD_SIZE"] = str(accelerator.num_processes) + # Ensure distributed rendezvous variables are set without colliding across concurrent runs + ensure_master_addr_port() + + quantization = None + if is_bitsandbytes_available(): + for _, module in model.named_modules(): + if isinstance(module, bnb.nn.Linear4bit): + quantization = "bitsandbytes" + break + elif isinstance(module, bnb.nn.Linear8bitLt): + raise ValueError("vLLM does not support in-flight 8-bit quantization.") + + # Build LLM initialization kwargs + self.llm = LLM( + model=model.name_or_path, + tensor_parallel_size=self.tensor_parallel_size, + gpu_memory_utilization=self.gpu_memory_utilization, + max_model_len=self.max_model_length, + max_num_seqs=self.max_num_seqs, + enable_sleep_mode=self.enable_sleep_mode, + model_impl=self.model_impl, + distributed_executor_backend="external_launcher", + # Feed identical seed for tp groups to ensure sampling results are the same across workers + seed=accelerator.process_index // self.tensor_parallel_size, + # Latest vLLM v1 memory profiler is misled by the high default value (i.e., 32768) - thinking there's not enough memory + max_num_batched_tokens=4096, + # Important so temperature scaling/logit tweaking affects the TIS log probs + logprobs_mode="processed_logprobs", + quantization=quantization, + ) + if self.enable_sleep_mode: + self.llm.sleep(level=2) + else: + raise ValueError(f"vllm_mode must be either 'server' or 'colocate', got '{self.mode}'.") + + # When using vLLM, the main process is responsible for loading the model weights. This can cause process + # desynchronization and seems to lead to DeepSpeed hanging during initialization. To prevent this, we + # synchronize all processes after vLLM has been fully initialized. + accelerator.wait_for_everyone() + + def _fix_param_name_to_vllm(self, name: str, extra_prefixes: list[str] | None = None) -> str: + """Fix parameter name for vLLM compatibility.""" + extra_prefixes = extra_prefixes or [] + prefixes = ["_checkpoint_wrapped_module."] + extra_prefixes + for prefix in prefixes: + name = name.replace(prefix, "") + return name + + def _push_param_to_vllm(self, name: str, param) -> None: + """Push a single parameter tensor to the vLLM engine (server or colocate mode).""" + if self.mode == "server" and self.accelerator.is_main_process: + self.vllm_client.update_named_param(name, param) + elif self.mode == "colocate": + self.llm.llm_engine.model_executor.driver_worker.model_runner.model.load_weights([(name, param)]) + + def _sync_fsdp1_params_to_vllm(self, module: nn.Module, prefix: str = "", visited: set[str] | None = None): + """Memory-efficient post-order traversal of FSDP modules to extract full parameters and sync with vLLM.""" + # For FSDP1, we need to recurse into children and also use summon_full_params + if visited is None: + visited = set() + for child_name, child_module in module.named_children(): + child_prefix = f"{prefix}.{child_name}" if prefix else child_name + self._sync_fsdp1_params_to_vllm( + child_module, prefix=child_prefix, visited=visited + ) # recurse into the child + + if isinstance(module, FSDP): + with FSDP.summon_full_params(module, recurse=False, writeback=False): + for param_name, param in module.named_parameters(): + full_name = f"{prefix}.{param_name}" if prefix else param_name + full_name = self._fix_param_name_to_vllm(full_name, extra_prefixes=["_fsdp_wrapped_module."]) + + if full_name in visited: + continue # skip FSDP subtrees already traversed + visited.add(full_name) + + self._push_param_to_vllm(full_name, param.data) + + def _sync_fsdp2_params_to_vllm(self, module: nn.Module): + """FSDP2-specific parameter synchronization.""" + # For FSDP2, module.state_dict() already covers all parameters, so no need for recursion + for name, param in module.state_dict().items(): + # When using PEFT, we need to recover the original parameter name + name = name.removeprefix("base_model.model.").replace(".base_layer", "") + # Skip PEFT layers: they don't exist in vLLM, and they are merged already. + if is_peft_model(module) and module.prefix in name: + continue + # When module to save, remove its prefix and discard the original module + if "original_module" in name: + continue + name = self._fix_param_name_to_vllm(name, extra_prefixes=["modules_to_save.default."]) + + if param.is_cpu: + param = param.to(torch.device("cuda")) + param = param.full_tensor() + + self._push_param_to_vllm(name, param) + + def _sync_fsdp_params_to_vllm(self, model: nn.Module): + """Dispatch FSDP weight sync to the version-appropriate method.""" + if self._dist.fsdp_version == 1: + self._sync_fsdp1_params_to_vllm(model) + elif self._dist.fsdp_version == 2: + self._sync_fsdp2_params_to_vllm(model) + + def sync_weights(self): + """Synchronize model weights to vLLM. + + Handles FSDP, DeepSpeed, PEFT weight synchronization. + """ + # Wake up vLLM weights before loading to ensure device memory is mapped. Without this, load_weights() writes to + # freed/unmapped memory when sleep mode is active, which crashes on backends with strict physical memory + # management (e.g., Ascend NPU). See https://github.com/huggingface/trl/issues/5142 + if self.mode == "colocate" and self.enable_sleep_mode: + empty_cache() # required to avoid OOM in some cases + self.llm.wake_up(tags=["weights"]) + + model = self.model + accelerator = self.accelerator + + if is_peft_model(model): + # With PEFT and FSDP/DeepSpeed ZeRO Stage 3, we must gather the full model at once before merging, as + # merging adapters in a sharded manner is not supported. + # TODO: does this work with FSDP? + with self._dist.gather_params(list(model.parameters())): + model.merge_adapter() + + # Update vLLM weights while parameters are gathered + if self._dist.is_fsdp: # note if using FSDP, gather_params is a no-op + # For PEFT with FSDP we need to use the memory efficient post-order traversal + self._sync_fsdp_params_to_vllm(model) + else: + # DeepSpeed ZeRO-3 with PEFT + for name, param in model.named_parameters(): + # When using PEFT, we need to recover the original parameter name + name = name.removeprefix("base_model.model.").replace(".base_layer", "") + # Skip PEFT layers: they don't exist in vLLM, and they are merged already. + if model.prefix in name: + continue + # When module to save, remove its prefix and discard the original module + if "original_module" in name: + continue + name = self._fix_param_name_to_vllm(name, extra_prefixes=["modules_to_save.default."]) + + self._push_param_to_vllm(name, param.data) + # Unmerge adapters while parameters are still gathered + model.unmerge_adapter() + # Parameters will automatically be repartitioned when exiting the context + else: + # For non-PEFT models, simply gather (if needed) and update each parameter individually. + if self._dist.is_fsdp: + self._sync_fsdp_params_to_vllm(model) + else: + for name, param in model.named_parameters(): + name = self._fix_param_name_to_vllm(name) + with self._dist.gather_params([param]): + self._push_param_to_vllm(name, param.data) + + # Reset cache on vLLM + if self.mode == "server" and accelerator.is_main_process: + self.vllm_client.reset_prefix_cache() + elif self.mode == "colocate": + self.llm.reset_prefix_cache() + + def generate( + self, + prompts: list[list[int]], + images: list[list | None] | None, + num_generations: int, + profiler: ProfilingContext | None = None, + ) -> tuple: + """Generate completions using vLLM. + + Args: + prompts: List of token ID lists, one per prompt (already tokenized). + images: Optional list of image lists for VLM support. Each element is a list of PIL images for the + corresponding prompt, or `None` if no images for that prompt. `None` if no images at all. + num_generations: Number of generations per prompt. + profiler: Optional profiler for performance tracking. + + Returns: + Tuple of (prompt_ids, completion_ids, logprobs, logprob_token_ids). + + - `prompt_ids`: `list[list[int]]` of shape `(batch_size, prompt_len)`. + - `completion_ids`: `list[list[int]]` of shape `(batch_size, completion_len)`. + - `logprobs`: `list[list[list[float | None]]]` of shape `(batch_size, completion_len, num_logprobs)`. + - `logprob_token_ids`: `list[list[list[int]]]` of shape `(batch_size, completion_len, num_logprobs)`. + + `num_logprobs` is 1 when `logprobs=0`, or up to N+1 when `logprobs=N` (the sampled token is always included + and may fall outside the top-N). + """ + profiler = profiler or nullcontext() + accelerator = self.accelerator + temperature = self.temperature + top_p = self.top_p + top_k = self.top_k + min_p = self.min_p + repetition_penalty = self.repetition_penalty + max_completion_length = self.max_completion_length + + # Wake up colocated vLLM weights if needed (idempotent if already awake from sync_weights) + if self.mode == "colocate" and self.enable_sleep_mode: + empty_cache() # required to avoid OOM in some cases + self.llm.wake_up(tags=["weights"]) + # Work around for https://github.com/vllm-project/vllm/issues/29341 + try: + self.llm.collective_rpc("reload_weights") + except NotImplementedError: + # Non-CUDA vLLM backends (e.g., vllm-ascend's NPUWorkerV1), don't implement reload_weights + pass + + # Generate completions using vLLM: gather all prompts and use them in a single call in the main process + if self.mode == "server": + all_prompts = gather_object(prompts) + # Always gather images (even when None) to avoid deadlock: images may be None on some ranks + # and non-None on others in mixed datasets, and gather_object is a collective operation. + all_images = gather_object(images if images is not None else [None] * len(prompts)) + if all(img is None for img in all_images): + all_images = None + + if accelerator.is_main_process: + # Since 'prompts' contains 'num_generations' duplicates, we first take unique prompts, and + # generate num_generations outputs for each one. This is faster than generating outputs for each + # duplicate prompt individually. + ordered_set_of_prompt_ids = all_prompts[::num_generations] + ordered_set_of_images = all_images[::num_generations] if all_images is not None else None + + sampling_params = { + "n": num_generations, + "repetition_penalty": repetition_penalty, + "temperature": temperature, + "top_p": top_p, + "top_k": top_k, + "min_p": 0.0 if min_p is None else min_p, + "max_tokens": max_completion_length, + "logprobs": self.logprobs, + "structured_outputs_regex": self.structured_outputs_regex, + "generation_kwargs": self.generation_kwargs, + } + with profiler: + output = self.vllm_client.generate( + prompts=ordered_set_of_prompt_ids, + images=ordered_set_of_images, + **sampling_params, + ) + payload = ( + output["prompt_ids"], + output["completion_ids"], + output["logprobs"], + output.get("logprob_token_ids"), + ) + else: + payload = None + + # Broadcast the completions from the main process to all processes, ensuring each process receives its corresponding slice. + obj_list = [payload] + broadcast_object_list(obj_list, from_process=0) + all_prompt_ids, all_completion_ids, all_logprobs, all_logprob_token_ids = obj_list[0] + + # vllm_client.generate(n=num_generations) returns num_generations completions per prompt. + # Duplicate prompt_ids to align with per-completion entries. + all_prompt_ids = [ids for ids in all_prompt_ids for _ in range(num_generations)] + + process_slice = slice( + accelerator.process_index * len(prompts), + (accelerator.process_index + 1) * len(prompts), + ) + prompt_ids = all_prompt_ids[process_slice] + completion_ids = all_completion_ids[process_slice] + logprobs = all_logprobs[process_slice] if all_logprobs is not None else None + logprob_token_ids = all_logprob_token_ids[process_slice] if all_logprob_token_ids is not None else None + + # Generate completions using colocated vLLM instances: each device holds vLLM copy and work on their own batch of prompts + elif self.mode == "colocate": + generation_kwargs = { + "n": 1, # vLLM on each GPU generates only 1 in colocate mode + "repetition_penalty": repetition_penalty, + "temperature": temperature, + "top_p": top_p, + "top_k": top_k, + "min_p": 0.0 if min_p is None else min_p, + "max_tokens": max_completion_length, + "logprobs": self.logprobs, + } + generation_kwargs.update(self.generation_kwargs) + + if self.structured_outputs_regex is not None: + if generation_kwargs.get("structured_outputs") is not None: + logger.warning( + "Both `structured_outputs_regex` and `generation_kwargs['structured_outputs']` are set; " + "`structured_outputs_regex` takes precedence." + ) + generation_kwargs["structured_outputs"] = StructuredOutputsParams(regex=self.structured_outputs_regex) + elif isinstance(structured_outputs_kwargs := generation_kwargs.get("structured_outputs"), dict): + generation_kwargs["structured_outputs"] = StructuredOutputsParams(**structured_outputs_kwargs) + sampling_params = SamplingParams(**generation_kwargs) + + if self.tensor_parallel_size > 1: + # Gather prompts from all ranks in the TP group and flatten. + # Each rank starts with its own prompts; after gathering, all ranks see the full group set. + orig_size = len(prompts) + gathered_prompts = [None for _ in range(self.tensor_parallel_size)] + torch.distributed.all_gather_object(gathered_prompts, prompts, group=self.tp_group) + all_prompts = [p for sublist in gathered_prompts for p in sublist] + # Always gather images (even when None) to avoid deadlock: images may be None on some + # ranks and non-None on others in mixed datasets, and all_gather_object is collective. + local_images = images if images is not None else [None] * len(prompts) + gathered_images = [None for _ in range(self.tensor_parallel_size)] + torch.distributed.all_gather_object(gathered_images, local_images, group=self.tp_group) + all_images = [img for sublist in gathered_images for img in sublist] + if all(img is None for img in all_images): + all_images = None + else: + all_prompts = prompts + all_images = images + + if self.enable_sleep_mode: + self.llm.wake_up(tags=["kv_cache"]) + + # Build vLLM-compatible prompt inputs with token IDs and optional multi-modal data + vllm_prompts = [] + if all_images is not None: + for ids, img_list in zip(all_prompts, all_images, strict=True): + row = {"prompt_token_ids": ids} + if img_list is not None: + row["multi_modal_data"] = {"image": img_list if len(img_list) > 1 else img_list[0]} + vllm_prompts.append(row) + else: + vllm_prompts = [{"prompt_token_ids": ids} for ids in all_prompts] + + # When PEFT is used, DDP gradient all-reduce only covers the small LoRA parameters, so + # NCCL operations complete very quickly. On non-NVLink hardware (e.g. A40/A100), vLLM's + # TP NCCL collective can race with NCCL's internal P2P/SHM channel cleanup from that + # all-reduce, causing llm.generate() to hang. A barrier on the default process group + # forces NCCL to fully drain before vLLM's TP communication starts. + # See https://github.com/huggingface/trl/issues/3671 + if is_peft_model(self.model) and self.tensor_parallel_size > 1: + torch.distributed.barrier() + + with profiler: + all_outputs = self.llm.generate(vllm_prompts, sampling_params=sampling_params, use_tqdm=False) + + all_prompt_ids = [output.prompt_token_ids for output in all_outputs] + all_completion_ids = [output.token_ids for outputs in all_outputs for output in outputs.outputs] + all_logprobs, all_logprob_token_ids = extract_logprobs(all_outputs) + + if self.tensor_parallel_size > 1: + # Slice completions for this rank within its TP group. + # Each rank generates all outputs — we keep only our share. + local_rank_in_group = torch.distributed.get_rank(group=self.tp_group) + tp_slice = slice(local_rank_in_group * orig_size, (local_rank_in_group + 1) * orig_size) + prompt_ids = all_prompt_ids[tp_slice] + completion_ids = all_completion_ids[tp_slice] + logprobs = all_logprobs[tp_slice] if all_logprobs is not None else None + logprob_token_ids = all_logprob_token_ids[tp_slice] if all_logprob_token_ids is not None else None + else: + prompt_ids = all_prompt_ids + completion_ids = all_completion_ids + logprobs = all_logprobs + logprob_token_ids = all_logprob_token_ids + + if self.enable_sleep_mode: + self.llm.sleep(level=2) + + return prompt_ids, completion_ids, logprobs, logprob_token_ids diff --git a/tasks/tasksmith-b3c12843c3fb/solution/solve.sh b/tasks/tasksmith-b3c12843c3fb/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e909e364f2346a0d32d0e6d8045dcd25395ff3e6 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p -- /workspace/trl/generation +cp /solution/reference/trl/generation/vllm_generation.py /workspace/trl/generation/vllm_generation.py diff --git a/tasks/tasksmith-b3c12843c3fb/task.toml b/tasks/tasksmith-b3c12843c3fb/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2c613d6e8fb0ef2cbaacc007cca9f1cf481ca3f0 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/task.toml @@ -0,0 +1,116 @@ +schema_version = "1.3" + +[task] +name = "repo2rlenv/tasksmith-b3c12843c3fb" + +[metadata.repo2env] +recipe = "tasksmith" +recipe_version = "1" +source_url = "https://github.com/huggingface/trl/pull/6139" +source_head = "cc372fc272d3627ed5245b2adf36699592b6471a" +source_base = "b3caa40b7807fb866aef16ded227285a9825558f" +workspace_strategy = "head_minus_source_patch" +source_diff_sha256 = "7ebf5381df5e7e736b4111f40fd2dbb7b7ca930c54ac3703f38a11eccbc68a43" +acceptance_profile = "practical-generation-v1" +upstream_test_policy = "retain" +reward_kinds = [ + "test_execution", +] +quality_status = "exported" +fail_to_pass_count = 1 +pass_to_pass_count = 12 +bundle_hash = "sha256:f4b0728a2e2c045f611ed1f7574e737b689643e1c173cafeffd1709add2ad9ce" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "verified" +stage = "complete" +reason_codes = [ + "quality_verified", +] +detail = "Reviewed controls, semantic probes and blind rollout passed the quality profile." +checked_at = "2026-09-14T05:39:19.571309Z" +provenance = "unknown" +subject_bundle_hash = "sha256:f4b0728a2e2c045f611ed1f7574e737b689643e1c173cafeffd1709add2ad9ce" +profile = "practical-generation-v1" +source_task_path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v9/candidates/d4394947c06d/candidates/b3c12843c3fb/quality/revisions/r0/tasksmith-b3c12843c3fb" +source_task_toml_sha256 = "78b6c34f819296d623451c6072857747c363f085b5884d03778650aa025f5689" + +[[metadata.repo2env.evaluation.evidence]] +kind = "quality_result" +path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v9/candidates/d4394947c06d/candidates/b3c12843c3fb/quality/result.json" +sha256 = "be7090ec0c840dca4a609af1eecce8a7b67ac31e9d02a2595964f230ad36ab9b" +subject_bundle_hash = "sha256:f4b0728a2e2c045f611ed1f7574e737b689643e1c173cafeffd1709add2ad9ce" + +[[metadata.repo2env.evaluation.evidence]] +kind = "baseline" +path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v9/candidates/d4394947c06d/candidates/b3c12843c3fb/quality/trials/r0-baseline/tsbatch-1c3a4e1be0c6-d4394947c06d-q-b3c12843-r0-baseline/r2e-070fd341b1e4029e1dc74069/result.json" +sha256 = "c17d3b37a474f123230785670bce7faa06864297c09a87e14c92f1d582dc8e00" +subject_bundle_hash = "sha256:f4b0728a2e2c045f611ed1f7574e737b689643e1c173cafeffd1709add2ad9ce" +harbor_task_checksum = "563231ddc78a54490815d1ca885c847201205939f7ce0512259b812e019490db" + +[[metadata.repo2env.evaluation.evidence]] +kind = "oracle" +path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v9/candidates/d4394947c06d/candidates/b3c12843c3fb/quality/trials/r0-oracle/tsbatch-1c3a4e1be0c6-d4394947c06d-q-b3c12843-r0-oracle/r2e-98aa018a7611a3322f72b783/result.json" +sha256 = "754cc848099b8d5f392337a2211c2838b4f4ec26ea48eed89dcfc07ec77337da" +subject_bundle_hash = "sha256:f4b0728a2e2c045f611ed1f7574e737b689643e1c173cafeffd1709add2ad9ce" +harbor_task_checksum = "563231ddc78a54490815d1ca885c847201205939f7ce0512259b812e019490db" + +[[metadata.repo2env.evaluation.evidence]] +kind = "probe" +path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v9/candidates/d4394947c06d/candidates/b3c12843c3fb/quality/trials/r0-probe0/tsbatch-1c3a4e1be0c6-d4394947c06d-q-b3c12843-r0-probe0/r2e-5398efffe0042f001e094b34/result.json" +sha256 = "2c29b3356cb6c029ae7f457614e1aa11a25f2565d69f028c55fb7453bcf874b1" +subject_bundle_hash = "sha256:23b6f792d463dab65374d96ab28d2866e0569d85c0673452ace45f99407bcaa3" +harbor_task_checksum = "46a23c3186a7252a2deef6f1c77cd3091c069ee638292dae3fb4c191435f41e0" + +[[metadata.repo2env.evaluation.evidence]] +kind = "probe" +path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v9/candidates/d4394947c06d/candidates/b3c12843c3fb/quality/trials/r0-probe1/tsbatch-1c3a4e1be0c6-d4394947c06d-q-b3c12843-r0-probe1/r2e-948dce3d2878ba98b1747875/result.json" +sha256 = "5347a8767dca4555e84df6f44a7b9e8c2bd78fa22462bb75eb61bc33b534d609" +subject_bundle_hash = "sha256:4b167cff9a406813fd181e604c38a6864ba6847ccd0b7156fd61daffedd211f0" +harbor_task_checksum = "7705a5bf5d5aa5e7db87dd6576bc7141ce4d365ae598d5863ff82c5ac5dc2dd6" + +[[metadata.repo2env.evaluation.evidence]] +kind = "rollout" +path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v9/candidates/d4394947c06d/candidates/b3c12843c3fb/quality/trials/r0-rollout/tsbatch-1c3a4e1be0c6-d4394947c06d-q-b3c12843-r0-rollout/r2e-e2b5501072ac1d608ac258ce/result.json" +sha256 = "52ee1d673c1d00a10a43b4dc56c990fe5333134f1bcacb6ccefb9d7871ff311f" +subject_bundle_hash = "sha256:f4b0728a2e2c045f611ed1f7574e737b689643e1c173cafeffd1709add2ad9ce" +harbor_task_checksum = "563231ddc78a54490815d1ca885c847201205939f7ce0512259b812e019490db" + +[environment] +cpus = 4 +memory_mb = 16384 +build_timeout_sec = 600 +network_mode = "no-network" +gpus = 2 +gpu_types = [ + "L4", +] + +[agent] +timeout_sec = 600 +user = "learner" +network_mode = "no-network" + +[verifier] +timeout_sec = 240 +user = "root" +network_mode = "no-network" +environment_mode = "separate" + +[verifier.environment] +network_mode = "no-network" +cpus = 4 +memory_mb = 16384 +gpus = 2 +gpu_types = [ + "L4", +] + +[[artifacts]] +source = "/workspace/trl" +exclude = [ + "__pycache__", + "*.pyc", + ".pytest_cache", +] diff --git a/tasks/tasksmith-b3c12843c3fb/tests/Dockerfile b/tasks/tasksmith-b3c12843c3fb/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..95df0c963a770d99fc42715fa6eb4997e98040bb --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/Dockerfile @@ -0,0 +1,13 @@ +FROM pytorch/pytorch:2.11.0-cuda12.8-cudnn9-runtime +WORKDIR /workspace +RUN apt-get update && apt-get install -y --no-install-recommends python3-venv && rm -rf /var/lib/apt/lists/* +RUN python -m venv --system-site-packages /opt/tasksmith-venv +ENV PATH=/opt/tasksmith-venv/bin:$PATH +RUN python -m pip install --no-cache-dir setuptools==81.0.0 wheel==0.46.3 numpy==2.4.3 packaging==26.0 psutil==7.2.2 pytest==8.4.2 jinja2==3.1.6 transformers==5.17.0 accelerate==1.15.0 peft==0.20.0 pandas==3.0.5 datasets==5.0.1 parameterized==0.9.0 pillow==12.1.1 huggingface-hub==1.31.0 tokenizers==0.23.2 requests==2.32.5 safetensors==0.8.0 typing-extensions==4.16.0 +COPY source /workspace +RUN python -m pip install --no-cache-dir --no-deps --no-build-isolation -e . +ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 +ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1 +RUN useradd -m -u 1001 grader +COPY grade.py test_driver.py test_results.py contract.json test.sh /tests/ +RUN chmod 755 /tests && chmod 644 /tests/* diff --git a/tasks/tasksmith-b3c12843c3fb/tests/contract.json b/tasks/tasksmith-b3c12843c3fb/tests/contract.json new file mode 100644 index 0000000000000000000000000000000000000000..1df83707e1cad93114ce98949f4019985c28dcb7 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/contract.json @@ -0,0 +1 @@ +{"expected_passes": ["tests.tasksmith_behavior::test_barrier_called_before_generate_peft_tp2", "tests.tasksmith_behavior::test_colocate_tp1_non_peft_generate_completes", "tests.tasksmith_behavior::test_no_barrier_non_peft_tp2", "tests.tasksmith_behavior::test_no_barrier_peft_tp1", "tests.test_grpo_trainer.TestGRPORolloutDispatch::test_generate_prefers_rollout_func", "tests.test_grpo_trainer.TestGRPORolloutDispatch::test_generate_rollout_func_raises_when_required_keys_are_missing", "tests.test_grpo_trainer.TestGRPORolloutDispatch::test_generate_rollout_func_syncs_vllm_weights_when_needed", "tests.test_grpo_trainer.TestGetHighEntropyMask::test_compute_entropy_all_masked", "tests.test_grpo_trainer.TestGetHighEntropyMask::test_compute_entropy_mask_0", "tests.test_grpo_trainer.TestGetHighEntropyMask::test_compute_entropy_mask_1", "tests.test_grpo_trainer.TestGetHighEntropyMask::test_compute_entropy_mask_lower_threshold", "tests.test_grpo_trainer.TestGetHighEntropyMask::test_compute_entropy_threshold_0", "tests.test_grpo_trainer.TestGetHighEntropyMask::test_compute_entropy_threshold_1"], "immutable_assets": {"trl/accelerate_configs/fsdp1.yaml": "141c3c8ba7622f07dc508e94bbb4fe513a5dee7898d3adad2ec08530ba13d1ce", "trl/accelerate_configs/fsdp2.yaml": "ce0d4bde454325bee4beec483daa8c37a9994050f69af1bc2314919a463b7439", "trl/accelerate_configs/multi_gpu.yaml": "c835fe48fa3ca98dd25bc8ec7ffe775495f51b0215db4c2644f05b08a7f8ffc2", "trl/accelerate_configs/single_gpu.yaml": "e0cb8e6488c7362af669d3b36a83a00700fd2175d16cf34fcc16155bece473b2", "trl/accelerate_configs/zero1.yaml": "7f2525cb343f9e13faa1a98e80e04cecc0d932e1ef1b8c597e6ffedb09ee613a", "trl/accelerate_configs/zero2.yaml": "916e7cac52233b5273d3e4d68e0db35073b90540472384cf1485076f633e5a24", "trl/accelerate_configs/zero3.yaml": "54ddc70d2c449ff582bd8a4c2f8b6158eedca6bd8ddfd5700098ccbcfb707f11", "trl/chat_templates/README.md": "ef244427646b71bb8bd6ae8060d347c64926e12c8630c936a1e32f1fc68d3ddf", "trl/chat_templates/cohere.jinja": "90c33aee14aa2a226127516d48ee9184c9b90745d4a04c484621ec2e82fb712c", "trl/chat_templates/cohere2.jinja": "2147c474f41b522b7296f74692b9f31e45f49a31465960576a9d321339c5915a", "trl/chat_templates/cohere2_training.jinja": "7e5836a74c01d22504306273f8a7b49f944f6b960efee67609c07eef0a9ba295", "trl/chat_templates/cohere_training.jinja": "5f9718bfe3a1945366ea792b9714e42aa5849f1d41a1093c2ce4da4a77383996", "trl/chat_templates/deepseekv3.jinja": "563b1ce7d61d50a9b4c7439a912a1116f095b712df5b5e4d3e1116049874eb64", "trl/chat_templates/deepseekv3_training.jinja": "aadb4942004c186f9ba97d28f653d7f2e0dc20e4275352a486f7cafbe4dd7b51", "trl/chat_templates/gemma.jinja": "ecd6ae513fe103f0eb62e8ab5bfa8d0fe45c1074fa398b089c93a7e70c15cfd6", "trl/chat_templates/gemma3.jinja": "7de1c58e208eda46e9c7f86397df37ec49883aeece39fb961e0a6b24088dd3c4", "trl/chat_templates/gemma3_training.jinja": "959b257e7fc1603f8cae9c9890e62f43d6ded6c0f72b9b73c4106a4ceaa096fc", "trl/chat_templates/gemma_training.jinja": "f825de9ae80eac8a89fa5f9e6e80adf7b79ab8602564907e7c41dc15315d04ab", "trl/chat_templates/glm4moe.jinja": "44f815868bf02fa458dd2f741a338046f4bf45f398eb6d067766726b9d96cce3", "trl/chat_templates/glm4moe_training.jinja": "79c2386fbe44c9881be09b2dd086e0799b15447f8d530c45041152b6da9f3704", "trl/chat_templates/gptoss.jinja": "a4c9919cbbd4acdd51ccffe22da049264b1b73e59055fa58811a99efbd7c8146", "trl/chat_templates/gptoss_training.jinja": "6adda7cea0f63ef14918be7f26100b324525b6185a8f06932914388ffaa52e32", "trl/chat_templates/idefics3.jinja": "0d7e56ca41705b79932de707b22bc855c3cfcefae62f1ac5e458560654883d2e", "trl/chat_templates/idefics3_training.jinja": "b3d230222aae242eeda373f36f08c7170557dcbd4a93dfb2d2d3c718ee777654", "trl/chat_templates/llama3.jinja": "ba03a121d097859c7b5b9cd03af99aafe95275210d2876f642ad9929a150f122", "trl/chat_templates/llama3_1.jinja": "e10ca381b1ccc5cf9db52e371f3b6651576caee0a630b452e2816b2d404d4b65", "trl/chat_templates/llama3_2.jinja": "5816fce10444e03c2e9ee1ef8a4a1ea61ae7e69e438613f3b17b69d0426223a4", "trl/chat_templates/llama3_training.jinja": "9dce981e2954cf77d4d0ad2dbacf8006a5fda34a0bdf4923075a933d08b69470", "trl/chat_templates/llava_next.jinja": "2c17243a977fd0643fb549a509a8e2684f45517df0f9f608d5893b719f16569f", "trl/chat_templates/llava_next_training.jinja": "ae0ba79488f7c225ae69dc33d7d3ba3c23b1973c04d82cdd5f3f4cd165109742", "trl/chat_templates/nemotron_3_nano.jinja": "ab7813c3abdd9cb655905a410728b26c7884eca45ddfab8d9f931553485a7862", "trl/chat_templates/nemotron_3_nano_training.jinja": "f52a4a70292b98db4d1b9f69a59546a43fc5e8603a6794781973a3e5821bd475", "trl/chat_templates/nemotron_3_super.jinja": "575fb74f54ed264df9047d0ecce3c98938aae953fb4f50356675706264cbb68a", "trl/chat_templates/nemotron_3_super_training.jinja": "d3859585444574090259d403ca65f71a496b77b0b50f31106aa99a25f5caa692", "trl/chat_templates/nemotron_3_ultra.jinja": "82753bef5cedc4932c1ed509b5c9a12be680fd86d1adb65bc3f7398d11c8eebc", "trl/chat_templates/nemotron_3_ultra_training.jinja": "d61cca230ac4f8137e74e88d73d8a649e4c3a71bb79b82925a19cf6dc52a6c7e", "trl/chat_templates/phi3.jinja": "dcaee66df77bfbb789ec541fe713218da30225a526f1db97138fc39ee6dc56aa", "trl/chat_templates/phi3_5.jinja": "78d976a442bcde2f0be15aafbb8e3050e1104f86732266f68403251b89982a90", "trl/chat_templates/phi3_5_training.jinja": "a76a9651a9785afe269c6b91598d55f03ab8adf3d8489a4a9c8ef432128b7c08", "trl/chat_templates/phi3_training.jinja": "f00b774c5933129ee0a72bed355d9947cb09f8063d6cf23b7db71b33b5ea2162", "trl/chat_templates/qwen2_5.jinja": "cd8e9439f0570856fd70470bf8889ebd8b5d1107207f67a5efb46e342330527f", "trl/chat_templates/qwen2_5_training.jinja": "0cd86fb80f520885e35040a8df321540e729d3358da41f27cf74d33103d94f62", "trl/chat_templates/qwen2_5_vl.jinja": "a0bc6f6fc7a29a80017a433e8f03a1cc1236e838a944a2d034295a60c4f2fddb", "trl/chat_templates/qwen2_5_vl_training.jinja": "31c85932a6d8826f0fe8d52b81767eba6b869128b0a7c7503d1e7baaad4e8043", "trl/chat_templates/qwen3.jinja": "a55ee1b1660128b7098723e0abcd92caa0788061051c62d51cbe87d9cf1974d8", "trl/chat_templates/qwen3_5_nothink.jinja": "273d8e0e683b885071fb17e08d71e5f2a5ddfb5309756181681de4f5a1822d80", "trl/chat_templates/qwen3_5_nothink_training.jinja": "2394dc8c5833499b9aade0b513df8d164c69ec6e185fa84d1b57d4005342ad8c", "trl/chat_templates/qwen3_5_think.jinja": "a4aee8afcf2e0711942cf848899be66016f8d14a889ff9ede07bca099c28f715", "trl/chat_templates/qwen3_5_think_training.jinja": "22faf421afa07dab5d42477864a57449f7cdfb4e462ff26eb2dec02911eb09a0", "trl/chat_templates/qwen3_6.jinja": "e84f32a23fdda27689f868aa4a1a5621f41133e51a48d7f3efcbea2839574259", "trl/chat_templates/qwen3_6_training.jinja": "0d352aed09e9b292ef1b42ebbd37b23808b86424ae370adb81534780797d6ff9", "trl/chat_templates/qwen3_instruct_2507.jinja": "64f85b198065d0fba2a81f37e10ed68161ce2c19a754c7100e67e0ca2ee9c326", "trl/chat_templates/qwen3_instruct_2507_training.jinja": "48e17aa3caf5bf20075b6e7366864ee943e00b6f0752aadfe8b670c2ab0291a5", "trl/chat_templates/qwen3_training.jinja": "4c6e1cdccb191ce13a7af64dacdbf86c22df9d5456f7f14eac9cb8332e41be32", "trl/chat_templates/qwen3_vl.jinja": "3636d0f0bd6bef02654cdffdc447b79cb2cef8ab02cc75267345946291a489e4", "trl/chat_templates/qwen3_vl_training.jinja": "66bd81986bf7f8abe6d7fb4a50341c8d8ae14b16637e8fb876bca7e7ef0b9c6f", "trl/py.typed": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "trl/skills/trl-training/SKILL.md": "cfdec413fcf030f29205042cb8c56a0c5404f637919839704d7da5d04cb1958f", "trl/templates/completions_dataset_card.md": "e3c73984d04fd41b46d35198707587b7216c3312fd3badce5ca1e94f2936c4ec", "trl/templates/lm_model_card.md": "1940335bdac5a4de859f8efff30ac51ed11aaf3dd9653950b53d60be420983be", "trl/templates/rm_model_card.md": "a5ebd8cb4fc1f4e4e1b1c8f959c0d793fd05a29ba57dadc819e1d202bf0dc0b3"}, "optional_files": [], "submitted_files": ["trl/__init__.py", "trl/_compat.py", "trl/_lazy_module.py", "trl/chat_template_utils.py", "trl/cli/__init__.py", "trl/cli/accelerate_config.py", "trl/cli/accelerate_launcher.py", "trl/cli/commands/__init__.py", "trl/cli/commands/base.py", "trl/cli/commands/env.py", "trl/cli/commands/skills.py", "trl/cli/commands/training.py", "trl/cli/commands/vllm_serve.py", "trl/cli/main.py", "trl/data_utils.py", "trl/distributed.py", "trl/experimental/__init__.py", "trl/experimental/a2po/__init__.py", "trl/experimental/a2po/a2po_config.py", "trl/experimental/a2po/a2po_trainer.py", "trl/experimental/async_grpo/__init__.py", "trl/experimental/async_grpo/async_grpo_config.py", "trl/experimental/async_grpo/async_grpo_trainer.py", "trl/experimental/async_grpo/async_rollout_worker.py", "trl/experimental/async_grpo/weight_transfer.py", "trl/experimental/bco/__init__.py", "trl/experimental/bco/bco_config.py", "trl/experimental/bco/bco_trainer.py", "trl/experimental/bema_for_ref_model/__init__.py", "trl/experimental/bema_for_ref_model/callback.py", "trl/experimental/bema_for_ref_model/dpo_trainer.py", "trl/experimental/cpo/__init__.py", "trl/experimental/cpo/cpo_config.py", "trl/experimental/cpo/cpo_trainer.py", "trl/experimental/distillation/__init__.py", "trl/experimental/distillation/distillation_config.py", "trl/experimental/distillation/distillation_trainer.py", "trl/experimental/dppo/__init__.py", "trl/experimental/dppo/dppo_config.py", "trl/experimental/dppo/dppo_trainer.py", "trl/experimental/gfpo/__init__.py", "trl/experimental/gfpo/gfpo_config.py", "trl/experimental/gfpo/gfpo_trainer.py", "trl/experimental/gkd/__init__.py", "trl/experimental/gkd/gkd_config.py", "trl/experimental/gkd/gkd_trainer.py", "trl/experimental/gmpo/__init__.py", "trl/experimental/gmpo/gmpo_config.py", "trl/experimental/gmpo/gmpo_trainer.py", "trl/experimental/gold/__init__.py", "trl/experimental/gold/gold_config.py", "trl/experimental/gold/gold_trainer.py", "trl/experimental/grpo_with_replay_buffer/__init__.py", "trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_config.py", "trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_trainer.py", "trl/experimental/gspo_token/__init__.py", "trl/experimental/gspo_token/grpo_trainer.py", "trl/experimental/harbor/__init__.py", "trl/experimental/harbor/_env.py", "trl/experimental/harbor/_spec.py", "trl/experimental/kto/__init__.py", "trl/experimental/kto/kto_config.py", "trl/experimental/kto/kto_trainer.py", "trl/experimental/merge_model_callback.py", "trl/experimental/minillm/__init__.py", "trl/experimental/minillm/minillm_config.py", "trl/experimental/minillm/minillm_trainer.py", "trl/experimental/nash_md/__init__.py", "trl/experimental/nash_md/nash_md_config.py", "trl/experimental/nash_md/nash_md_trainer.py", "trl/experimental/online_dpo/__init__.py", "trl/experimental/online_dpo/online_dpo_config.py", "trl/experimental/online_dpo/online_dpo_trainer.py", "trl/experimental/openenv/__init__.py", "trl/experimental/openenv/utils.py", "trl/experimental/openreward/__init__.py", "trl/experimental/openreward/_spec.py", "trl/experimental/openreward/environment.py", "trl/experimental/orpo/__init__.py", "trl/experimental/orpo/orpo_config.py", "trl/experimental/orpo/orpo_trainer.py", "trl/experimental/papo/__init__.py", "trl/experimental/papo/papo_config.py", "trl/experimental/papo/papo_trainer.py", "trl/experimental/ppo/__init__.py", "trl/experimental/ppo/modeling_value_head.py", "trl/experimental/ppo/ppo_config.py", "trl/experimental/ppo/ppo_trainer.py", "trl/experimental/prm/__init__.py", "trl/experimental/prm/prm_config.py", "trl/experimental/prm/prm_trainer.py", "trl/experimental/sdft/__init__.py", "trl/experimental/sdft/loss_utils.py", "trl/experimental/sdft/sdft_config.py", "trl/experimental/sdft/sdft_trainer.py", "trl/experimental/sdft/teacher_sync.py", "trl/experimental/sdpo/__init__.py", "trl/experimental/sdpo/loss_utils.py", "trl/experimental/sdpo/sdpo_config.py", "trl/experimental/sdpo/sdpo_trainer.py", "trl/experimental/sdpo/teacher_sync.py", "trl/experimental/ssd/__init__.py", "trl/experimental/ssd/ssd_config.py", "trl/experimental/ssd/ssd_trainer.py", "trl/experimental/tpo/__init__.py", "trl/experimental/tpo/tpo_config.py", "trl/experimental/tpo/tpo_trainer.py", "trl/experimental/utils.py", "trl/experimental/xpo/__init__.py", "trl/experimental/xpo/xpo_config.py", "trl/experimental/xpo/xpo_trainer.py", "trl/extras/__init__.py", "trl/extras/dataset_formatting.py", "trl/extras/profiling.py", "trl/generation/__init__.py", "trl/generation/vllm_client.py", "trl/generation/vllm_generation.py", "trl/import_utils.py", "trl/models/__init__.py", "trl/models/activation_offloading.py", "trl/models/utils.py", "trl/rewards/__init__.py", "trl/rewards/accuracy_rewards.py", "trl/rewards/format_rewards.py", "trl/rewards/other_rewards.py", "trl/scripts/__init__.py", "trl/scripts/_hf_argparser.py", "trl/scripts/dpo.py", "trl/scripts/env.py", "trl/scripts/grpo.py", "trl/scripts/kto.py", "trl/scripts/reward.py", "trl/scripts/rloo.py", "trl/scripts/sft.py", "trl/scripts/utils.py", "trl/scripts/vllm_serve.py", "trl/skills/__init__.py", "trl/skills/cli.py", "trl/skills/skills.py", "trl/trainer/__init__.py", "trl/trainer/base_config.py", "trl/trainer/base_trainer.py", "trl/trainer/callbacks.py", "trl/trainer/dpo_config.py", "trl/trainer/dpo_trainer.py", "trl/trainer/grpo_config.py", "trl/trainer/grpo_trainer.py", "trl/trainer/kto_config.py", "trl/trainer/kto_trainer.py", "trl/trainer/model_config.py", "trl/trainer/reward_config.py", "trl/trainer/reward_trainer.py", "trl/trainer/rloo_config.py", "trl/trainer/rloo_trainer.py", "trl/trainer/sft_config.py", "trl/trainer/sft_trainer.py", "trl/trainer/utils.py"], "submitted_roots": ["trl"], "test_paths": ["tests/test_grpo_trainer.py::TestGetHighEntropyMask", "tests/test_grpo_trainer.py::TestGRPORolloutDispatch", "tests/tasksmith_behavior.py"], "timeout_sec": 210} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/tests/grade.py b/tasks/tasksmith-b3c12843c3fb/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..7e060dd2eaf372c0e83ae8f5aea784e5bd622402 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/grade.py @@ -0,0 +1,188 @@ +"""Standalone trusted entry point; copied into each separate verifier image. + +No Repo2RLEnv installation is needed to grade an exported task. Submitted Python +runs as an unprivileged user; this parent owns the result parser and reward file. +""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import os +import signal +import stat +import subprocess +import sys +import tempfile +from pathlib import Path + + +def child_environment(temporary: str) -> dict[str, str]: + """Preserve prepared runtime assets without inheriting controller credentials.""" + return { + **{ + key: os.environ[key] + for key in ( + "LD_LIBRARY_PATH", + "CUDA_VISIBLE_DEVICES", + "NVIDIA_VISIBLE_DEVICES", + "NVIDIA_DRIVER_CAPABILITIES", + "NCCL_SOCKET_IFNAME", + "GLOO_SOCKET_IFNAME", + "HF_HOME", + "HF_HUB_CACHE", + "HF_HUB_OFFLINE", + "TRANSFORMERS_OFFLINE", + "HF_DATASETS_OFFLINE", + ) + if key in os.environ + }, + "PATH": str(Path(sys.executable).parent) + ":/usr/local/bin:/usr/bin:/bin", + "HOME": temporary, + "PYTHONDONTWRITEBYTECODE": "1", + "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1", + } + + +def validate_submission(workspace: Path, contract: dict) -> None: + """Validate private staging and remove inert backups before importing Python.""" + submitted = set(contract["submitted_files"]) + backups: set[str] = set() + optional = submitted & set(contract.get("optional_files", [])) + paths = submitted - optional + for relative in optional: + path = workspace / relative + if any(component.is_symlink() for component in (path, *path.parents)): + raise ValueError("Submitted source contains a symlink") + # Added standalone modules may be absent in the baseline. If supplied, + # apply the same regular-file and size checks as every required module. + if path.exists(): + paths.add(relative) + roots = contract.get("submitted_roots", []) + immutable = contract.get("immutable_assets", {}) + paths.update(immutable) + for relative in roots: + root = workspace / relative + if root.is_symlink() or not root.is_dir(): + raise ValueError("Submitted source root is missing or linked") + for path in root.rglob("*"): + if path.is_symlink(): + raise ValueError("Submitted source contains a symlink") + if path.is_dir(): + continue + name = path.relative_to(workspace).as_posix() + if path.suffix != ".py" and name not in immutable: + if name not in submitted and path.name.endswith((".py.bak", ".py~")): + backups.add(name) + else: + raise ValueError("Only Python source files may be added") + paths.add(name) + for relative in sorted(paths): + path = workspace / relative + for component in (path, *path.parents): + if component.is_symlink(): + raise ValueError("Submitted source contains a symlink") + if ( + not path.is_file() + or not stat.S_ISREG(path.stat().st_mode) + or path.stat().st_size > 8 * 1024 * 1024 + ): + raise ValueError("Submitted source is not a bounded regular file") + if ( + relative in immutable + and hashlib.sha256(path.read_bytes()).hexdigest() != immutable[relative] + ): + raise ValueError("Non-Python source assets must remain unchanged") + if relative not in backups: + os.chown(path, 0, 0) + path.chmod(0o644) + # Only the verifier's collected copy is cleaned. The learner workspace and + # archived submission retain their bytes. Validate every path first so a + # backup cannot bypass linked, oversized, required, or immutable file checks. + for relative in sorted(backups): + (workspace / relative).unlink() + + +def main() -> None: + directory = Path("/tests") + parser_spec = importlib.util.spec_from_file_location( + "test_results", directory / "test_results.py" + ) + parser = importlib.util.module_from_spec(parser_spec) + sys.modules[parser_spec.name] = parser + parser_spec.loader.exec_module(parser) + contract = json.loads((directory / "contract.json").read_text()) + logs = Path("/logs/verifier") + logs.mkdir(parents=True, exist_ok=True) + logs.chmod(0o755) + reward = logs / "reward.txt" + reward.write_text("0\n") + reward.chmod(0o644) + try: + validate_submission(Path("/workspace"), contract) + except (ValueError, OSError) as exc: + (logs / "result.json").write_text(json.dumps({"passed": False, "reason": str(exc)})) + return + with tempfile.TemporaryDirectory(prefix="r2e-grade-") as temporary: + working = Path(temporary) + os.chown(working, 1001, 1001) + working.chmod(0o700) + report = working / "results.xml" + command = [ + sys.executable, + "-I", + "/tests/test_driver.py", + *contract["test_paths"], + "-q", + "--tb=short", + "-p", + "no:cacheprovider", + f"--junitxml={report}", + ] + with (logs / "stdout.txt").open("w") as stdout, (logs / "stderr.txt").open("w") as stderr: + process = subprocess.Popen( + command, + cwd="/workspace", + stdout=stdout, + stderr=stderr, + user=1001, + group=1001, + extra_groups=[], + start_new_session=True, + env=child_environment(temporary), + ) + try: + code = process.wait(timeout=contract["timeout_sec"]) + finally: + # Terminate descendants too: they must not keep modifying the + # child-owned report while the trusted parent checks it. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + if report.is_symlink() or not report.is_file() or report.stat().st_size > 16 * 1024 * 1024: + (logs / "result.json").write_text( + json.dumps({"passed": False, "returncode": code, "reason": "invalid_report"}) + ) + return + text = report.read_text() + (logs / "results.xml").write_text(text) + try: + parsed = parser.parse_junit(text, returncode=code) + except ValueError as exc: + (logs / "result.json").write_text( + json.dumps({"passed": False, "returncode": code, "reason": str(exc)}) + ) + return + expected = set(contract["expected_passes"]) + passed = code == 0 and bool(expected) and parsed.passed == expected + (logs / "result.json").write_text( + json.dumps({"passed": passed, "returncode": code, "statuses": parsed.statuses}) + ) + reward.write_text("1\n" if passed else "0\n") + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.ai/AGENTS.md b/tasks/tasksmith-b3c12843c3fb/tests/source/.ai/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..347a556b5bc6d8afa59ecb114ba705331c7295c3 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.ai/AGENTS.md @@ -0,0 +1,97 @@ +# AGENTS.md + +## Repository-specific guidance + +### Main code vs experimental code + +The repository is separated into **main code** and **experimental code**. + +* **Main code** should remain stable, consistent, and well-tested. +* **Experimental code** may be less stable and may contain inconsistent patterns or limited testing. + +Small non-invasive improvements that make experimental code more consistent with the main codebase are encouraged, but avoid large refactors. + +### Paper implementations + +If a PR implements a method, algorithm, or training approach from a research paper, it must also add a corresponding subsection to `paper_index.md`. + +When reviewing such PRs, ensure that `paper_index.md` was updated. + +### Code duplication and consistency + +Trainers in this repository are **self-contained by design**. Shared logic (generation, reward computation, metric logging, weight syncing, etc.) is deliberately duplicated across trainers rather than abstracted into a shared base class. + +This is intentional: each trainer must be readable, modifiable, and evolvable in isolation. The base class (`_BaseTrainer`) provides only minimal utilities (model card generation). Everything else — vLLM generation paths, `_get_per_token_logps_and_entropies`, `_calculate_rewards`, `_prepare_inputs`, metric logging — is copied in full. + +**The tradeoff**: duplication is accepted, but **consistency is mandatory**. When the same logic appears in multiple trainers, the duplicated blocks must stay aligned: + +- Same variable names (`self._last_loaded_step`, `self._metrics[mode]`, …) +- Same control flow structure (if/elif/else branches in the same order) +- Same comments (word-for-word when the logic is identical) +- Divergences only where the trainer's semantics require it (e.g., GRPO extracts logprobs from vLLM, RLOO discards them) + +**Consistency over correctness**: this is a strong requirement. When duplicating code, reproduce it exactly — even if you believe the original has a bug. Do not silently fix the issue in your copy. Instead, keep your copy consistent with the source and report the problem so it can be fixed across all trainers in a dedicated PR. A correct-but-inconsistent codebase is harder to maintain than a consistently-wrong one that can be fixed in a single sweep. + +**When modifying duplicated code**: if you change a pattern that exists in multiple trainers (e.g., the vLLM generation path in `_generate_single_turn`), apply the same change to all other trainers. A fix in GRPO often implies the same fix in RLOO, and vice versa. Not propagating a change is a bug. + +**When reviewing**: if a PR touches duplicated logic, verify that all copies are updated consistently. A common mistake is fixing one trainer and forgetting the others. + +### Simplicity + +This codebase values **leanness and simplicity above all**. Prefer straightforward, inline code over abstractions, helpers, or utilities — even at the cost of some robustness or generality. + +Concretely: + +- Do not add layers of indirection (registries, factory patterns, plugin systems). A contributor should be able to read a trainer top to bottom and understand the full flow. +- Prefer a simple implementation that covers 90% of cases over a complex one that covers 100%. A function that handles the common path in 20 lines is better than a catch-all that handles every edge case in 80. +- Do not add defensive code, fallback paths, or configuration options "just in case". Only handle cases that actually exist today. +- Avoid `hasattr` and `getattr`. Their use is almost always a symptom of overly defensive programming or a disguised version check (e.g., "this attribute was added in version X"). Instead, either drop the conditional entirely or express the version check explicitly with a version comparison. There is nearly always a cleaner alternative. +- When in doubt, prefer less code. Every new function, parameter, or branch is maintenance burden. The best abstraction is often no abstraction. + +## Documentation + +### Docstrings + +Docstrings must follow the repository format below. Do **not** convert docstrings to other styles (Google, NumPy, etc.). + +Rules: + +* Types appear in backticks inside parentheses: (`str`) +* Optional parameters are marked with `*optional*` +* Defaults are written as: `defaults to ` +* When the default is `None`, prefer ```(`str`, *optional*)``` instead of ```(`str` or `None`, *optional*, defaults to `None`)``` +* Union types use `or`: `str` or `None` +* References to classes use the format: [`~transformers.PreTrainedModel`] +* Class docstrings may group parameters using headers such as: `> Parameters for X:` + +Example: + +````python +def method(self, param1: str, param2: int = 1, param3: float | None = None): + """ + Brief one-line description of what this does. + + Args: + param1 (`str`): + Description of required param. + param2 (`int`, *optional*, defaults to `1`): + Description of optional param with default. + param3 (`float`, *optional*): + Description of optional param without explicit default. + + Returns: + `dict` with keys: + - `key1` (`list[int]`): + Description of this key. + + Examples: + + ```python + >>> my_func("hello") + ``` + """ +```` + +### Links to papers + +When linking to papers, use `https://huggingface.co/papers/` instead of `https://arxiv.org/abs/` (same ID suffix system). diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.cursor/BUGBOT.md b/tasks/tasksmith-b3c12843c3fb/tests/source/.cursor/BUGBOT.md new file mode 100644 index 0000000000000000000000000000000000000000..347a556b5bc6d8afa59ecb114ba705331c7295c3 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.cursor/BUGBOT.md @@ -0,0 +1,97 @@ +# AGENTS.md + +## Repository-specific guidance + +### Main code vs experimental code + +The repository is separated into **main code** and **experimental code**. + +* **Main code** should remain stable, consistent, and well-tested. +* **Experimental code** may be less stable and may contain inconsistent patterns or limited testing. + +Small non-invasive improvements that make experimental code more consistent with the main codebase are encouraged, but avoid large refactors. + +### Paper implementations + +If a PR implements a method, algorithm, or training approach from a research paper, it must also add a corresponding subsection to `paper_index.md`. + +When reviewing such PRs, ensure that `paper_index.md` was updated. + +### Code duplication and consistency + +Trainers in this repository are **self-contained by design**. Shared logic (generation, reward computation, metric logging, weight syncing, etc.) is deliberately duplicated across trainers rather than abstracted into a shared base class. + +This is intentional: each trainer must be readable, modifiable, and evolvable in isolation. The base class (`_BaseTrainer`) provides only minimal utilities (model card generation). Everything else — vLLM generation paths, `_get_per_token_logps_and_entropies`, `_calculate_rewards`, `_prepare_inputs`, metric logging — is copied in full. + +**The tradeoff**: duplication is accepted, but **consistency is mandatory**. When the same logic appears in multiple trainers, the duplicated blocks must stay aligned: + +- Same variable names (`self._last_loaded_step`, `self._metrics[mode]`, …) +- Same control flow structure (if/elif/else branches in the same order) +- Same comments (word-for-word when the logic is identical) +- Divergences only where the trainer's semantics require it (e.g., GRPO extracts logprobs from vLLM, RLOO discards them) + +**Consistency over correctness**: this is a strong requirement. When duplicating code, reproduce it exactly — even if you believe the original has a bug. Do not silently fix the issue in your copy. Instead, keep your copy consistent with the source and report the problem so it can be fixed across all trainers in a dedicated PR. A correct-but-inconsistent codebase is harder to maintain than a consistently-wrong one that can be fixed in a single sweep. + +**When modifying duplicated code**: if you change a pattern that exists in multiple trainers (e.g., the vLLM generation path in `_generate_single_turn`), apply the same change to all other trainers. A fix in GRPO often implies the same fix in RLOO, and vice versa. Not propagating a change is a bug. + +**When reviewing**: if a PR touches duplicated logic, verify that all copies are updated consistently. A common mistake is fixing one trainer and forgetting the others. + +### Simplicity + +This codebase values **leanness and simplicity above all**. Prefer straightforward, inline code over abstractions, helpers, or utilities — even at the cost of some robustness or generality. + +Concretely: + +- Do not add layers of indirection (registries, factory patterns, plugin systems). A contributor should be able to read a trainer top to bottom and understand the full flow. +- Prefer a simple implementation that covers 90% of cases over a complex one that covers 100%. A function that handles the common path in 20 lines is better than a catch-all that handles every edge case in 80. +- Do not add defensive code, fallback paths, or configuration options "just in case". Only handle cases that actually exist today. +- Avoid `hasattr` and `getattr`. Their use is almost always a symptom of overly defensive programming or a disguised version check (e.g., "this attribute was added in version X"). Instead, either drop the conditional entirely or express the version check explicitly with a version comparison. There is nearly always a cleaner alternative. +- When in doubt, prefer less code. Every new function, parameter, or branch is maintenance burden. The best abstraction is often no abstraction. + +## Documentation + +### Docstrings + +Docstrings must follow the repository format below. Do **not** convert docstrings to other styles (Google, NumPy, etc.). + +Rules: + +* Types appear in backticks inside parentheses: (`str`) +* Optional parameters are marked with `*optional*` +* Defaults are written as: `defaults to ` +* When the default is `None`, prefer ```(`str`, *optional*)``` instead of ```(`str` or `None`, *optional*, defaults to `None`)``` +* Union types use `or`: `str` or `None` +* References to classes use the format: [`~transformers.PreTrainedModel`] +* Class docstrings may group parameters using headers such as: `> Parameters for X:` + +Example: + +````python +def method(self, param1: str, param2: int = 1, param3: float | None = None): + """ + Brief one-line description of what this does. + + Args: + param1 (`str`): + Description of required param. + param2 (`int`, *optional*, defaults to `1`): + Description of optional param with default. + param3 (`float`, *optional*): + Description of optional param without explicit default. + + Returns: + `dict` with keys: + - `key1` (`list[int]`): + Description of this key. + + Examples: + + ```python + >>> my_func("hello") + ``` + """ +```` + +### Links to papers + +When linking to papers, use `https://huggingface.co/papers/` instead of `https://arxiv.org/abs/` (same ID suffix system). diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/ISSUE_TEMPLATE/bug-report.yml b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/ISSUE_TEMPLATE/bug-report.yml new file mode 100644 index 0000000000000000000000000000000000000000..fbf352cffccef11f4690e7b41346504f16ce8778 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/ISSUE_TEMPLATE/bug-report.yml @@ -0,0 +1,67 @@ +name: "\U0001F41B Bug Report" +description: Submit a bug report to help us improve TRL +labels: [ "bug" ] +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to fill out this bug report! 🤗 + + 🚩 If it is your first time submitting, be sure to check our [bug report guidelines](https://github.com/huggingface/trl/blob/main/CONTRIBUTING.md#did-you-find-a-bug) + + - type: textarea + id: reproduction + validations: + required: true + attributes: + label: Reproduction + description: | + Please provide a code sample that reproduces the problem you ran into. It can be a Colab link or just a code snippet. + If you have code snippets, error messages, stack traces please provide them here as well. + Important! Use code tags to correctly format your code. See https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting + Do not use screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code. + + value: | + ```python + from trl import ... + + ``` + + outputs: + + ``` + Traceback (most recent call last): + File "example.py", line 42, in + ... + ``` + + - type: textarea + id: system-info + attributes: + label: System Info + description: | + Please provide information about your system: platform, Python version, PyTorch version, Transformers version, devices, TRL version, ... + You can get this information by running `trl env` in your terminal. + + placeholder: Copy-paste the output of `trl env` + validations: + required: true + + - type: checkboxes + id: terms + attributes: + label: Checklist + description: | + Before submitting, please confirm that you've completed each of the following. + If an item doesn't apply to your issue, check it anyway to show you've reviewed it. + options: + - label: "I have checked that my issue isn't already filed (see [open issues](https://github.com/huggingface/trl/issues?q=is%3Aissue))" + required: true + - label: "I have included my system information" + required: true + - label: "Any code provided is minimal, complete, and reproducible ([more on MREs](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/creating-and-highlighting-code-blocks))" + required: true + - label: "Any code provided is properly formatted in code blocks, (no screenshot, [more on code blocks](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/creating-and-highlighting-code-blocks))" + required: true + - label: "Any traceback provided is complete" + required: true diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/ISSUE_TEMPLATE/feature-request.yml b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/ISSUE_TEMPLATE/feature-request.yml new file mode 100644 index 0000000000000000000000000000000000000000..0a593186c098ae3824ef994374686092f97ccb4a --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/ISSUE_TEMPLATE/feature-request.yml @@ -0,0 +1,31 @@ +name: "\U0001F680 Feature request" +description: Submit a proposal/request for a new TRL feature +labels: [ "Feature request" ] +body: + - type: textarea + id: feature-request + validations: + required: true + attributes: + label: Feature request + description: | + A clear and concise description of the feature proposal. Please provide a link to the paper and code in case they exist. + + - type: textarea + id: motivation + validations: + required: true + attributes: + label: Motivation + description: | + Please outline the motivation for the proposal. Is your feature request related to a problem? e.g., I'm always frustrated when [...]. If this is related to another GitHub issue, please link here too. + + + - type: textarea + id: contribution + validations: + required: true + attributes: + label: Your contribution + description: | + Is there any way that you could help, e.g. by submitting a PR? Make sure to read the CONTRIBUTING.MD [readme](https://github.com/huggingface/trl/blob/main/CONTRIBUTING.md) diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/ISSUE_TEMPLATE/new-trainer-addition.yml b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/ISSUE_TEMPLATE/new-trainer-addition.yml new file mode 100644 index 0000000000000000000000000000000000000000..ea0b5afb10ae6d7519d07ee510faf617f369048c --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/ISSUE_TEMPLATE/new-trainer-addition.yml @@ -0,0 +1,32 @@ +name: "\U0001F31F New trainer addition" +description: Submit a proposal/request to implement a new trainer for a post-training method +labels: [ "New trainer" ] + +body: + - type: textarea + id: description-request + validations: + required: true + attributes: + label: Method description + description: | + Put any and all important information relative to the method + + - type: checkboxes + id: information-tasks + attributes: + label: Open source status + description: | + Please note that if the method implementation isn't available or model weights with training datasets aren't available, we are less likely to implement it in `trl`. + options: + - label: "The method implementation is available" + - label: "The model weights are available" + - label: "The training datasets are available" + + - type: textarea + id: additional-info + attributes: + label: Provide useful links for the implementation + description: | + Please provide information regarding the implementation, the weights, and the authors. + Please mention the authors by @gh-username if you're aware of their usernames. diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/PULL_REQUEST_TEMPLATE.md b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000000000000000000000000000000000000..7280e8194b71d8a14e1a589634fc92d9a0607ef4 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,35 @@ +# What does this PR do? + + + + + +Fixes # (issue) + +## Before submitting + +- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case). +- [ ] Did you read the [contributor guideline](https://github.com/huggingface/trl/blob/main/CONTRIBUTING.md#create-a-pull-request), Pull Request section? +- [ ] Was this discussed/approved via a GitHub issue? Please add a link to it if that's the case. +- [ ] Did you make sure to update the documentation with your changes? +- [ ] Did you write any new necessary tests? + +## AI writing disclosure + +We welcome the use of AI tools to help with contributions. For transparency and to help us improve our review process, please indicate the level of AI involvement in this PR. + +- [ ] No AI usage: the PR was written entirely by a human. +- [ ] AI-assisted: some parts were suggested or improved by AI, but the PR was written and reviewed by a human. +- [ ] AI-generated: the PR was mostly or fully generated by an AI tool. + +## Who can review? + +Anyone in the community is free to review the PR once the tests have passed. Feel free to tag members/contributors who may be interested in your PR. diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/codeql/custom-queries.qls b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/codeql/custom-queries.qls new file mode 100644 index 0000000000000000000000000000000000000000..81deab4a871ed3b8114eeec45a4e2edbf9204b70 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/codeql/custom-queries.qls @@ -0,0 +1,19 @@ +import codeql + +from WorkflowString interpolation, Workflow workflow +where + interpolation.getStringValue().matches("${{ github.event.issue.title }}") or + interpolation.getStringValue().matches("${{ github.event.issue.body }}") or + interpolation.getStringValue().matches("${{ github.event.pull_request.title }}") or + interpolation.getStringValue().matches("${{ github.event.pull_request.body }}") or + interpolation.getStringValue().matches("${{ github.event.review.body }}") or + interpolation.getStringValue().matches("${{ github.event.comment.body }}") or + interpolation.getStringValue().matches("${{ github.event.inputs.* }}") or + interpolation.getStringValue().matches("${{ github.event.head_commit.message }}") + interpolation.getStringValue().matches("${{ github.event.* }}") and + ( + step.getKey() = "run" or // Injection in run + step.getKey() = "env" or // Injection via env + step.getKey() = "with" // Injection via with + ) +select workflow, "🚨 Do not use directly as input of action" diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/dependabot.yml b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..15f7bdd7916ac5fca2274ad5d1239bafe0f0f5a2 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/dependabot.yml @@ -0,0 +1,11 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + cooldown: + default-days: 7 + groups: + actions: + patterns: ["*"] diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/build_documentation.yml b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/build_documentation.yml new file mode 100644 index 0000000000000000000000000000000000000000..943903aad36816ec8dab599b5b48f99024403946 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/build_documentation.yml @@ -0,0 +1,21 @@ +name: Build documentation + +on: + push: + branches: + - main + - doc-builder* + - v*-release + +env: + TRL_EXPERIMENTAL_SILENCE: 1 + +jobs: + build: + uses: huggingface/doc-builder/.github/workflows/build_main_documentation.yml@bcff59fca682130d2e7271ca8589911b7ac0b8bf # main + with: + commit_sha: ${{ github.sha }} + package: trl + version_tag_suffix: "" + secrets: + hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }} diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/build_pr_documentation.yml b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/build_pr_documentation.yml new file mode 100644 index 0000000000000000000000000000000000000000..d52266b4ee7a63d61d4bd72a9b0138cfea70389e --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/build_pr_documentation.yml @@ -0,0 +1,21 @@ +name: Build PR Documentation + +on: + pull_request: + +env: + TRL_EXPERIMENTAL_SILENCE: 1 + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + build: + if: github.event.pull_request.draft == false + uses: huggingface/doc-builder/.github/workflows/build_pr_documentation.yml@bcff59fca682130d2e7271ca8589911b7ac0b8bf # main + with: + commit_sha: ${{ github.event.pull_request.head.sha }} + pr_number: ${{ github.event.number }} + package: trl + version_tag_suffix: "" diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/clear_cache.yml b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/clear_cache.yml new file mode 100644 index 0000000000000000000000000000000000000000..7508bc71d4b84e3f24a386f60e19828851e77082 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/clear_cache.yml @@ -0,0 +1,32 @@ +name: "Cleanup Cache" + +on: + workflow_dispatch: + schedule: + - cron: "0 0 * * *" + +jobs: + cleanup: + runs-on: ubuntu-latest + steps: + - name: Check out code + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: Cleanup + run: | + gh extension install actions/gh-actions-cache + + echo "Fetching list of cache key" + cacheKeysForPR=$(gh actions-cache list -R $REPO | cut -f 1 ) + + ## Setting this to not fail the workflow while deleting cache keys. + set +e + echo "Deleting caches..." + for cacheKey in $cacheKeysForPR + do + gh actions-cache delete $cacheKey -R $REPO --confirm + done + echo "Done" + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPO: ${{ github.repository }} diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/codeQL.yml b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/codeQL.yml new file mode 100644 index 0000000000000000000000000000000000000000..8c2b108ee1b880ca2150830dd8ff1e6c49953139 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/codeQL.yml @@ -0,0 +1,26 @@ +name: "CodeQL Analysis - Workflows" + +on: + workflow_dispatch: + +jobs: + analyze: + name: "Analyze GitHub Workflows" + runs-on: ubuntu-latest + permissions: + security-events: write + actions: read + contents: read + + steps: + - name: "Checkout repository" + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: "Initialize CodeQL" + uses: github/codeql-action/init@8aad20d150bbac5944a9f9d289da16a4b0d87c1e # v4.36.2 + with: + languages: "actions" + queries: +security-and-quality, ./.github/codeql/custom-queries.qls + + - name: "Perform CodeQL Analysis" + uses: github/codeql-action/analyze@8aad20d150bbac5944a9f9d289da16a4b0d87c1e # v4.36.2 diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/docker-build.yml b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/docker-build.yml new file mode 100644 index 0000000000000000000000000000000000000000..5a44cd0243fcf366aa83f8d3e58414c77aeae4e3 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/docker-build.yml @@ -0,0 +1,96 @@ +name: Build TRL Docker image + +on: + push: + branches: + - main + workflow_dispatch: + +concurrency: + group: docker-image-builds + cancel-in-progress: false + +jobs: + trl: + name: "Build and push TRL Docker image" + runs-on: + group: aws-general-8-plus + steps: + - name: Checkout code + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: Get TRL version from PyPI + run: | + VERSION=$(curl -s https://pypi.org/pypi/trl/json | jq -r .info.version) + if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+([a-zA-Z0-9._-]*)?$ ]]; then + echo "Invalid version format: $VERSION" + exit 1 + fi + if [[ ${#VERSION} -gt 50 ]]; then + echo "Version string too long: $VERSION" + exit 1 + fi + echo "VERSION=$VERSION" >> $GITHUB_ENV + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0 + + - name: Login to DockerHub + uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + + - name: Build and Push + uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7.2.0 + env: + VERSION: ${{ env.VERSION }} + with: + context: docker/trl + push: true + tags: | + huggingface/trl:${{ env.VERSION }} + huggingface/trl + + - name: Post to Slack + if: always() + uses: huggingface/hf-workflows/.github/actions/post-slack@a88e7fa2eaee28de5a4d6142381b1fb792349b67 # main + with: + slack_channel: ${{ secrets.CI_DOCKER_CHANNEL }} + title: 🤗 Results of the TRL Dev Docker Image build + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + + trl-dev: + name: "Build and push TRL Dev Docker image" + runs-on: + group: aws-general-8-plus + steps: + - name: Checkout code + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0 + + - name: Login to DockerHub + uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + + - name: Build and Push + uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7.2.0 + with: + context: docker/trl-dev + push: true + tags: | + huggingface/trl:dev + + - name: Post to Slack + if: always() + uses: huggingface/hf-workflows/.github/actions/post-slack@a88e7fa2eaee28de5a4d6142381b1fb792349b67 # main + with: + slack_channel: ${{ secrets.CI_DOCKER_CHANNEL }} + title: 🤗 Results of the TRL Dev Docker Image build + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/pr_template_check.yml b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/pr_template_check.yml new file mode 100644 index 0000000000000000000000000000000000000000..5eb6836d908aab6167bb147727ec139ad89f7c4e --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/pr_template_check.yml @@ -0,0 +1,82 @@ +# This workflow runs when a PR is first opened by an external contributor +# (author_association is FIRST_TIME_CONTRIBUTOR, FIRST_TIMER, or NONE). +# Org members with public membership are skipped (author_association = MEMBER). +# It checks that the PR body: +# 1. Contains a non-empty description (not just the template placeholder) +# 2. Includes the "## Before submitting" checklist +# 3. Has at least one checkbox checked +# If any check fails, the workflow posts a comment and closes the PR. + +name: PR Template Check + +on: + pull_request_target: + types: [opened] + +permissions: + pull-requests: write + issues: write + statuses: write + +jobs: + check-pr-template: + runs-on: ubuntu-latest + if: > + github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR' || + github.event.pull_request.author_association == 'FIRST_TIMER' || + github.event.pull_request.author_association == 'NONE' + steps: + - name: Check PR body follows template + id: check + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + PR_BODY: ${{ github.event.pull_request.body }} + with: + script: | + const body = process.env.PR_BODY || ""; + + const errors = []; + + // 1. Must have a non-placeholder description (the "What does this PR do?" section) + const descriptionSection = body.split("## Before submitting")[0] || ""; + const strippedDescription = descriptionSection + .replace(//g, "") // remove HTML comments + .replace(/Fixes\s*#\s*\(issue\)/gi, "") // remove placeholder issue line + .trim(); + + if (strippedDescription.length < 20) { + errors.push("- Missing PR description: please explain what this PR does and why."); + } + + // 2. Must have the "Before submitting" checklist + if (!body.includes("## Before submitting")) { + errors.push("- Missing '## Before submitting' checklist section."); + } + + // 3. At least one checkbox must be checked + const checkedBoxes = (body.match(/- \[x\]/gi) || []).length; + if (checkedBoxes === 0) { + errors.push("- No checkboxes are checked in the 'Before submitting' section. Please review and check the relevant items."); + } + + if (errors.length > 0) { + const comment = "Your PR has been closed because it does not follow the required [PR template](https://github.com/huggingface/trl/blob/main/.github/PULL_REQUEST_TEMPLATE.md). Please open a new PR following the template. See [CONTRIBUTING.md](https://github.com/huggingface/trl/blob/main/CONTRIBUTING.md#submitting-a-pull-request-pr) for guidance."; + + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.payload.pull_request.number, + body: comment, + }); + + await github.rest.pulls.update({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.payload.pull_request.number, + state: "closed", + }); + + core.setFailed("PR does not follow the required template."); + } else { + console.log("PR template check passed."); + } diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/publish.yml b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/publish.yml new file mode 100644 index 0000000000000000000000000000000000000000..70b6b370dd1a1bb3113ab68b1ae6b1f79572d664 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/publish.yml @@ -0,0 +1,43 @@ +name: Publish to PyPI + +on: + push: + branches: + - main + - v*-release + paths: + - "VERSION" + +jobs: + publish: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: Read version + id: get_version + run: echo "version=$(cat VERSION)" >> $GITHUB_OUTPUT + + - name: Debug - Show version.txt content + run: echo "Version is ${{ steps.get_version.outputs.version }}" + + - name: Set up Python + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 #v6.2.0 + with: + python-version: "3.x" + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install build twine + + - name: Build package + run: python -m build + + - name: Publish to PyPI + if: ${{ !contains(steps.get_version.outputs.version, 'dev') }} + env: + TWINE_USERNAME: __token__ + TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }} + run: | + python -m twine upload dist/* diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/slow-tests.yml b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/slow-tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..753fb20ef78c0197096339af1d6cc9ce4a148730 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/slow-tests.yml @@ -0,0 +1,110 @@ +name: Slow tests (on push) + +on: + push: + branches: [main] + paths: + # Run only when python files are modified + - "trl/**.py" + - "examples/**.py" +env: + RUN_SLOW: "yes" + IS_GITHUB_CI: "1" + SLACK_API_TOKEN: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + HF_TOKEN: ${{ secrets.HF_TOKEN }} + TRL_EXPERIMENTAL_SILENCE: 1 + +jobs: + run_all_tests_single_gpu: + runs-on: + group: aws-g4dn-2xlarge + env: + CUDA_VISIBLE_DEVICES: "0" + TEST_TYPE: "single_gpu" + container: + image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel + options: --gpus all --shm-size "16gb" + defaults: + run: + shell: bash + steps: + - name: Git checkout + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: Install system dependencies + run: | + apt-get update && apt-get install -y make git curl + + - name: Install uv + uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0 + + - name: Create Python virtual environment + run: | + uv venv + uv pip install --upgrade setuptools wheel + + - name: Install dependencies + run: | + source .venv/bin/activate + uv pip install ".[dev]" + uv pip install pytest-reportlog + + - name: Run slow SFT tests on single GPU + if: always() + run: | + source .venv/bin/activate + make slow_tests + + - name: Generate Report + if: always() + run: | + source .venv/bin/activate + uv pip install slack_sdk tabulate + python scripts/log_reports.py >> $GITHUB_STEP_SUMMARY + + run_all_tests_multi_gpu: + runs-on: + group: aws-g4dn-2xlarge + env: + CUDA_VISIBLE_DEVICES: "0,1" + TEST_TYPE: "multi_gpu" + container: + image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel + options: --gpus all --shm-size "16gb" + defaults: + run: + shell: bash + steps: + - name: Git checkout + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: Install system dependencies + run: | + apt-get update && apt-get install -y make git curl + + - name: Install uv + uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0 + + - name: Create Python virtual environment + run: | + uv venv + uv pip install --upgrade setuptools wheel + + - name: Install dependencies + run: | + source .venv/bin/activate + uv pip install ".[dev]" + uv pip install pytest-reportlog + + - name: Run slow SFT tests on Multi GPU + if: always() + run: | + source .venv/bin/activate + make slow_tests + + - name: Generate Reports + if: always() + run: | + source .venv/bin/activate + uv pip install slack_sdk tabulate + python scripts/log_reports.py >> $GITHUB_STEP_SUMMARY diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/sync-huggingface-skills.yml b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/sync-huggingface-skills.yml new file mode 100644 index 0000000000000000000000000000000000000000..ad2a60680cd5dc7a7810ea139b5e6f8e4cb815ed --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/sync-huggingface-skills.yml @@ -0,0 +1,91 @@ +name: Sync TRL skill with huggingface/skills + +on: + push: + tags: + - 'v*' + - '!v*rc*' + workflow_dispatch: + +jobs: + sync-skills: + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - name: Checkout trl repo + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: Set up Python + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: '3.12' + + - name: Determine PR title + id: pr_title + run: | + if [[ "${{ github.event_name }}" == "push" && "${{ github.ref_type }}" == "tag" ]]; then + echo "title=Sync TRL Skill (${{ github.ref_name }})" >> $GITHUB_OUTPUT + else + echo "title=Sync TRL Skill (manual trigger)" >> $GITHUB_OUTPUT + fi + + - name: Create GitHub App token + id: app_token + uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 + with: + app-id: ${{ secrets.APP_ID_HUB_SKILLS_REPO }} + private-key: ${{ secrets.APP_SECRET_PREM_HUB_SKILLS_REPO }} + repositories: skills + + - name: Checkout huggingface/skills repo + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + repository: huggingface/skills + token: ${{ steps.app_token.outputs.token }} + path: skills-repo + + - name: Set up uv + uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0 + + - name: Copy generated files + run: cp trl/skills/trl-training/SKILL.md skills-repo/skills/trl-training/ + + - name: Check for TRL skill changes + id: check_changes + working-directory: skills-repo + # git diff returns zero if there is no diff + run: | + if git diff --quiet -- skills/trl-training/SKILL.md; then + echo "changed=false" >> "$GITHUB_OUTPUT" + echo "No trl skill changes; skipping PR" + else + echo "changed=true" >> "$GITHUB_OUTPUT" + fi + + - name: Regenerate skills repo artifacts + if: steps.check_changes.outputs.changed == 'true' + working-directory: skills-repo + run: | + ./scripts/publish.sh + + - name: Create Pull Request + if: steps.check_changes.outputs.changed == 'true' + uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1 + with: + token: ${{ steps.app_token.outputs.token }} + path: skills-repo + branch: sync/hf-cli-${{ github.run_id }} + delete-branch: true + title: ${{ steps.pr_title.outputs.title }} + body: | + Auto-generated from [trl@${{ github.sha }}](https://github.com/huggingface/trl/commit/${{ github.sha }}) + + Triggered by changes to `trl/skills/trl-training` + + --- + This PR was created automatically by the [sync-huggingface-skills](https://github.com/huggingface/trl/blob/main/.github/workflows/sync-huggingface-skills.yml) workflow. + commit-message: "Sync TRL skill from trl@${{ github.sha }}" + labels: | + automated + cli-sync diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/tests-experimental.yml b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/tests-experimental.yml new file mode 100644 index 0000000000000000000000000000000000000000..b21cf32ac6435c6b7fee2537fbc116cd7ae111d3 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/tests-experimental.yml @@ -0,0 +1,71 @@ +name: Tests (experimental) + +on: + pull_request: + paths: + # Run only when relevant files are modified + - "trl/experimental/**" + - "tests/experimental/**" + +env: + TQDM_DISABLE: 1 + HF_TOKEN: ${{ secrets.HF_TOKEN }} + PYTORCH_CUDA_ALLOC_CONF: "expandable_segments:True" + PYTORCH_ALLOC_CONF: "expandable_segments:True" + TRL_EXPERIMENTAL_SILENCE: 1 + +jobs: + check_code_quality: + name: Check code quality + runs-on: ubuntu-latest + if: github.event.pull_request.draft == false + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + - name: Set up Python 3.13 + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: 3.13 + - uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1 + with: + extra_args: --all-files + + tests: + name: Tests (experimental) + runs-on: + group: aws-g4dn-2xlarge + container: + image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel + options: --gpus all + defaults: + run: + shell: bash + steps: + - name: Git checkout + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: Set up Python 3.13 + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: 3.13 + + - name: Install Make and Git + run: | + apt-get update && apt-get install -y make git curl + + - name: Install uv + uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0 + + - name: Create Python virtual environment + run: | + uv venv + uv pip install --upgrade setuptools wheel + + - name: Install dependencies + run: | + source .venv/bin/activate + uv pip install ".[dev]" + + - name: Test with pytest + run: | + source .venv/bin/activate + make test_experimental diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/tests.yml b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..3bde735e85cf41f42cd9e6a889341016fc192682 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/tests.yml @@ -0,0 +1,311 @@ +name: Tests + +on: + push: + branches: + - main + - ci-* + pull_request: + paths: + # Run only when relevant files are modified + - ".github/**.yml" + - "examples/**.py" + - "scripts/**.py" + - "tests/**.py" + - "trl/**.py" + - "pyproject.toml" + # Exclude if only experimental code/tests + - "!trl/experimental/**" + - "!tests/experimental/**" + +env: + TQDM_DISABLE: 1 + CI_SLACK_CHANNEL: ${{ secrets.CI_PUSH_MAIN_CHANNEL }} + HF_TOKEN: ${{ secrets.HF_TOKEN }} + PYTORCH_CUDA_ALLOC_CONF: "expandable_segments:True" + PYTORCH_ALLOC_CONF: "expandable_segments:True" + +jobs: + check_code_quality: + name: Check code quality + runs-on: ubuntu-latest + if: github.event.pull_request.draft == false + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + - name: Set up Python 3.12 + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: 3.12 + - uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1 + with: + extra_args: --all-files + + tests: + name: Tests + strategy: + matrix: + python-version: ['3.10', '3.11', '3.12', '3.13', '3.14'] + fail-fast: false + runs-on: + group: aws-g4dn-2xlarge + container: + image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel + options: --gpus all + defaults: + run: + shell: bash + if: github.event.pull_request.draft == false + steps: + - name: Git checkout + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: ${{ matrix.python-version }} + + - name: Install Make and Git + run: | + apt-get update && apt-get install -y make git curl + + - name: Install uv + uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0 + + - name: Create Python virtual environment + run: | + uv venv + uv pip install --upgrade setuptools wheel + + - name: Install dependencies + run: | + source .venv/bin/activate + uv pip install ".[dev]" + + - name: Test with pytest + run: | + source .venv/bin/activate + make test + + - name: Post to Slack + if: github.ref == 'refs/heads/main' && always() # Check if the branch is main + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ env.CI_SLACK_CHANNEL }} + title: Results with Python ${{ matrix.python-version }} and latest dependencies + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + + tests_dev: + name: Tests with dev dependencies + runs-on: + group: aws-g4dn-2xlarge + container: + image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel + options: --gpus all + defaults: + run: + shell: bash + if: github.event.pull_request.draft == false + steps: + - name: Git checkout + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: Set up Python 3.12 + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: '3.12' + + - name: Install Make and Git + run: | + apt-get update && apt-get install -y make git curl + + - name: Install uv + uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0 + + - name: Create Python virtual environment + run: | + uv venv + uv pip install --upgrade setuptools wheel + + - name: Install dependencies + run: | + source .venv/bin/activate + uv pip install -U \ + ".[dev]" \ + "accelerate @ git+https://github.com/huggingface/accelerate.git" \ + "datasets @ git+https://github.com/huggingface/datasets.git" \ + "transformers @ git+https://github.com/huggingface/transformers.git" \ + "peft @ git+https://github.com/huggingface/peft.git" + + - name: Test with pytest + run: | + source .venv/bin/activate + make test + + - name: Post to Slack + if: github.ref == 'refs/heads/main' && always() # Check if the branch is main + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ env.CI_SLACK_CHANNEL }} + title: Results with Python 3.12 and dev dependencies + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + + tests_wo_optional_deps: + name: Tests without optional dependencies + runs-on: + group: aws-g4dn-2xlarge + container: + image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel + options: --gpus all + defaults: + run: + shell: bash + if: github.event.pull_request.draft == false + steps: + - name: Git checkout + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: Set up Python 3.12 + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: '3.12' + + - name: Install Make and Git + run: | + apt-get update && apt-get install -y make git curl + + - name: Install uv + uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0 + + - name: Create Python virtual environment + run: | + uv venv + uv pip install --upgrade setuptools wheel + + - name: Install dependencies + run: | + source .venv/bin/activate + uv pip install ".[test]" + + - name: Test with pytest + run: | + source .venv/bin/activate + make test + + - name: Post to Slack + if: github.ref == 'refs/heads/main' && always() # Check if the branch is main + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ env.CI_SLACK_CHANNEL }} + title: Results with Python 3.12 without optional dependencies + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + + tests_min_versions: + name: Tests with minimum versions + runs-on: + group: aws-g4dn-2xlarge + container: + image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel + options: --gpus all + defaults: + run: + shell: bash + if: github.event.pull_request.draft == false + steps: + - name: Git checkout + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: Set up Python 3.12 + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: '3.12' + + - name: Install Make and Git + run: | + apt-get update && apt-get install -y make git curl + + - name: Install uv + uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0 + + - name: Create Python virtual environment + run: | + uv venv + uv pip install --upgrade setuptools wheel + + - name: Install dependencies + run: | + source .venv/bin/activate + uv pip install \ + ".[dev]" \ + "accelerate==1.4.0" \ + "datasets==4.7.0" \ + "transformers==4.56.2" + + - name: Test with pytest + run: | + source .venv/bin/activate + make test + + - name: Post to Slack + if: github.ref == 'refs/heads/main' && always() # Check if the branch is main + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ env.CI_SLACK_CHANNEL }} + title: Results with Python 3.12 and minimum dependencies versions + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + + distributed_smoke: + name: Distributed smoke tests + runs-on: + group: aws-g5-12xlarge-cache + container: + image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel + options: --gpus all + defaults: + run: + shell: bash + if: github.event.pull_request.draft == false + env: + CUDA_VISIBLE_DEVICES: "0,1" + steps: + - name: Git checkout + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: Set up Python 3.12 + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: '3.12' + + - name: Install Make and Git + run: | + apt-get update && apt-get install -y make git curl + + - name: Install uv + uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0 + + - name: Create Python virtual environment + run: | + uv venv + uv pip install --upgrade setuptools wheel + + - name: Install dependencies + run: | + source .venv/bin/activate + uv pip install ".[dev]" + + - name: Run distributed smoke tests + run: | + source .venv/bin/activate + pytest -v tests/distributed/test_distributed.py + + - name: Post to Slack + if: github.ref == 'refs/heads/main' && always() # Check if the branch is main + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ env.CI_SLACK_CHANNEL }} + title: Results of distributed smoke tests + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/tests_latest.yml b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/tests_latest.yml new file mode 100644 index 0000000000000000000000000000000000000000..ae938d210a138630e47ff2f061d8eb29770863bc --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/tests_latest.yml @@ -0,0 +1,68 @@ +name: Tests latest TRL release with dev dependencies + +on: + schedule: + - cron: '0 0 * * *' # Runs daily at midnight UTC + + workflow_dispatch: + +env: + TQDM_DISABLE: 1 + CI_SLACK_CHANNEL: ${{ secrets.CI_PUSH_MAIN_CHANNEL }} + HF_TOKEN: ${{ secrets.HF_TOKEN }} + TRL_EXPERIMENTAL_SILENCE: 1 + +jobs: + tests: + name: Tests latest TRL release with dev dependencies + runs-on: + group: aws-g4dn-2xlarge + container: + image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel + options: --gpus all + defaults: + run: + shell: bash + steps: + - name: Git checkout + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: { ref: v1.7-release } + + - name: Set up Python 3.12 + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: '3.12' + + - name: Install Make and Git + run: | + apt-get update && apt-get install -y make git curl + + - name: Install uv + uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0 + + - name: Create Python virtual environment + run: | + uv venv + uv pip install --upgrade setuptools wheel + + - name: Install dependencies + run: | + source .venv/bin/activate + uv pip install -U \ + ".[dev]" \ + "accelerate @ git+https://github.com/huggingface/accelerate.git" \ + "datasets @ git+https://github.com/huggingface/datasets.git" \ + "transformers @ git+https://github.com/huggingface/transformers.git" + + - name: Test with pytest + run: | + source .venv/bin/activate + make test + + - name: Post to Slack + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ env.CI_SLACK_CHANNEL }} + title: Results of latest TRL with Python 3.12 and dev dependencies + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/tests_transformers_branch.yml b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/tests_transformers_branch.yml new file mode 100644 index 0000000000000000000000000000000000000000..f83190b29c44533cdd287e3ef84aa9206f4a0e9c --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/tests_transformers_branch.yml @@ -0,0 +1,127 @@ +name: Tests against Transformers branch + +on: + workflow_dispatch: + inputs: + transformers_ref: + description: "Transformers git ref (branch, tag, or commit SHA)" + required: true + default: "main" + +env: + TQDM_DISABLE: 1 + CI_SLACK_CHANNEL: ${{ secrets.CI_PUSH_MAIN_CHANNEL }} + HF_TOKEN: ${{ secrets.HF_TOKEN }} + PYTORCH_CUDA_ALLOC_CONF: "expandable_segments:True" + PYTORCH_ALLOC_CONF: "expandable_segments:True" + +jobs: + tests_transformers_branch: + name: Tests with Transformers ${{ inputs.transformers_ref }} + runs-on: + group: aws-g4dn-2xlarge + container: + image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel + options: --gpus all + defaults: + run: + shell: bash + steps: + - name: Git checkout + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: Set up Python 3.12 + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: '3.12' + + - name: Install Make and Git + run: | + apt-get update && apt-get install -y make git curl + + - name: Install uv + uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0 + + - name: Create Python virtual environment + run: | + uv venv + uv pip install --upgrade setuptools wheel + + - name: Install dependencies + env: + TRANSFORMERS_REF: ${{ inputs.transformers_ref }} + run: | + source .venv/bin/activate + uv pip install -U \ + ".[dev]" \ + "transformers @ git+https://github.com/huggingface/transformers.git@${TRANSFORMERS_REF}" + + - name: Test with pytest + run: | + source .venv/bin/activate + make test + + - name: Post to Slack + if: github.ref == 'refs/heads/main' && always() + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ env.CI_SLACK_CHANNEL }} + title: Results with Transformers ${{ inputs.transformers_ref }} + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + + distributed_smoke: + name: Distributed smoke tests with Transformers ${{ inputs.transformers_ref }} + runs-on: + group: aws-g5-12xlarge-cache + container: + image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel + options: --gpus all + defaults: + run: + shell: bash + env: + CUDA_VISIBLE_DEVICES: "0,1" + steps: + - name: Git checkout + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: Set up Python 3.12 + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: '3.12' + + - name: Install Make and Git + run: | + apt-get update && apt-get install -y make git curl + + - name: Install uv + uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0 + + - name: Create Python virtual environment + run: | + uv venv + uv pip install --upgrade setuptools wheel + + - name: Install dependencies + env: + TRANSFORMERS_REF: ${{ inputs.transformers_ref }} + run: | + source .venv/bin/activate + uv pip install -U \ + ".[dev]" \ + "transformers @ git+https://github.com/huggingface/transformers.git@${TRANSFORMERS_REF}" + + - name: Run distributed smoke tests + run: | + source .venv/bin/activate + pytest -v tests/distributed/test_distributed.py + + - name: Post to Slack + if: github.ref == 'refs/heads/main' && always() + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ env.CI_SLACK_CHANNEL }} + title: Results of distributed smoke tests with Transformers ${{ inputs.transformers_ref }} + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/trufflehog.yml b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/trufflehog.yml new file mode 100644 index 0000000000000000000000000000000000000000..e22a891b2d1b2afa8d914dd81b118aa53addc8e7 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/trufflehog.yml @@ -0,0 +1,18 @@ +on: + push: + +name: Secret Leaks + +jobs: + trufflehog: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + fetch-depth: 0 + - name: Secret Scanning + uses: trufflesecurity/trufflehog@d411fff7b8879a62509f3fa98c07f247ac089a51 # v3.95.5 + with: + # exclude buggy postgres detector that is causing false positives and not relevant to our codebase + extra_args: --results=verified,unknown --exclude-detectors=postgres diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/upload_pr_documentation.yml b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/upload_pr_documentation.yml new file mode 100644 index 0000000000000000000000000000000000000000..fb13fbd597b164890d4f22413f078a1ca96c6779 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.github/workflows/upload_pr_documentation.yml @@ -0,0 +1,17 @@ +name: Upload PR Documentation + +on: + workflow_run: + workflows: ["Build PR Documentation"] + types: + - completed + +jobs: + build: + uses: huggingface/doc-builder/.github/workflows/upload_pr_documentation.yml@bcff59fca682130d2e7271ca8589911b7ac0b8bf # main + with: + package_name: trl + secrets: + hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }} + comment_bot_app_id: ${{ secrets.COMMENT_BOT_APP_ID }} + comment_bot_secret_pem: ${{ secrets.COMMENT_BOT_SECRET_PEM }} \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.gitignore b/tasks/tasksmith-b3c12843c3fb/tests/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6219ed974aa8d884323fbfca2c26694d3abd1683 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.gitignore @@ -0,0 +1,152 @@ +*.bak +.gitattributes +.last_checked +.gitconfig +*.bak +*.log +*~ +~* +_tmp* +tmp* +tags + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv +venv/ +ENV/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +.vscode +*.swp + +# osx generated files +.DS_Store +.DS_Store? +.Trashes +ehthumbs.db +Thumbs.db +.idea + +# pytest +.pytest_cache + +# tools/trust-doc-nbs +docs_src/.last_checked + +# symlinks to fastai +docs_src/fastai +tools/fastai + +# link checker +checklink/cookies.txt + +# .gitconfig is now autogenerated +.gitconfig + +# wandb files +nbs/wandb/ +examples/notebooks/wandb/ +wandb/ + +# uv +uv.lock + +# AI agent generated artifacts +/.agents/skills +/.claude/skills \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/.pre-commit-config.yaml b/tasks/tasksmith-b3c12843c3fb/tests/source/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..017eb89f8c7d5e8cc6763e942af625dffeb37fce --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/.pre-commit-config.yaml @@ -0,0 +1,19 @@ +repos: + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.13.3 + hooks: + - id: ruff-check + types_or: [ python, pyi ] + args: [ --fix ] + - id: ruff-format + types_or: [ python, pyi ] + + - repo: local + hooks: + - id: doc-builder-style + name: Check style with doc-builder + language: python + entry: doc-builder style trl tests docs/source --max_len 119 + additional_dependencies: ["git+https://github.com/huggingface/doc-builder@2430c1ec91d04667414e2fa31ecfc36c153ea391", ruff] # See GH-5633 + pass_filenames: false + types_or: [python, markdown, rst] diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/AGENTS.md b/tasks/tasksmith-b3c12843c3fb/tests/source/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..347a556b5bc6d8afa59ecb114ba705331c7295c3 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/AGENTS.md @@ -0,0 +1,97 @@ +# AGENTS.md + +## Repository-specific guidance + +### Main code vs experimental code + +The repository is separated into **main code** and **experimental code**. + +* **Main code** should remain stable, consistent, and well-tested. +* **Experimental code** may be less stable and may contain inconsistent patterns or limited testing. + +Small non-invasive improvements that make experimental code more consistent with the main codebase are encouraged, but avoid large refactors. + +### Paper implementations + +If a PR implements a method, algorithm, or training approach from a research paper, it must also add a corresponding subsection to `paper_index.md`. + +When reviewing such PRs, ensure that `paper_index.md` was updated. + +### Code duplication and consistency + +Trainers in this repository are **self-contained by design**. Shared logic (generation, reward computation, metric logging, weight syncing, etc.) is deliberately duplicated across trainers rather than abstracted into a shared base class. + +This is intentional: each trainer must be readable, modifiable, and evolvable in isolation. The base class (`_BaseTrainer`) provides only minimal utilities (model card generation). Everything else — vLLM generation paths, `_get_per_token_logps_and_entropies`, `_calculate_rewards`, `_prepare_inputs`, metric logging — is copied in full. + +**The tradeoff**: duplication is accepted, but **consistency is mandatory**. When the same logic appears in multiple trainers, the duplicated blocks must stay aligned: + +- Same variable names (`self._last_loaded_step`, `self._metrics[mode]`, …) +- Same control flow structure (if/elif/else branches in the same order) +- Same comments (word-for-word when the logic is identical) +- Divergences only where the trainer's semantics require it (e.g., GRPO extracts logprobs from vLLM, RLOO discards them) + +**Consistency over correctness**: this is a strong requirement. When duplicating code, reproduce it exactly — even if you believe the original has a bug. Do not silently fix the issue in your copy. Instead, keep your copy consistent with the source and report the problem so it can be fixed across all trainers in a dedicated PR. A correct-but-inconsistent codebase is harder to maintain than a consistently-wrong one that can be fixed in a single sweep. + +**When modifying duplicated code**: if you change a pattern that exists in multiple trainers (e.g., the vLLM generation path in `_generate_single_turn`), apply the same change to all other trainers. A fix in GRPO often implies the same fix in RLOO, and vice versa. Not propagating a change is a bug. + +**When reviewing**: if a PR touches duplicated logic, verify that all copies are updated consistently. A common mistake is fixing one trainer and forgetting the others. + +### Simplicity + +This codebase values **leanness and simplicity above all**. Prefer straightforward, inline code over abstractions, helpers, or utilities — even at the cost of some robustness or generality. + +Concretely: + +- Do not add layers of indirection (registries, factory patterns, plugin systems). A contributor should be able to read a trainer top to bottom and understand the full flow. +- Prefer a simple implementation that covers 90% of cases over a complex one that covers 100%. A function that handles the common path in 20 lines is better than a catch-all that handles every edge case in 80. +- Do not add defensive code, fallback paths, or configuration options "just in case". Only handle cases that actually exist today. +- Avoid `hasattr` and `getattr`. Their use is almost always a symptom of overly defensive programming or a disguised version check (e.g., "this attribute was added in version X"). Instead, either drop the conditional entirely or express the version check explicitly with a version comparison. There is nearly always a cleaner alternative. +- When in doubt, prefer less code. Every new function, parameter, or branch is maintenance burden. The best abstraction is often no abstraction. + +## Documentation + +### Docstrings + +Docstrings must follow the repository format below. Do **not** convert docstrings to other styles (Google, NumPy, etc.). + +Rules: + +* Types appear in backticks inside parentheses: (`str`) +* Optional parameters are marked with `*optional*` +* Defaults are written as: `defaults to ` +* When the default is `None`, prefer ```(`str`, *optional*)``` instead of ```(`str` or `None`, *optional*, defaults to `None`)``` +* Union types use `or`: `str` or `None` +* References to classes use the format: [`~transformers.PreTrainedModel`] +* Class docstrings may group parameters using headers such as: `> Parameters for X:` + +Example: + +````python +def method(self, param1: str, param2: int = 1, param3: float | None = None): + """ + Brief one-line description of what this does. + + Args: + param1 (`str`): + Description of required param. + param2 (`int`, *optional*, defaults to `1`): + Description of optional param with default. + param3 (`float`, *optional*): + Description of optional param without explicit default. + + Returns: + `dict` with keys: + - `key1` (`list[int]`): + Description of this key. + + Examples: + + ```python + >>> my_func("hello") + ``` + """ +```` + +### Links to papers + +When linking to papers, use `https://huggingface.co/papers/` instead of `https://arxiv.org/abs/` (same ID suffix system). diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/CITATION.cff b/tasks/tasksmith-b3c12843c3fb/tests/source/CITATION.cff new file mode 100644 index 0000000000000000000000000000000000000000..c1a44ae0d7d8b1b5d58d16aa020e5e5cc9efe363 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/CITATION.cff @@ -0,0 +1,41 @@ +cff-version: 1.2.0 +title: 'TRL: Transformers Reinforcement Learning' +message: >- + If you use this software, please cite it using the + metadata from this file. +type: software +authors: + - given-names: Leandro + family-names: von Werra + - given-names: Younes + family-names: Belkada + - given-names: Lewis + family-names: Tunstall + - given-names: Edward + family-names: Beeching + - given-names: Tristan + family-names: Thrush + - given-names: Nathan + family-names: Lambert + - given-names: Shengyi + family-names: Huang + - given-names: Kashif + family-names: Rasul + - given-names: Quentin + family-names: Gallouédec +repository-code: 'https://github.com/huggingface/trl' +abstract: >- + TRL (Transformers Reinforcement Learning) is an + open-source toolkit for aligning transformer models via + post-training. It provides practical, scalable + implementations of SFT, reward modeling, DPO, and GRPO + within the Hugging Face ecosystem. +keywords: + - transformers + - reinforcement learning + - preference optimization + - language model alignment + - post-training +license: Apache-2.0 +version: '1.7' +date-released: '2020-03-27' diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/CLAUDE.md b/tasks/tasksmith-b3c12843c3fb/tests/source/CLAUDE.md new file mode 100644 index 0000000000000000000000000000000000000000..347a556b5bc6d8afa59ecb114ba705331c7295c3 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/CLAUDE.md @@ -0,0 +1,97 @@ +# AGENTS.md + +## Repository-specific guidance + +### Main code vs experimental code + +The repository is separated into **main code** and **experimental code**. + +* **Main code** should remain stable, consistent, and well-tested. +* **Experimental code** may be less stable and may contain inconsistent patterns or limited testing. + +Small non-invasive improvements that make experimental code more consistent with the main codebase are encouraged, but avoid large refactors. + +### Paper implementations + +If a PR implements a method, algorithm, or training approach from a research paper, it must also add a corresponding subsection to `paper_index.md`. + +When reviewing such PRs, ensure that `paper_index.md` was updated. + +### Code duplication and consistency + +Trainers in this repository are **self-contained by design**. Shared logic (generation, reward computation, metric logging, weight syncing, etc.) is deliberately duplicated across trainers rather than abstracted into a shared base class. + +This is intentional: each trainer must be readable, modifiable, and evolvable in isolation. The base class (`_BaseTrainer`) provides only minimal utilities (model card generation). Everything else — vLLM generation paths, `_get_per_token_logps_and_entropies`, `_calculate_rewards`, `_prepare_inputs`, metric logging — is copied in full. + +**The tradeoff**: duplication is accepted, but **consistency is mandatory**. When the same logic appears in multiple trainers, the duplicated blocks must stay aligned: + +- Same variable names (`self._last_loaded_step`, `self._metrics[mode]`, …) +- Same control flow structure (if/elif/else branches in the same order) +- Same comments (word-for-word when the logic is identical) +- Divergences only where the trainer's semantics require it (e.g., GRPO extracts logprobs from vLLM, RLOO discards them) + +**Consistency over correctness**: this is a strong requirement. When duplicating code, reproduce it exactly — even if you believe the original has a bug. Do not silently fix the issue in your copy. Instead, keep your copy consistent with the source and report the problem so it can be fixed across all trainers in a dedicated PR. A correct-but-inconsistent codebase is harder to maintain than a consistently-wrong one that can be fixed in a single sweep. + +**When modifying duplicated code**: if you change a pattern that exists in multiple trainers (e.g., the vLLM generation path in `_generate_single_turn`), apply the same change to all other trainers. A fix in GRPO often implies the same fix in RLOO, and vice versa. Not propagating a change is a bug. + +**When reviewing**: if a PR touches duplicated logic, verify that all copies are updated consistently. A common mistake is fixing one trainer and forgetting the others. + +### Simplicity + +This codebase values **leanness and simplicity above all**. Prefer straightforward, inline code over abstractions, helpers, or utilities — even at the cost of some robustness or generality. + +Concretely: + +- Do not add layers of indirection (registries, factory patterns, plugin systems). A contributor should be able to read a trainer top to bottom and understand the full flow. +- Prefer a simple implementation that covers 90% of cases over a complex one that covers 100%. A function that handles the common path in 20 lines is better than a catch-all that handles every edge case in 80. +- Do not add defensive code, fallback paths, or configuration options "just in case". Only handle cases that actually exist today. +- Avoid `hasattr` and `getattr`. Their use is almost always a symptom of overly defensive programming or a disguised version check (e.g., "this attribute was added in version X"). Instead, either drop the conditional entirely or express the version check explicitly with a version comparison. There is nearly always a cleaner alternative. +- When in doubt, prefer less code. Every new function, parameter, or branch is maintenance burden. The best abstraction is often no abstraction. + +## Documentation + +### Docstrings + +Docstrings must follow the repository format below. Do **not** convert docstrings to other styles (Google, NumPy, etc.). + +Rules: + +* Types appear in backticks inside parentheses: (`str`) +* Optional parameters are marked with `*optional*` +* Defaults are written as: `defaults to ` +* When the default is `None`, prefer ```(`str`, *optional*)``` instead of ```(`str` or `None`, *optional*, defaults to `None`)``` +* Union types use `or`: `str` or `None` +* References to classes use the format: [`~transformers.PreTrainedModel`] +* Class docstrings may group parameters using headers such as: `> Parameters for X:` + +Example: + +````python +def method(self, param1: str, param2: int = 1, param3: float | None = None): + """ + Brief one-line description of what this does. + + Args: + param1 (`str`): + Description of required param. + param2 (`int`, *optional*, defaults to `1`): + Description of optional param with default. + param3 (`float`, *optional*): + Description of optional param without explicit default. + + Returns: + `dict` with keys: + - `key1` (`list[int]`): + Description of this key. + + Examples: + + ```python + >>> my_func("hello") + ``` + """ +```` + +### Links to papers + +When linking to papers, use `https://huggingface.co/papers/` instead of `https://arxiv.org/abs/` (same ID suffix system). diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/CODE_OF_CONDUCT.md b/tasks/tasksmith-b3c12843c3fb/tests/source/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..ef09fa1375a81440bf0733b659045453a5476c43 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/CODE_OF_CONDUCT.md @@ -0,0 +1,133 @@ + +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +feedback@huggingface.co. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/CONTRIBUTING.md b/tasks/tasksmith-b3c12843c3fb/tests/source/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..3ec168688b208b177bbfe1b0fa41228ac323b621 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/CONTRIBUTING.md @@ -0,0 +1,430 @@ +# How to contribute to TRL? + +Everyone is welcome to contribute, and we value everybody's contribution. Code contributions are not the only way to help the community. Answering questions, helping others, and improving the documentation are also immensely valuable. + +It also helps us if you spread the word! Reference the library in blog posts about the awesome projects it made possible, shout out on Twitter every time it has helped you, or simply ⭐️ the repository to say thank you. + +However you choose to contribute, please be mindful and respect our [code of conduct](https://github.com/huggingface/trl/blob/main/CODE_OF_CONDUCT.md). + +**This guide was heavily inspired by the awesome [scikit-learn guide to contributing](https://github.com/scikit-learn/scikit-learn/blob/main/CONTRIBUTING.md).** + +## AI usage policy + +We encourage using AI tools to help with contributions — they can be a great way to write better code, catch issues early, and navigate the codebase. + +That said, **we will not review fully AI-generated PRs from first-time contributors.** Our review resources are limited, and reviewing agent-generated code is especially costly when the contributor cannot engage meaningfully in the discussion or vouch for the correctness of the changes. We want to make sure that every PR we spend time on reflects a genuine understanding of what is being proposed. + +## Ways to contribute + +There are several ways you can contribute to TRL: + +* Fix outstanding issues with the existing code. +* Submit issues related to bugs or desired new features. +* Implement trainers for new post-training algorithms. +* Contribute to the examples or the documentation. + +If you don't know where to start, there is a special [Good First Issue](https://github.com/huggingface/trl/labels/%F0%9F%91%B6%20good%20first%20issue) listing. It will give you a list of open issues that are beginner-friendly and help you start contributing to open-source. The best way to do that is to open a Pull Request and link it to the issue that you'd like to work on. We try to give priority to opened PRs as we can easily track the progress of the fix, and if the contributor does not have time anymore, someone else can take the PR over. + +For something slightly more challenging, you can also take a look at the [Good Second Issue](https://github.com/huggingface/trl/labels/%F0%9F%A7%92%20good%20second%20issue) list. In general though, if you feel like you know what you're doing, go for it and we'll help you get there! 🚀 + +> All contributions are equally valuable to the community. 🥰 + +Before you start contributing make sure you have installed all the dev tools: + +```bash +pip install -e .[dev] +``` + +## Fixing outstanding issues + +If you notice an issue with the existing code and have a fix in mind, feel free to [start contributing](#submitting-a-pull-request-pr) and open a Pull Request! + +## Submitting a bug-related issue or feature request + +Do your best to follow these guidelines when submitting a bug-related issue or a feature request. It will make it easier for us to come back to you quickly and with good feedback. + +### Did you find a bug? + +The TRL library is robust and reliable thanks to users who report the problems they encounter. + +Before you report an issue, we would really appreciate it if you could **make sure the bug was not already reported** (use the search bar on GitHub under Issues). Your issue should also be related to bugs in the library itself, and not your code. + +Once you've confirmed the bug hasn't already been reported, please include the following information in your issue so we can quickly resolve it: + +* Your **OS type and version**, **Python**, **PyTorch**, **TRL** and **Transformers** versions. +* A short, self-contained, code snippet that allows us to reproduce the bug in less than 30s. +* The *full* traceback if an exception is raised. +* Attach any other additional information, like screenshots, you think may help. + +To get the OS and software versions automatically, run the following command: + +```bash +trl env +``` + +### Do you want a new feature? + +If there is a new feature you'd like to see in TRL, please open an issue and describe: + +1. What is the *motivation* behind this feature? Is it related to a problem or frustration with the library? Is it a feature related to something you need for a project? Is it something you worked on and think it could benefit the community? + + Whatever it is, we'd love to hear about it! + +2. Describe your requested feature in as much detail as possible. The more you can tell us about it, the better we'll be able to help you. +3. Provide a *code snippet* that demonstrates the feature's usage. +4. If the feature is related to a paper, please include a link. + +If your issue is well written we're already 80% of the way there by the time you create it. + +## Do you want to implement a new trainer? + +New post-training methods are published frequently and those that satisfy the following criteria are good candidates to be integrated into TRL: + +* **Simplicity:** Does the new method achieve similar performance as prior methods, but with less complexity? A good example is Direct Preference Optimization (DPO) [[Rafailov et al, 2023]](https://huggingface.co/papers/2305.18290), which provided a simpler and compelling alternative to RLHF methods. +* **Efficiency:** Does the new method provide a significant improvement in training efficiency? A good example is Odds Ratio Preference Optimization (ORPO) [[Hong et al, 2023]](https://huggingface.co/papers/2403.07691), which utilizes a similar objective as DPO but requires half the GPU VRAM. + +Methods that only provide incremental improvements at the expense of added complexity or compute costs are unlikely to be included in TRL. + +If you want to implement a trainer for a new post-training method, first open an issue and provide the following information: + +* A short description of the method and a link to the paper. +* Link to the implementation if it is open-sourced. +* Link to model weights trained with the method if they are available. + +Based on the community and maintainer feedback, the next step will be to implement the trainer and config classes. See the following examples for inspiration: + +* Paired preference optimisation: [`dpo_trainer.py`](./trl/trainer/dpo_trainer.py) and [`dpo_config.py`](./trl/trainer/dpo_config.py) +* RL-based optimisation: [`rloo_trainer.py`](./trl/trainer/rloo_trainer.py) and [`rloo_config.py`](./trl/trainer/rloo_config.py) +* Online optimisation: [`online_dpo_trainer.py`](./trl/experimental/online_dpo/online_dpo_trainer.py) and [`online_dpo_config.py`](./trl/experimental/online_dpo/online_dpo_config.py) + +## Do you want to add documentation? + +We're always looking for improvements to the documentation that make it more clear and accurate. Please let us know how the documentation can be improved, such as typos, dead links, and any missing, unclear, or inaccurate content... We'll be happy to make the changes or help you contribute if you're interested! + +## Submitting a pull request (PR) + +> [!IMPORTANT] +> **First-time contributors: you MUST fill out the [PR template](https://github.com/huggingface/trl/blob/main/.github/PULL_REQUEST_TEMPLATE.md) when opening a pull request.** PRs that do not follow the template (missing description, unchecked checklist, no linked issue) will be closed without review. + +Before writing code, we strongly advise you to search through the existing PRs or issues to make sure that nobody is already working on the same thing. If you are unsure, it is always a good idea to open an issue to get some feedback. + +You will need basic `git` proficiency to be able to contribute to TRL. `git` is not the easiest tool to use but it has the greatest manual. Type `git --help` in a shell and enjoy. If you prefer books, [Pro Git](https://git-scm.com/book/en/v2) is a very good reference. + +Follow these steps to start contributing: + +1. Fork the [repository](https://github.com/huggingface/trl) by clicking on the 'Fork' button on the repository's page. This creates a copy of the code under your GitHub user account. + +2. Clone your fork to your local disk, and add the base repository as a remote. The following command assumes you have your public SSH key uploaded to GitHub. See the following guide for more [information](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository). + + ```bash + git clone git@github.com:/trl.git + cd trl + git remote add upstream https://github.com/huggingface/trl.git + ``` + +3. Create a new branch to hold your development changes, and do this for every new PR you work on. + + Start by synchronizing your `main` branch with the `upstream/main` branch (more details in the [GitHub Docs](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/syncing-a-fork)): + + ```bash + git checkout main + git fetch upstream + git merge upstream/main + ``` + + Once your `main` branch is synchronized, create a new branch from it: + + ```bash + git checkout -b a-descriptive-name-for-my-changes + ``` + + **Do not** work on the `main` branch. + +4. Set up a development environment by running the following command in a conda or a virtual environment you've created for working on this library: + + ```bash + pip install -e .[dev] + ``` + + (If TRL was already installed in the virtual environment, remove it with `pip uninstall trl` before reinstalling it.) + + Alternatively, if you are using [Visual Studio Code](https://code.visualstudio.com/Download), the fastest way to get set up is by using the provided Dev Container. Check [the documentation on how to get started with dev containers](https://code.visualstudio.com/docs/remote/containers). + +5. Develop the features on your branch. + + As you work on the features, you should make sure that the test suite passes. You should run the tests impacted by your changes like this (see below an explanation regarding the environment variable): + + ```bash + pytest tests/.py + ``` + + > For the following commands leveraging the `make` utility. + + You can also run the full suite with the following command. + + ```bash + make test + ``` + + TRL relies on `ruff` for maintaining consistent code formatting across its source files. Before submitting any PR, you should apply automatic style corrections and run code verification checks. + + We provide a `precommit` target in the `Makefile` that simplifies this process by running all required checks and optimizations on only the files modified by your PR. + + To apply these checks and corrections in one step, use: + + ```bash + make precommit + ``` + + This command runs the following: + + * Executes `pre-commit` hooks to automatically fix style issues with `ruff` and other tools. + * Runs additional scripts such as adding copyright information. + + If you prefer to apply the style corrections separately or review them individually, the `pre-commit` hook will handle the formatting for the files in question. + + Once you're happy with your changes, add changed files using `git add` and make a commit with `git commit` to record your changes locally: + + ```bash + git add modified_file.py + git commit + ``` + + Please write [good commit messages](https://chris.beams.io/posts/git-commit/). + + It is a good idea to sync your copy of the code with the original + repository regularly. This way you can quickly account for changes: + + ```bash + git fetch upstream + git rebase upstream/main + ``` + + Push the changes to your account using: + + ```bash + git push -u origin a-descriptive-name-for-my-changes + ``` + +6. Once you are satisfied (**and the checklist below is happy too**), go to the webpage of your fork on GitHub. Click on 'Pull request' to send your changes to the project maintainers for review. + +7. It's ok if maintainers ask you for changes. It happens to core contributors too! To ensure everyone can review your changes in the pull request, work on your local branch and push the updates to your fork. They will automatically appear in the pull request. + +### Checklist + +1. The title of your pull request should be a summary of its contribution; +2. If your pull request addresses an issue, please mention the issue number in the pull request description to make sure they are linked (and people consulting the issue know you are working on it); +3. To indicate a work in progress please prefix the title with `[WIP]`, or mark the PR as a draft PR. These are useful to avoid duplicated work, and to differentiate it from PRs ready to be merged; +4. Make sure existing tests pass; +5. Add high-coverage tests. No quality testing = no merge. + +### Tests + +An extensive test suite is included to test the library behavior and several examples. Library tests can be found in +the [tests folder](https://github.com/huggingface/trl/tree/main/tests). + +We use `pytest` to run the tests. From the root of the +repository here's how to run tests with `pytest` for the library: + +```bash +python -m pytest -sv ./tests +``` + +That's how `make test` is implemented (without the `pip install` line)! + +You can specify a smaller set of tests to test only the feature +you're working on. + +### Default values guidelines + +1. **Use defaults when appropriate**: + + Provide default values unless the parameter's value varies significantly by use case. For example, datasets or models should not have defaults, but parameters like `learning_rate` should. + +2. **Prioritize proven defaults**: + + Default values should align with those recommended in the original paper or method. Alternatives require strong evidence of superior performance in most cases. + +3. **Ensure safety and predictability**: + + Defaults must be safe, expected and reliable. Avoid settings that could lead to surprising outcomes, such as excessive memory usage or poor performance in edge cases. + +4. **Balance consistency and flexibility**: + + Aim for consistent defaults across similar functions or methods. However, consistency should not be preferred to point 2 or 3. + +5. **Opt-in for new features**: + + Do not enable new features or improvements (e.g., novel loss functions) by default. Users should explicitly opt-in to use these. + +### Writing documentation + +High-quality documentation is crucial for maintaining a project that is easy to use, understand, and extend. When adding new features, ensure they are thoroughly documented to maintain consistency and clarity throughout the project. + +To illustrate what good documentation looks like, here’s an example of a well-documented function: + +````python +def replicate_str(string: str, n: int, sep: str = " ") -> str: + r""" + Replicate a string `n` times with a separator. + + Args: + string (`str`): + String to replicate. + n (`int`): + Number of times to replicate the string. + sep (`str`, *optional*, defaults to `" "`): + Separator to use between each replication. + + Returns: + `str`: The replicated string. + + Examples: + ```python + >>> replicate_str("hello", 3) + "hello hello hello" + >>> replicate_str("hello", 3, sep=", ") + "hello, hello, hello" + ``` + """ + return sep.join([string] * n) +```` + +* **Line Wrapping:** Applied a consistent line wrap at column 120 to improve readability. +* **Definite Articles:** Removed definite articles where possible to streamline language. (Eg: Changed "The string to replicate" to "String to replicate") +* **Type Annotations:** + * Always include type definitions, indicating if a parameter is optional and specifying the default value. + +* **String Defaults:** + * Ensured that default string values are wrapped in double quotes: + + ```txt + defaults to `"foo"` + ``` + +* **Dictionary Typing:** + * Replaced generic `dict` type hints with more explicit `dict[str, Any]` to clarify expected key-value pairs. +* **Default Value Formatting:** + * Consistently surrounded default values with backticks for improved formatting: + + ```txt + defaults to `4` + ``` + +* **Sub-sectioning:** When the number of arguments is large, consider breaking them into sub-sections for better readability. + + ```python + def calculate_statistics(data: list[float], precision: int = 2, include_variance: bool = False) -> dict[str, float]: + r""" + Calculates basic statistics for a given dataset. + + Args: + > Data inputs + + data (`list[float]`): + A list of numerical values to analyze. + + > Configuration parameters + + precision (`int`, *optional*, defaults to `2`): + Number of decimal places to round the results. + include_variance (`bool`, *optional*, defaults to `False`): + Whether to include the variance of the dataset in the results. + + Returns: + `dict[str, float]`: + A dictionary containing calculated statistics such as mean, median, and optionally variance. + """ + ... + ``` + +### Deprecation and backward compatibility + +Our approach to deprecation and backward compatibility is flexible and based on the feature’s usage and impact. Each deprecation is carefully evaluated, aiming to balance innovation with user needs. + +When a feature or component is marked for deprecation, its use will emit a warning message. This warning will include: + +* **Transition Guidance**: Instructions on how to migrate to the alternative solution or replacement. +* **Removal Version**: The target version when the feature will be removed, providing users with a clear timeframe to transition. + +Example: + + ```python + warnings.warn( + "The `Trainer.foo` method is deprecated and will be removed in version 0.14.0. " + "Please use the `Trainer.bar` class instead.", + FutureWarning, + stacklevel=2, + ) + ``` + +The deprecation and removal schedule is based on each feature's usage and impact, with examples at two extremes: + +* **Experimental or Low-Use Features**: For a feature that is experimental or has limited usage, backward compatibility may not be maintained between releases. Users should therefore anticipate potential breaking changes from one version to the next. + +* **Widely-Used Components**: For a feature with high usage, we aim for a more gradual transition period of approximately **5 months**, generally scheduling deprecation around **5 minor releases** after the initial warning. + +These examples represent the two ends of a continuum. The specific timeline for each feature will be determined individually, balancing innovation with user stability needs. + +### Working with warnings + +Warnings play a critical role in guiding users toward resolving potential issues, but they should be used thoughtfully to avoid unnecessary noise. Unlike logging, which provides informational context or operational details, warnings signal conditions that require attention and action. Overusing warnings can dilute their importance, leading users to ignore them entirely. + +#### Definitions + +* **Correct**: An operation is correct if it is valid, follows the intended approach, and aligns with the current best practices or guidelines within the codebase. This is the recommended or intended way to perform the operation. +* **Supported**: An operation is supported if it is technically valid and works within the current codebase, but it may not be the most efficient, optimal, or recommended way to perform the task. This includes deprecated features or legacy approaches that still work but may be phased out in the future. + +#### Choosing the right message + +* **Correct → No warning**: + If the operation is fully valid and expected, no message should be issued. The system is working as intended, so no warning is necessary. + +* **Correct but deserves attention → No warning, possibly a log message**: + When an operation is correct but uncommon or requires special attention, providing an informational message can be helpful. This keeps users informed without implying any issue. If available, use the logger to output this message. Example: + + ```python + logger.info("This is an informational message about a rare but correct operation.") + ``` + +* **Correct but very likely a mistake → Warning with option to disable**: + In rare cases, you may want to issue a warning for a correct operation that’s very likely a mistake. In such cases, you must provide an option to suppress the warning. This can be done with a flag in the function. Example: + + ```python + def my_function(foo, bar, _warn=True): + if foo == bar: + if _warn: + logger.warning("foo and bar are the same, this is likely a mistake. Ignore this warning by setting `_warn=False`.") + # Do something + ``` + +* **Supported but not correct → Warning**: + If the operation is technically supported but is deprecated, suboptimal, or could cause future issues (e.g., conflicting arguments), a warning should be raised. This message should be actionable, meaning it must explain how to resolve the issue. Example: + + ```python + def my_function(foo, bar): + if foo and bar: + logger.warning("Both `foo` and `bar` were provided, but only one is allowed. Ignoring `foo`. Please pass only one of these arguments.") + # Do something + ``` + +* **Not supported → Exception**: + If the operation is invalid or unsupported, raise an exception. This indicates that the operation cannot be performed and requires immediate attention. Example: + + ```python + def my_function(foo, bar): + if foo and bar: + raise ValueError("Both `foo` and `bar` were provided, but only one is allowed. Please pass only one of these arguments.") + ``` + +By following this classification, you ensure that warnings, information, and exceptions are used appropriately, providing clear guidance to the user without cluttering the system with unnecessary messages. + +## Coding with AI agents + +This repository keeps AI-agent configuration in `.ai/` and exposes local agent files via symlinks. + +Skills can be exposed to agents by running `make codex` or `make claude` + +`AGENTS.md`, `CLAUDE.md`, and `.cursor/BUGBOT.md` all point to `.ai/AGENTS.md`. + +Cursor reads `AGENTS.md` and Bugbot reads `.cursor/BUGBOT.md`. Cursor reads skills from Claude or Codex paths, so setting up the repository for Claude or Codex will work for Cursor. diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/LICENSE b/tasks/tasksmith-b3c12843c3fb/tests/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f577b7741dfb5c6af119f250971549dd7750acb9 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2020-2026 The HuggingFace Team + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/MANIFEST.in b/tasks/tasksmith-b3c12843c3fb/tests/source/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..e843c590270bb5f441cef5f596c7cb3e32ebd26b --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/MANIFEST.in @@ -0,0 +1,10 @@ +include LICENSE +include CONTRIBUTING.md +include README.md +include trl/accelerate_configs/*.yaml +include trl/templates/*.md +include trl/chat_templates/*.jinja +include trl/chat_templates/*.md +include trl/skills/**/*.md +recursive-exclude * __pycache__ +prune tests diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/MIGRATION.md b/tasks/tasksmith-b3c12843c3fb/tests/source/MIGRATION.md new file mode 100644 index 0000000000000000000000000000000000000000..ba2c8e2338a507d7e2b1eb8cd33b79e6e9015b58 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/MIGRATION.md @@ -0,0 +1,40 @@ +# Migrating from TRL v0 to v1 + +This guide covers the breaking changes introduced in TRL v1 and how to update your code. Most structural changes (trainers moved to experimental, removed model classes, etc.) already shipped in v0.29 — if you're already on v0.29, this migration is minimal. + +## Changed defaults + +| Config | Parameter | v0 default | v1 default | Action needed | +| --- | --- | --- | --- | --- | +| `GRPOConfig` | `vllm_mode` | `"server"` | `"colocate"` | If you use `use_vllm=True` without specifying `vllm_mode`, vLLM will now run in the same process instead of connecting to a separate server. Set `vllm_mode="server"` explicitly if you rely on server mode. | +| `RLOOConfig` | `vllm_mode` | `"server"` | `"colocate"` | Same as above. | + +## Renamed options + +| Config | Parameter | v0 value | v1 value | Action needed | +| --- | --- | --- | --- | --- | +| `SFTConfig` | `packing` | `"bfd-requeue"` | `"bfd_split"` | Replace `packing="bfd-requeue"` with `packing="bfd_split"`. The old value will still be accepted for a few versions but will be removed in a future release. | + +## Removed automatic `None` stripping from trainer preprocessing + +TRL trainers (SFT, DPO, Reward) no longer automatically strip `None` values from dataset examples during preprocessing. Previously, each trainer applied `remove_none_values` via `dataset.with_transform` to work around tabular backends (Arrow/Parquet) inserting `None` for missing keys in nested structures. + +This affects datasets that contain `None` values because they were: + +- Created before `datasets` v4.7.0, which introduced the Json dtype that preserves nested structures without inserting `None`. +- Created with `datasets` v4.7.0 or later, but saved without using the Json feature. + +**Action needed:** If your dataset falls into one of the above categories and contains `None` values in nested columns, apply the fix manually before training: + +```python +from trl.trainer.utils import remove_none_values + +dataset = dataset.with_transform(remove_none_values) +trainer = SFTTrainer(..., train_dataset=dataset) +``` + +Datasets created or re-saved with `datasets` v4.7.0+ using the Json dtype are unaffected. + +## Migrating from an earlier version + +Depending on which version you're migrating from, refer to the [release notes](https://github.com/huggingface/trl/releases) for v0.29 and earlier for version-specific changes. diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/Makefile b/tasks/tasksmith-b3c12843c3fb/tests/source/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..38161efa3322210441f558d6aaf39b6c45002005 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/Makefile @@ -0,0 +1,31 @@ +.PHONY: test precommit common_tests slow_tests tests_gpu test_experimental codex claude clean-ai + +check_dirs := examples tests trl + +ACCELERATE_CONFIG_PATH = `pwd`/examples/accelerate_configs + +test: + pytest -n auto -m "not slow and not low_priority" -s -v --reruns 5 --reruns-delay 1 --only-rerun '(OSError|Timeout|HTTPError.*502|HTTPError.*504|OutOfMemoryError)' tests + +precommit: + python scripts/add_copyrights.py + pre-commit run --all-files + +slow_tests: + pytest -m "slow" tests/ $(if $(IS_GITHUB_CI),--report-log "slow_tests.log",) + +test_experimental: + pytest -n auto -s -v tests/experimental + +codex: + mkdir -p .agents + rm -rf .agents/skills + ln -snf ../.ai/skills .agents/skills + +claude: + mkdir -p .claude + rm -rf .claude/skills + ln -snf ../.ai/skills .claude/skills + +clean-ai: + rm -rf .agents/skills .claude/skills \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/README.md b/tasks/tasksmith-b3c12843c3fb/tests/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..46c99c45c437af7f12c0d9d3a16e89307b9941fc --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/README.md @@ -0,0 +1,205 @@ +# TRL - Transformers Reinforcement Learning + +
+ + + TRL Banner + +
+ +

+ +

+

A comprehensive library to post-train foundation models

+

+ +

+ License + Documentation + GitHub release + Hugging Face Hub +

+ +## 🎉 What's New + +**TRL v1:** We released TRL v1 — a major milestone that marks a real shift in what TRL is. Read the [blog post](https://huggingface.co/blog/trl-v1) to learn more. + +**🚢 Harbor:** We now support [Harbor](https://huggingface.co/docs/trl/harbor) — train agents against sandboxed task suites (instruction + sandbox image + in-sandbox verifier) via [`GRPOTrainer`](https://huggingface.co/docs/trl/grpo_trainer)'s `environment_factory`. + +## Overview + +TRL is a cutting-edge library designed for post-training foundation models using advanced techniques like Supervised Fine-Tuning (SFT), Group Relative Policy Optimization (GRPO), and Direct Preference Optimization (DPO). Built on top of the [🤗 Transformers](https://github.com/huggingface/transformers) ecosystem, TRL supports a variety of model architectures and modalities, and can be scaled-up across various hardware setups. + +## Highlights + +- **Trainers**: Various fine-tuning methods are easily accessible via trainers like [`SFTTrainer`](https://huggingface.co/docs/trl/sft_trainer), [`GRPOTrainer`](https://huggingface.co/docs/trl/grpo_trainer), [`DPOTrainer`](https://huggingface.co/docs/trl/dpo_trainer), [`RewardTrainer`](https://huggingface.co/docs/trl/reward_trainer) and more. + +- **Efficient and scalable**: + - Leverages [🤗 Accelerate](https://github.com/huggingface/accelerate) to scale from single GPU to multi-node clusters using methods like [DDP](https://pytorch.org/tutorials/intermediate/ddp_tutorial.html) and [DeepSpeed](https://github.com/deepspeedai/DeepSpeed). + - Full integration with [🤗 PEFT](https://github.com/huggingface/peft) enables training on large models with modest hardware via quantization and LoRA/QLoRA. + - Integrates [🦥 Unsloth](https://github.com/unslothai/unsloth) for accelerating training using optimized kernels. + +- **Command Line Interface (CLI)**: A simple interface lets you fine-tune with models without needing to write code. + +## Installation + +### Python Package + +Install the library using `pip`: + +```bash +pip install trl +``` + +### From source + +If you want to use the latest features before an official release, you can install TRL from source: + +```bash +pip install git+https://github.com/huggingface/trl.git +``` + +### Repository + +If you want to use the examples you can clone the repository with the following command: + +```bash +git clone https://github.com/huggingface/trl.git +``` + +## Quick Start + +For more flexibility and control over training, TRL provides dedicated trainer classes to post-train language models or PEFT adapters on a custom dataset. Each trainer in TRL is a light wrapper around the 🤗 Transformers trainer and natively supports distributed training methods like DDP, DeepSpeed ZeRO, and FSDP. + +### `SFTTrainer` + +Here is a basic example of how to use the [`SFTTrainer`](https://huggingface.co/docs/trl/sft_trainer): + +```python +from trl import SFTTrainer +from datasets import load_dataset + +dataset = load_dataset("trl-lib/Capybara", split="train") + +trainer = SFTTrainer( + model="Qwen/Qwen2.5-0.5B", + train_dataset=dataset, +) +trainer.train() +``` + +### `GRPOTrainer` + +[`GRPOTrainer`](https://huggingface.co/docs/trl/grpo_trainer) implements the [Group Relative Policy Optimization (GRPO) algorithm](https://huggingface.co/papers/2402.03300) that is more memory-efficient than PPO and was used to train [Deepseek AI's R1](https://huggingface.co/deepseek-ai/DeepSeek-R1). + +```python +from datasets import load_dataset +from trl import GRPOTrainer +from trl.rewards import accuracy_reward + +dataset = load_dataset("trl-lib/DeepMath-103K", split="train") + +trainer = GRPOTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", + reward_funcs=accuracy_reward, + train_dataset=dataset, +) +trainer.train() +``` + +> [!NOTE] +> For reasoning models, use the `reasoning_accuracy_reward()` function for better results. + +### `DPOTrainer` + +[`DPOTrainer`](https://huggingface.co/docs/trl/dpo_trainer) implements the popular [Direct Preference Optimization (DPO) algorithm](https://huggingface.co/papers/2305.18290) that was used to post-train [Llama 3](https://huggingface.co/papers/2407.21783) and many other models. Here is a basic example of how to use the `DPOTrainer`: + +```python +from datasets import load_dataset +from trl import DPOTrainer + +dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") + +trainer = DPOTrainer( + model="Qwen/Qwen3-0.6B", + train_dataset=dataset, +) +trainer.train() +``` + +### `RewardTrainer` + +Here is a basic example of how to use the [`RewardTrainer`](https://huggingface.co/docs/trl/reward_trainer): + +```python +from trl import RewardTrainer +from datasets import load_dataset + +dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") + +trainer = RewardTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", + train_dataset=dataset, +) +trainer.train() +``` + +## Command Line Interface (CLI) + +You can use the TRL Command Line Interface (CLI) to quickly get started with post-training methods like Supervised Fine-Tuning (SFT) or Direct Preference Optimization (DPO): + +**SFT:** + +```bash +trl sft --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name trl-lib/Capybara \ + --output_dir Qwen2.5-0.5B-SFT +``` + +**DPO:** + +```bash +trl dpo --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ + --dataset_name argilla/Capybara-Preferences \ + --output_dir Qwen2.5-0.5B-DPO +``` + +Read more about CLI in the [relevant documentation section](https://huggingface.co/docs/trl/clis) or use `--help` for more details. + +## Development + +If you want to contribute to `trl` or customize it to your needs make sure to read the [contribution guide](https://github.com/huggingface/trl/blob/main/CONTRIBUTING.md) and make sure you make a dev install: + +```bash +git clone https://github.com/huggingface/trl.git +cd trl/ +pip install -e .[dev] +``` + +## Experimental + +A minimal incubation area is available under `trl.experimental` for unstable / fast-evolving features. Anything there may change or be removed in any release without notice. + +Example: + +```python +from trl.experimental.new_trainer import NewTrainer +``` + +Read more in the [Experimental docs](https://huggingface.co/docs/trl/experimental_overview). + +## Citation + +```bibtex +@software{vonwerra2020trl, + title = {{TRL: Transformers Reinforcement Learning}}, + author = {von Werra, Leandro and Belkada, Younes and Tunstall, Lewis and Beeching, Edward and Thrush, Tristan and Lambert, Nathan and Huang, Shengyi and Rasul, Kashif and Gallouédec, Quentin}, + license = {Apache-2.0}, + url = {https://github.com/huggingface/trl}, + year = {2020} +} +``` + +## License + +This repository's source code is available under the [Apache-2.0 License](LICENSE). diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/RELEASE.md b/tasks/tasksmith-b3c12843c3fb/tests/source/RELEASE.md new file mode 100644 index 0000000000000000000000000000000000000000..67087ad7ac8b1d2f7a5ea96a705944eda723fc03 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/RELEASE.md @@ -0,0 +1,167 @@ +# Making a release + +> [!NOTE] +> VERSION needs to be formatted following the `v{major}.{minor}.{patch}` convention. We need to follow this convention to be able to retrieve versioned scripts. + +## Major/Minor Release + +### 1. Ensure your local repository is up to date with the upstream repository + +```bash +git checkout main +git pull origin main +``` + +> [!WARNING] +> Do not merge other pull requests into `main` until the release is done. This is to ensure that the release is stable and does not include any untested changes. Announce internally (#trl-internal) to other maintainers that you are doing a release and that they must not merge PRs until the release is done. + +### 2. Create a release branch from main + +```bash +git checkout -b release-v{major}.{minor} +``` + +### 3. Change the version in the following files + +- `.github/workflows/tests_latest.yml`: + + ```diff + - with: { ref: v{major}.{minor-1}-release } + + with: { ref: v{major}.{minor}-release } + ``` + +- `CITATION.cff` + + ```diff + - version: '{major}.{minor-1}' + + version: '{major}.{minor}' + ``` + +- `VERSION` + + ```diff + - {major}.{minor}.0.dev0 + + {major}.{minor}.0 + ``` + +### 4. Commit and push these changes + +```shell +git add .github/workflows/tests_latest.yml CITATION.cff VERSION +git commit -m 'Release: {major}.{minor}' +git push origin release-v{major}.{minor} +``` + +### 5. Create a pull request + +from `release-v{major}.{minor}` to `main`, named `Release: v{major}.{minor}`, wait for tests to pass, and request a review. + +### 6. Once the pull request is approved, merge it into `main` + +It will automatically publish the new version of the package on PyPI. + +### 7. Add a tag in git to mark the release + +```shell +git checkout main +git pull origin main +git tag -a v{major}.{minor}.0 -m 'Adds tag v{major}.{minor}.0 for PyPI' +git push origin v{major}.{minor}.0 +``` + +### 8. Create a branch `v{major}.{minor}-release` for future patch releases + +```shell +git checkout -b v{major}.{minor}-release +git push origin v{major}.{minor}-release +``` + +This ensures that future patch releases (`v{major}.{minor}.1`, `v{major}.{minor}.2`, etc.) can be made separately from `main`. + +### 9. Create a GitHub Release + +1. Go to the repo’s [releases section](https://github.com/huggingface/trl/releases) on GitHub. +2. Click **Draft a new release**. +3. Select the `v{major}.{minor}.0` tag you just created in step 7. +4. Add a title (`v{major}.{minor}.0`) and a short description of what’s new. +5. Click **Publish Release**. + +### 10. Bump to dev version + +1. Create a branch `bump-dev-version-{major}.{minor+1}` from `main` and checkout to it. + + ```shell + git checkout -b bump-dev-version-{major}.{minor+1} + ``` + +2. Change the version in file `VERSION`: + + ```diff + - {major}.{minor}.0 + + {major}.{minor+1}.0.dev0 + ``` + +3. Commit and push these changes + + ```shell + git add VERSION + git commit -m '⬆️ Bump dev version' + git push origin bump-dev-version-{major}.{minor+1} + ``` + +4. Create a pull request from `bump-dev-version-{major}.{minor+1}` to `main`, named `⬆️ Bump dev version`, and request urgent review. + +5. Once the pull request is approved, merge it into `main`. + +6. The codebase is now ready for the next development cycle, inform the team in the #trl-internal channel. + +## Making a patch release + +### 1. Ensure your local repository is up to date with the upstream repository + +```bash +git checkout v{major}.{minor}-release +git pull origin main +``` + +### 2. Cherry-pick the changes you want to include in the patch release + +```bash +git cherry-pick +git cherry-pick +... +``` + +### 3. Change the version in the file `VERSION` + +```diff +- {major}.{minor}.{patch-1} ++ {major}.{minor}.{patch} +``` + +### 4. Commit and push these changes + +```shell +git add VERSION +git commit -m 'Release: {major}.{minor}.{patch}' +git push origin v{major}.{minor}-release +``` + +### 5. Wait for the CI to pass + +The CI will automatically publish the new version of the package on PyPI. + +### 6. Add a tag in git to mark the release + +```shell +git tag -a v{major}.{minor}.{patch} -m 'Adds tag v{major}.{minor}.{patch} for PyPI' +git push origin v{major}.{minor}.{patch} +``` + +#### 7. Create a GitHub Release + +1. Go to the repo’s [releases section](https://github.com/huggingface/trl/releases) on GitHub. +2. Click **Draft a new release**. +3. Select the `v{major}.{minor}.{patch}` tag you just created in step 7. +4. Add a title (`v{major}.{minor}.{patch}`) and a short description of what’s new. +5. Click **Publish Release**. diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/VERSION b/tasks/tasksmith-b3c12843c3fb/tests/source/VERSION new file mode 100644 index 0000000000000000000000000000000000000000..a7a1e80a7e90978c08982cf2ef7b71e7eb2c8721 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/VERSION @@ -0,0 +1 @@ +1.8.0.dev0 \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/assets/logo-dark.png b/tasks/tasksmith-b3c12843c3fb/tests/source/assets/logo-dark.png new file mode 100644 index 0000000000000000000000000000000000000000..48db11e330a0f85184676f188bf2ead71f977d06 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/assets/logo-dark.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ac72e1dc6b93dac4cdae7d10f36a8d274c10a29918d19b5887d764cd3972e1ba +size 30539 diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/assets/logo-light.png b/tasks/tasksmith-b3c12843c3fb/tests/source/assets/logo-light.png new file mode 100644 index 0000000000000000000000000000000000000000..520d8d1765456c213c47cb02fa2bfa70bd66abdf --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/assets/logo-light.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:902ecba8e7b1d2fb4621f3ca38ff0edb968de38f4061d8743b5a4965d3af1f33 +size 137446 diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docker/trl-dev/Dockerfile b/tasks/tasksmith-b3c12843c3fb/tests/source/docker/trl-dev/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9a756a8821d0c225dbdd012c76c9c6a540397df1 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docker/trl-dev/Dockerfile @@ -0,0 +1,5 @@ +FROM pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel +RUN apt-get update && apt-get install -y git && rm -rf /var/lib/apt/lists/* +RUN pip install --upgrade pip uv +RUN uv pip install --system --no-cache "git+https://github.com/huggingface/trl.git#egg=trl[liger,peft,vlm]" +RUN uv pip install --system kernels liger_kernel peft trackio \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docker/trl/Dockerfile b/tasks/tasksmith-b3c12843c3fb/tests/source/docker/trl/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8b6e2842a3859ab8a45e1cf9983a39d6f160988b --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docker/trl/Dockerfile @@ -0,0 +1,4 @@ +FROM pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel +RUN apt-get update && apt-get install -y git && rm -rf /var/lib/apt/lists/* +RUN pip install --upgrade pip uv +RUN uv pip install --system trl[liger,peft,vlm] kernels trackio \ No newline at end of file diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/_toctree.yml b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/_toctree.yml new file mode 100644 index 0000000000000000000000000000000000000000..9bd45b2437bfcf3539125a1d23e762cea934b19c --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/_toctree.yml @@ -0,0 +1,151 @@ +- sections: + - local: index + title: TRL + - local: installation + title: Installation + - local: quickstart + title: Quickstart + - local: usage_stats + title: Usage Stats Collection + title: Getting started +- sections: + - local: chat_templates + title: Chat Templates + - local: dataset_formats + title: Dataset Formats + - local: paper_index + title: Paper Index + title: Conceptual Guides +- sections: # Sorted alphabetically + - local: dpo_trainer + title: DPO + - local: grpo_trainer + title: GRPO + - local: reward_trainer + title: Reward + - local: rloo_trainer + title: RLOO + - local: sft_trainer + title: SFT + title: Trainers +- sections: + - local: clis + title: Command Line Interface (CLI) + - local: jobs_training + title: Training using Jobs + - local: customization + title: Customizing the Training + - local: reducing_memory_usage + title: Reducing Memory Usage + - local: speeding_up_training + title: Speeding Up Training + - local: distributing_training + title: Distributing Training + - local: use_model + title: Using Trained Models + title: How-to guides +- sections: + - local: deepspeed_integration + title: DeepSpeed + - local: harbor + title: Harbor + - local: kernels_hub + title: Kernels Hub + - local: liger_kernel_integration + title: Liger Kernel + - local: openenv + title: OpenEnv + - local: openreward + title: OpenReward + - local: peft_integration + title: PEFT + - local: ptt_integration + title: Post Training Toolkit + - local: rapidfire_integration + title: RapidFire AI + - local: trackio_integration + title: Trackio + - local: unsloth_integration + title: Unsloth + - local: vllm_integration + title: vLLM + title: Integrations +- sections: + - local: example_overview + title: Example Overview + - local: community_tutorials + title: Community Tutorials + - local: lora_without_regret + title: LoRA Without Regret + title: Examples +- sections: + - sections: + - local: chat_template_utils + title: Chat Template Utilities + - local: data_utils + title: Data Utilities + - local: script_utils + title: Script Utilities + title: Utilities + - local: callbacks + title: Callbacks + - local: rewards + title: Reward Functions + title: API +- sections: + - local: experimental_overview + title: Experimental Overview + - local: a2po_trainer # Sorted alphabetically + title: A2PO + - local: async_grpo_trainer + title: Asynchronous GRPO + - local: bema_for_reference_model + title: BEMA for Reference Model + - local: bco_trainer + title: BCO + - local: cpo_trainer + title: CPO + - local: distillation_trainer + title: Distillation + - local: gfpo + title: GFPO + - local: gkd_trainer + title: GKD + - local: gmpo + title: GMPO + - local: gold_trainer + title: GOLD + - local: grpo_with_replay_buffer + title: GRPO With Replay Buffer + - local: gspo_token + title: GSPO-token + - local: kto_trainer + title: KTO + - local: merge_model_callback + title: MergeModelCallback + - local: minillm_trainer + title: MiniLLM + - local: nash_md_trainer + title: Nash-MD + - local: online_dpo_trainer + title: Online DPO + - local: orpo_trainer + title: ORPO + - local: papo_trainer + title: PAPO + - local: ppo_trainer + title: PPO + - local: prm_trainer + title: PRM + - local: sdft_trainer + title: SDFT + - local: sdpo_trainer + title: SDPO + - local: ssd_trainer + title: SSD + - local: tpo_trainer + title: TPO + - local: xpo_trainer + title: XPO + title: Experimental + isExpanded: false diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/a2po_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/a2po_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..104fc5b552f8639e67566d9c064a19ff510c540c --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/a2po_trainer.md @@ -0,0 +1,51 @@ +# A2PO + +[![model badge](https://img.shields.io/badge/All_models-A2PO-blue)](https://huggingface.co/models?other=a2po,trl) + +TRL supports A\*-PO (Optimal Advantage Regression) as described in the paper [Accelerating RL for LLM Reasoning with Optimal Advantage Regression](https://huggingface.co/papers/2505.20686) by Kianté Brantley, Mingyu Chen, Zhaolin Gao, Jason D. Lee, Wen Sun, Wenhao Zhan, and Xuezhou Zhang. + +The abstract from the paper is the following: + +> Reinforcement learning (RL) has emerged as a powerful tool for fine-tuning large language models (LLMs) to improve complex reasoning abilities. However, state-of-the-art policy optimization methods often suffer from high computational overhead and memory consumption, primarily due to the need for multiple generations per prompt and the reliance on critic networks or advantage estimates of the current policy. In this paper, we propose A\*-PO, a novel two-stage policy optimization framework that directly approximates the optimal advantage function and enables efficient training of LLMs for reasoning tasks. In the first stage, we leverage offline sampling from a reference policy to estimate the optimal value function V\*, eliminating the need for costly online value estimation. In the second stage, we perform on-policy updates using a simple least-squares regression loss with only a single generation per prompt. Theoretically, we establish performance guarantees and prove that the KL-regularized RL objective can be optimized without requiring complex exploration strategies. Empirically, A\*-PO achieves competitive performance across a wide range of mathematical reasoning benchmarks, while reducing training time by up to 2× and peak memory usage by over 30% compared to PPO, GRPO, and REBEL. + +## Usage + +A\*-PO assumes a **binary, verifiable reward** (`r ∈ {0, 1}`) and runs in two stages: + +1. **Offline value estimation.** Before training, `num_value_samples` completions are sampled from the reference policy for every prompt and scored with `reward_funcs`. The optimal value `V*(x) = β₁·log(mean_i exp(r(x, yᵢ)/β₁))` is estimated and cached per prompt. +2. **On-policy regression.** During training, a single completion is generated per prompt from the current policy. The loss is the squared error between the implicit reward `β₂·log(π(y|x)/π_ref(y|x))` and the optimal advantage `r(x, y) − V*(x)`. + +```python +from trl.experimental.a2po import A2POConfig, A2POTrainer + +# A*-PO assumes a binary, verifiable reward in {0, 1}. +def reward_correct(completions, ground_truth, **kwargs): + return [float(completion.strip() == truth) for completion, truth in zip(completions, ground_truth)] + +training_args = A2POConfig( + output_dir="Qwen2.5-0.5B-A2PO", + num_value_samples=8, # Stage 1: samples per prompt from the reference policy to estimate V* + beta1=0.5, # Stage 1: KL temperature for the V* estimate + beta2=1e-3, # Stage 2: KL temperature for the regression target +) +trainer = A2POTrainer( + model="Qwen/Qwen2.5-0.5B", + reward_funcs=reward_correct, + args=training_args, + train_dataset=..., +) +trainer.train() +``` + +Because `V*` is estimated entirely from reference-policy samples, A\*-PO cannot exceed the reference policy's Pass@K. The official implementation can be found at [ZhaolinGao/A-PO](https://github.com/ZhaolinGao/A-PO). + +## A2POTrainer + +[[autodoc]] experimental.a2po.A2POTrainer + - train + - save_model + - push_to_hub + +## A2POConfig + +[[autodoc]] experimental.a2po.A2POConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/async_grpo_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/async_grpo_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..3aadb2db2257e6ab5e6d47b546368bfbebbb05ca --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/async_grpo_trainer.md @@ -0,0 +1,93 @@ +# Asynchronous GRPO + +> [!IMPORTANT] +> This trainer requires `vllm>=0.22.0` and `transformers>=5.2.0`. For distributed training, only FSDP2 is supported (DeepSpeed ZeRO is not). +> +> Currently, `vllm` and `transformers` have conflicting dependency constraints. To work around this, install vLLM first and then force-install transformers: +> +> ```bash +> pip install 'vllm>=0.22.0' +> pip install 'transformers>=5.2.0' --no-deps +> ``` + +## Overview + +[`AsyncGRPOTrainer`] implements the same [GRPO](grpo_trainer) algorithm but decouples rollout generation from training. A background worker continuously streams completions from a vLLM server while the training loop consumes them, so generation and gradient updates overlap instead of alternating. The API mirrors [`GRPOTrainer`] — for full details on the GRPO method itself (advantage computation, KL estimation, loss formulation, reward functions, etc.), see the [GRPO Trainer](grpo_trainer) documentation. Not all features from [`GRPOTrainer`] are available; refer to [`AsyncGRPOConfig`] for the supported parameters. + +This trainer was contributed by [Quentin Gallouédec](https://huggingface.co/qgallouedec) and [Amine Dirhoussi](https://huggingface.co/aminediroHF). + +## How it differs from [`GRPOTrainer`] + +In the standard [`GRPOTrainer`], generation and training are sequential: generate a batch, compute the loss, update weights, repeat. Even in [vLLM colocate mode](grpo_trainer#speed-up-training-with-vllm-powered-generation), where generation runs on the same GPUs, one phase must finish before the other begins. + +[`AsyncGRPOTrainer`] separates these two concerns: + +- **Rollout worker** (background process) — sends prompts to a vLLM server, scores completions with reward functions, computes advantages, and pushes ready-to-train samples into a queue. +- **Training loop** (main process) — pulls samples from the queue, computes the clipped surrogate loss, and updates the model weights. + +The rollout worker runs in a separate process spawned from the trainer, so reward computation never contends with the training loop for the GIL. This has two consequences for what you can pass as `reward_funcs`, `tools`, and `environment_factory` (for the latter, see the [OpenEnv guide](openenv), which covers the contract and the available integrations): + +> [!WARNING] +> Because we run the rollout worker in a separate process, everything passed to it is **pickled**. Each reward function, tool, and `environment_factory` (and anything they close over) must therefore be picklable: use a module-level function, [`functools.partial`](https://docs.python.org/3/library/functools.html#functools.partial), or a **callable class instance**. Lambdas and closures will raise a `TypeError` at `trainer.train()`. This is a difference from [`GRPOTrainer`], where reward functions are called in-process and closures work. +> +> The rollout process also runs with `CUDA_VISIBLE_DEVICES=""`, so it cannot use the GPU. A **GPU-backed reward model** (e.g. an `AutoModelForSequenceClassification` scorer) still loads without error but silently falls back to **CPU** (note that in [`GRPOTrainer`], such a reward model shares the trainer's GPUs). Keep reward functions CPU-side and lightweight (verifiers like `accuracy_reward`, format/length checks). +> +> If you do need a GPU reward model, the recommended approach is to **serve it behind its own inference engine** (vLLM, TGI, …) on separate GPUs and have a lightweight, picklable reward function call it over HTTP. This keeps the reward model on its own device while the rollout process stays CPU-only, and it scales independently of the trainer. + +After every `weight_sync_steps` training steps, the updated weights are transferred to the vLLM server via NCCL so that subsequent generations reflect the latest policy. + +Because generation and training run concurrently, the training samples may have been generated by a slightly older version of the model. The `max_staleness` parameter controls how many weight updates a sample can lag behind before being discarded. + +The number of concurrent requests sent to the vLLM server is controlled by `max_inflight_tasks`. By default it is set automatically to `max_staleness × per_device_train_batch_size × gradient_accumulation_steps × num_processes` — the maximum number of samples the trainer can consume before they become stale. Generating more than this is wasteful since the excess samples will be discarded. + +## Quick start + +```python +# train_async_grpo.py +from datasets import load_dataset +from trl.experimental.async_grpo import AsyncGRPOTrainer +from trl.rewards import accuracy_reward + +dataset = load_dataset("trl-lib/DeepMath-103K", split="train") + +trainer = AsyncGRPOTrainer( + model="Qwen/Qwen3-4B", + reward_funcs=accuracy_reward, + train_dataset=dataset, +) +trainer.train() +``` + +The vLLM server and the trainer must run on **separate GPUs**. Use `CUDA_VISIBLE_DEVICES` to partition your GPUs. For example, with 2 GPUs, you can run the vLLM server on GPU 0 and the trainer on GPU 1 as follows: + +```bash +# Terminal 1: vLLM server on GPU 0 (dev mode + NCCL weight transfer are required) +CUDA_VISIBLE_DEVICES=0 VLLM_SERVER_DEV_MODE=1 vllm serve Qwen/Qwen3-4B \ + --max-model-len 4096 \ + --logprobs-mode processed_logprobs \ + --weight-transfer-config '{"backend":"nccl"}' +``` + +> [!TIP] +> Set `--max-model-len` to the maximum total sequence length (prompt + completion) you expect. A lower value reduces GPU memory usage on the server, freeing more memory for the KV cache and increasing throughput. A good starting point is the prompt length plus `max_completion_length` from your config. + +```bash +# Terminal 2: training on GPU 1 +CUDA_VISIBLE_DEVICES=1 accelerate launch train_async_grpo.py +``` + +## Design philosophy + +This trainer is intentionally kept minimal and is not meant to grow into a general-purpose solution. If you need a feature that is not supported, we recommend cloning the repository and adapting the trainer to your needs directly. New features will only be considered when there is significant community demand. + +## AsyncGRPOConfig + +[[autodoc]] trl.experimental.async_grpo.AsyncGRPOConfig + +## AsyncGRPOTrainer + +[[autodoc]] trl.experimental.async_grpo.AsyncGRPOTrainer + +## RolloutWorkerProtocol + +[[autodoc]] trl.experimental.async_grpo.async_grpo_trainer.RolloutWorkerProtocol diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/bco_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/bco_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..43701940c801a3c8957f535678a76782ba15d56f --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/bco_trainer.md @@ -0,0 +1,105 @@ +# BCO Trainer + +[![model badge](https://img.shields.io/badge/All_models-BCO-blue)](https://huggingface.co/models?other=bco,trl) + +TRL supports the Binary Classifier Optimization (BCO). +The [BCO](https://huggingface.co/papers/2404.04656) authors train a binary classifier whose logit serves as a reward so that the classifier maps {prompt, chosen completion} pairs to 1 and {prompt, rejected completion} pairs to 0. +For a full example have a look at [`examples/scripts/bco.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/bco.py). + +## Expected dataset type + +The [`experimental.bco.BCOTrainer`] requires an [unpaired preference dataset](dataset_formats#unpaired-preference). +The [`experimental.bco.BCOTrainer`] supports both [conversational](dataset_formats#conversational) and [standard](dataset_formats#standard) dataset formats. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset. + +## Expected model format + +The BCO trainer expects a model of `AutoModelForCausalLM`, compared to PPO that expects `AutoModelForCausalLMWithValueHead` for the value function. + +## Using the `BCOTrainer` + +For a detailed example have a look at the `examples/scripts/bco.py` script. At a high level we need to initialize the `BCOTrainer` with a `model` we wish to train and a reference `ref_model` which we will use to calculate the implicit rewards of the preferred and rejected response. + +The `beta` refers to the hyperparameter of the implicit reward, and the dataset contains the 3 entries listed above. Note that the `model` and `ref_model` need to have the same architecture (ie decoder only or encoder-decoder). + +```python +from trl.experimental.bco import BCOConfig, BCOTrainer + +training_args = BCOConfig( + beta=0.1, +) + +bco_trainer = BCOTrainer( + model, + model_ref, + args=training_args, + train_dataset=train_dataset, + processing_class=tokenizer, +) +``` + +After this one can then call: + +```python +bco_trainer.train() +``` + +## Underlying Distribution matching (UDM) + +In practical scenarios, the thumbs-up and thumbs-down datasets are likely to have divergent underlying distributions of prompts. +Consider an LLM deployed for user feedback: if the model excels in writing tasks but underperforms in coding, the thumbs-up dataset will be dominated by writing-related prompts, while the thumbs-down dataset will contain mostly coding-related prompts. +If the prompts in your desired and undesired datasets differ a lot, it is useful to enable UDM. + +Choose an embedding model and tokenizer: + +```python +embedding_model = AutoModel.from_pretrained(your_model_id) +embedding_tokenizer = AutoTokenizer.from_pretrained(your_model_id) + +# customize this function depending on your embedding model +def embed_prompt(input_ids, attention_mask, model): + outputs = model(input_ids=input_ids, attention_mask=attention_mask) + return outputs.last_hidden_state.mean(dim=1) + +embedding_model = Accelerator().prepare_model(self.embedding_model) +embedding_func = partial(embed_prompt, model=embedding_model) +``` + +Set `prompt_sample_size` to define how many prompts are selected to train the UDM classifier and start the training with the provided embedding function: + +```python +training_args = BCOConfig( + beta=0.1, + prompt_sample_size=512, +) + +bco_trainer = BCOTrainer( + model, + model_ref, + args=training_args, + train_dataset=train_dataset, + processing_class=tokenizer, + embedding_func=embedding_func, + embedding_tokenizer=self.embedding_tokenizer, +) + +bco_trainer.train() +``` + +### For Mixture of Experts Models: Enabling the auxiliary loss + +MOEs are the most efficient if the load is about equally distributed between experts. +To ensure that we train MOEs similarly during preference-tuning, it is beneficial to add the auxiliary loss from the load balancer to the final loss. + +This option is enabled by setting `output_router_logits=True` in the model config (e.g. MixtralConfig). +To scale how much the auxiliary loss contributes to the total loss, use the hyperparameter `router_aux_loss_coef=...` (default: 0.001). + +## BCOTrainer + +[[autodoc]] experimental.bco.BCOTrainer + - train + - save_model + - push_to_hub + +## BCOConfig + +[[autodoc]] experimental.bco.BCOConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/bema_for_reference_model.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/bema_for_reference_model.md new file mode 100644 index 0000000000000000000000000000000000000000..896e642a3478b0d20759eb90a2df05898adf573e --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/bema_for_reference_model.md @@ -0,0 +1,32 @@ +# BEMA for Reference Model + +This feature implements the BEMA algorithm to update the reference model during DPO training. + +## Usage + +```python +from trl.experimental.bema_for_ref_model import BEMACallback, DPOTrainer +from datasets import load_dataset + +dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + +bema_callback = BEMACallback(update_ref_model=True) + +trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + train_dataset=dataset, + callbacks=[bema_callback], +) +trainer.train() +``` + +## DPOTrainer + +[[autodoc]] experimental.bema_for_ref_model.DPOTrainer + - train + - save_model + - push_to_hub + +## BEMACallback + +[[autodoc]] experimental.bema_for_ref_model.BEMACallback diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/callbacks.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/callbacks.md new file mode 100644 index 0000000000000000000000000000000000000000..395764282b3a04ab22b84ac46959a2d06686df6e --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/callbacks.md @@ -0,0 +1,17 @@ +# Callbacks + +## RichProgressCallback + +[[autodoc]] RichProgressCallback + +## LogCompletionsCallback + +[[autodoc]] LogCompletionsCallback + +## BEMACallback + +[[autodoc]] BEMACallback + +## WeaveCallback + +[[autodoc]] WeaveCallback diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/chat_template_utils.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/chat_template_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..53ee8fae46dd2ac38244878b5ae68142de3cc1eb --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/chat_template_utils.md @@ -0,0 +1,15 @@ +# Chat template utilities + +For an overview of the chat templates bundled with TRL and the rationale behind the training patches, see [Chat Templates](chat_templates). + +## clone_chat_template + +[[autodoc]] clone_chat_template + +## is_chat_template_prefix_preserving + +[[autodoc]] chat_template_utils.is_chat_template_prefix_preserving + +## get_training_chat_template + +[[autodoc]] chat_template_utils.get_training_chat_template diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/chat_templates.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/chat_templates.md new file mode 100644 index 0000000000000000000000000000000000000000..499c0d8a8141f6c905712704f45ed6bc4ec5b6bb --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/chat_templates.md @@ -0,0 +1,181 @@ +# Chat Templates + +A [chat template](https://huggingface.co/docs/transformers/en/chat_templating) is a Jinja2 snippet that formats messages into the string a model was trained on. For example: + +```python +>>> from transformers import AutoTokenizer +>>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +>>> tokenizer.chat_template +"{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }}{% endif %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}" +>>> tokenizer.apply_chat_template([{"role": "user", "content": "Hi!"}], tokenize=False) +'<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\nHi!<|im_end|>\n' +``` + +In most cases you don't need to worry about chat templates: models ship their template along with the tokenizer, and TRL applies it for you. The whole thing is transparent. But some TRL recipes rely on features that most shipped templates don't include: + +- **SFT with `assistant_only_loss=True`** needs `{% generation %}` / `{% endgeneration %}` markers around assistant output, so the loss mask can target only assistant tokens. +- **GRPO with tool calls** needs the template to be *prefix-preserving*: appending a tool message must not change how earlier messages are rendered. + +TRL ships patched templates under [`trl/chat_templates/`](https://github.com/huggingface/trl/tree/main/trl/chat_templates) for common families (Qwen, Llama, DeepSeek-V3, GPT-OSS, ...) and swaps them in automatically for supported models. For any other model, you'll need to patch its template yourself. The rest of this page catalogs what's bundled. + +## Supported model families + +TRL stores reference copies of the original templates so it can identify supported models at init and swap in a training template when needed. The following families are recognized: Cohere, Cohere2, DeepSeek-V3, Gemma, Gemma3, GLM-4-MoE, GPT-OSS, Idefics3, Llama 3 / 3.1 / 3.2, Llava-Next, Nemotron 3 (Nano, Super, Ultra), Phi-3, Phi-3.5, Qwen2-VL, Qwen2.5, Qwen2.5-VL, Qwen3 (including the Instruct-2507 variant), Qwen3-VL, Qwen3.5, Qwen3.6. + +## Training templates + +Patched templates that fix training-specific issues. Swapped in at init when tools are enabled (GRPO) or when `assistant_only_loss=True` (SFT). + +### `cohere_training.jinja` + +Patched Cohere template. Diff vs `cohere.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `cohere2_training.jinja` + +Patched Cohere2 template. Diff vs `cohere2.jinja`: + +Move the trailing `<|END_OF_TURN_TOKEN|>` from after the role-dispatch `{% endif %}` into each role branch, and wrap the assistant branch (`<|START_RESPONSE|>...<|END_RESPONSE|><|END_OF_TURN_TOKEN|>`) with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `deepseekv3_training.jinja` + +Patched DeepSeek-V3 template. Diff vs `deepseekv3.jinja`: + +- Uses `| tojson` on `tool['function']['arguments']` so that `arguments` can be passed as a `dict` (the documented format per [transformers docs](https://huggingface.co/docs/transformers/en/chat_extras#tool-calling-example)). The original template uses raw string concatenation, which crashes on dict inputs. +- Wraps assistant message output with `{% generation %}` / `{% endgeneration %}` markers for SFT assistant-only loss. + +### `gemma_training.jinja` + +Patched Gemma template (shared by Gemma and Gemma2, which ship identical chat templates). Diff vs `gemma.jinja`: + +Split the unified assistant output so that the `model\n` header (a prompt cue, not generated by the model) sits outside the generation block, and wrap the assistant content with `{% generation %}` / `{% endgeneration %}` markers for SFT assistant-only loss. + +### `gemma3_training.jinja` + +Patched Gemma 3 template. Same diff as `gemma_training.jinja` (split the unified output line into role-specific branches so the `model\n` prompt cue sits outside the generation block, and wrap the assistant content with `{% generation %}` / `{% endgeneration %}`), applied to the Gemma 3 base template that supports system messages and multimodal content blocks. + +### `glm4moe_training.jinja` + +Patched GLM-4-MoE template. Diff vs `glm4moe.jinja`: + +Require both `` and `` to be present before parsing, to avoid incorrect splitting when the model generates only one tag: + +```diff +- {%- if '
' in content %} ++ {%- if '' in content and '' in content %} +``` + +Wrap assistant message output (including the thinking block and tool calls) with `{% generation %}` / `{% endgeneration %}` markers for SFT assistant-only loss. + +### `qwen3_training.jinja` + +Patched Qwen3 template. Diff vs `qwen3.jinja`: + +Require both `` and `` to be present before parsing, to avoid incorrect splitting when the model generates only one tag: + +```diff +- {%- if '
' in content %} ++ {%- if '' in content and '' in content %} +``` + +Always include the thinking block regardless of message position. The original conditionally omits it based on `loop.last`, which changes the assistant rendering when a tool message is appended, breaking prefix-preservation: + +```diff +- {%- if loop.index0 > ns.last_query_index %} +- {%- if loop.last or (not loop.last and reasoning_content) %} +- {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content.strip('\n') + '\n\n\n' + content.lstrip('\n') }} +- {%- else %} +- {{- '<|im_start|>' + message.role + '\n' + content }} +- {%- endif %} +- {%- else %} +- {{- '<|im_start|>' + message.role + '\n' + content }} +- {%- endif %} ++ {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content.strip('\n') + '\n\n\n' + content.lstrip('\n') }} +``` + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `qwen3_vl_training.jinja` + +Patched Qwen3-VL template. Diff vs `qwen3_vl.jinja`: + +Wrap assistant message output (both `content` and `tool_calls`) with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `gptoss_training.jinja` + +Patched GPT-OSS template. Diff vs `gptoss.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `idefics3_training.jinja` + +Patched Idefics3 template. Diff vs `idefics3.jinja`: + +Split the assistant message into its own branch so the `{% generation %}` / `{% endgeneration %}` markers wrap the assistant content. This enables `return_assistant_tokens_mask=True` to produce correct masks for SFT assistant-only loss. + +### `llama3_training.jinja` + +Patched Llama 3 template. Diff vs `llama3.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `llava_next_training.jinja` + +Patched Llava-Next template. Diff vs `llava_next.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `nemotron_3_nano_training.jinja` + +Patched Nemotron Nano template. Diff vs `nemotron_3_nano.jinja`: the original is already prefix-preserving, so the only change is wrapping assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `nemotron_3_super_training.jinja` + +Patched Nemotron Super template. Diff vs `nemotron_3_super.jinja`: same as `nemotron_3_nano_training.jinja` — the original is already prefix-preserving, so the only change is wrapping assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `nemotron_3_ultra_training.jinja` + +Patched Nemotron Ultra template. Diff vs `nemotron_3_ultra.jinja`: same as `nemotron_3_nano_training.jinja` — the original is already prefix-preserving, so the only change is wrapping assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `phi3_training.jinja` + +Patched Phi-3 template. Diff vs `phi3.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `phi3_5_training.jinja` + +Patched Phi-3.5 template. Diff vs `phi3_5.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `qwen2_5_training.jinja` + +Patched Qwen2.5 template. Diff vs `qwen2_5.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `qwen2_5_vl_training.jinja` + +Patched Qwen2.5-VL template (also used for Qwen2-VL, which ships a byte-identical template). Diff vs `qwen2_5_vl.jinja`: + +Split the assistant message into its own branch so the `{% generation %}` / `{% endgeneration %}` markers wrap the assistant content. This enables `return_assistant_tokens_mask=True` to produce correct masks for SFT assistant-only loss. + +### `qwen3_instruct_2507_training.jinja` + +Patched Qwen3-Instruct-2507 template (used by models like `Qwen3-4B-Instruct-2507`, which ship a simpler Qwen3 variant without `reasoning_content` / `` parsing, `multi_step_tool` tracking, or the `enable_thinking` flag). Diff vs `qwen3_instruct_2507.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `qwen3_5_think_training.jinja` / `qwen3_5_nothink_training.jinja` + +Patched Qwen3.5 templates, shared logic across both flavors (they differ only in the default value of the `enable_thinking` flag — `qwen3_5_think_training.jinja` defaults to thinking enabled, used by Qwen3.5-4B and larger; `qwen3_5_nothink_training.jinja` defaults to thinking disabled, used by Qwen3.5-2B and smaller). Diff vs `qwen3_5_think.jinja` / `qwen3_5_nothink.jinja`: same set of changes as `qwen3_training.jinja` — require both `` and `` to be present before parsing, drop the `loop.index0 > ns.last_query_index` conditional so the thinking block is always emitted (prefix-preservation), and wrap assistant output with `{% generation %}` / `{% endgeneration %}` markers for SFT assistant-only loss. + +### `qwen3_6_training.jinja` + +Patched Qwen3.6 template. Diff vs `qwen3_6.jinja`: same set of changes as `qwen3_training.jinja` — require both `` and `` to be present before parsing, drop the `loop.index0 > ns.last_query_index` conditional so the thinking block is always emitted (prefix-preservation), and wrap assistant output with `{% generation %}` / `{% endgeneration %}` markers for SFT assistant-only loss. + +## Related utilities + +See [Chat Template Utilities](chat_template_utils) for the helper functions ([`clone_chat_template`], [`is_chat_template_prefix_preserving`], [`get_training_chat_template`]) that operate on these templates. diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/clis.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/clis.md new file mode 100644 index 0000000000000000000000000000000000000000..54c8c1055f99522af7de6bcc989599487a26e29b --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/clis.md @@ -0,0 +1,703 @@ +# Command Line Interfaces (CLIs) + +TRL provides a powerful command-line interface (CLI) to fine-tune large language models (LLMs) using methods like Supervised Fine-Tuning (SFT), Direct Preference Optimization (DPO), and more. The CLI abstracts away much of the boilerplate, letting you launch training jobs quickly and reproducibly. + +## Commands + +Currently supported commands are: + +### Training Commands + +- `trl dpo`: fine-tune a LLM with DPO +- `trl grpo`: fine-tune a LLM with GRPO +- `trl kto`: fine-tune a LLM with KTO +- `trl reward`: train a Reward Model +- `trl rloo`: fine-tune a LLM with RLOO +- `trl sft`: fine-tune a LLM with SFT + +### Other Commands + +- `trl env`: get the system information +- `trl vllm-serve`: serve a model with vLLM + +## Fine-Tuning with the TRL CLI + +### Basic Usage + +You can launch training directly from the CLI by specifying required arguments like the model and dataset: + + + + +```bash +trl sft \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name stanfordnlp/imdb +``` + + + + +```bash +trl dpo \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name anthropic/hh-rlhf +``` + + + + +```bash +trl reward \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name trl-lib/ultrafeedback_binarized +``` + + + + +```bash +trl grpo \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name HuggingFaceH4/Polaris-Dataset-53K \ + --reward_funcs accuracy_reward +``` + + + + +```bash +trl rloo \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name HuggingFaceH4/Polaris-Dataset-53K \ + --reward_funcs accuracy_reward +``` + + + + +```bash +trl kto \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name trl-lib/kto-mix-14k +``` + + + + +### Using Configuration Files + +To keep your CLI commands clean and reproducible, you can define all training arguments in a YAML configuration file: + + + + +```yaml +# sft_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +dataset_name: stanfordnlp/imdb +``` + +Launch with: + +```bash +trl sft --config sft_config.yaml +``` + + + + +```yaml +# dpo_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +dataset_name: anthropic/hh-rlhf +``` + +Launch with: + +```bash +trl dpo --config dpo_config.yaml +``` + + + + +```yaml +# reward_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +dataset_name: trl-lib/ultrafeedback_binarized +``` + +Launch with: + +```bash +trl reward --config reward_config.yaml +``` + + + + +```yaml +# grpo_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +dataset_name: HuggingFaceH4/Polaris-Dataset-53K +reward_funcs: + - accuracy_reward +``` + +Launch with: + +```bash +trl grpo --config grpo_config.yaml +``` + + + + +```yaml +# rloo_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +dataset_name: HuggingFaceH4/Polaris-Dataset-53K +reward_funcs: + - accuracy_reward +``` + +Launch with: + +```bash +trl rloo --config rloo_config.yaml +``` + + + + +```yaml +# kto_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +dataset_name: trl-lib/kto-mix-14k +``` + +Launch with: + +```bash +trl kto --config kto_config.yaml +``` + + + + +### Scaling Up with Accelerate + +TRL CLI natively supports [🤗 Accelerate](https://huggingface.co/docs/accelerate), making it easy to scale training across multiple GPUs, machines, or use advanced setups like DeepSpeed — all from the same CLI. + +You can pass any `accelerate launch` arguments directly to `trl`, such as `--num_processes`. For more information see [Using accelerate launch](https://huggingface.co/docs/accelerate/en/basic_tutorials/launch#using-accelerate-launch). + + + + +```bash +trl sft \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name stanfordnlp/imdb \ + --num_processes 4 +``` + +or, with a config file: + +```yaml +# sft_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +dataset_name: stanfordnlp/imdb +num_processes: 4 +``` + +Launch with: + +```bash +trl sft --config sft_config.yaml +``` + + + + +```bash +trl dpo \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name anthropic/hh-rlhf \ + --num_processes 4 +``` + +or, with a config file: + +```yaml +# dpo_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +dataset_name: anthropic/hh-rlhf +num_processes: 4 +``` + +Launch with: + +```bash +trl dpo --config dpo_config.yaml +``` + + + + +```bash +trl reward \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name trl-lib/ultrafeedback_binarized \ + --num_processes 4 +``` + +or, with a config file: + +```yaml +# reward_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +dataset_name: trl-lib/ultrafeedback_binarized +num_processes: 4 +``` + +Launch with: + +```bash +trl reward --config reward_config.yaml +``` + + + + +```bash +trl grpo \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name HuggingFaceH4/Polaris-Dataset-53K \ + --reward_funcs accuracy_reward \ + --num_processes 4 +``` + +or, with a config file: + +```yaml +# grpo_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +dataset_name: HuggingFaceH4/Polaris-Dataset-53K +reward_funcs: + - accuracy_reward +num_processes: 4 +``` + +Launch with: + +```bash +trl grpo --config grpo_config.yaml +``` + + + + +```bash +trl rloo \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name HuggingFaceH4/Polaris-Dataset-53K \ + --reward_funcs accuracy_reward \ + --num_processes 4 +``` + +or, with a config file: + +```yaml +# rloo_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +dataset_name: HuggingFaceH4/Polaris-Dataset-53K +reward_funcs: + - accuracy_reward +num_processes: 4 +``` + +Launch with: + +```bash +trl rloo --config rloo_config.yaml +``` + + + + +```bash +trl kto \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name trl-lib/kto-mix-14k \ + --num_processes 4 +``` + +or, with a config file: + +```yaml +# kto_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +dataset_name: trl-lib/kto-mix-14k +num_processes: 4 +``` + +Launch with: + +```bash +trl kto --config kto_config.yaml +``` + + + + +### Using `--accelerate_config` for Accelerate Configuration + +The `--accelerate_config` flag lets you easily configure distributed training with [🤗 Accelerate](https://github.com/huggingface/accelerate). This flag accepts either: + +- the name of a predefined config profile (built into TRL), or +- a path to a custom Accelerate YAML config file. + +#### Predefined Config Profiles + +TRL provides several ready-to-use Accelerate configs to simplify common training setups: + +| Name | Description | +| --- | --- | +| `fsdp1` | Fully Sharded Data Parallel Stage 1 | +| `fsdp2` | Fully Sharded Data Parallel Stage 2 | +| `zero1` | DeepSpeed ZeRO Stage 1 | +| `zero2` | DeepSpeed ZeRO Stage 2 | +| `zero3` | DeepSpeed ZeRO Stage 3 | +| `multi_gpu` | Multi-GPU training | +| `single_gpu` | Single-GPU training | + +To use one of these, just pass the name to `--accelerate_config`. TRL will automatically load the corresponding config file from `trl/accelerate_config/`. + +#### Example Usage + + + + +```bash +trl sft \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name stanfordnlp/imdb \ + --accelerate_config zero2 # or path/to/my/accelerate/config.yaml +``` + +or, with a config file: + +```yaml +# sft_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +dataset_name: stanfordnlp/imdb +accelerate_config: zero2 # or path/to/my/accelerate/config.yaml +``` + +Launch with: + +```bash +trl sft --config sft_config.yaml +``` + + + + +```bash +trl dpo \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name anthropic/hh-rlhf \ + --accelerate_config zero2 # or path/to/my/accelerate/config.yaml +``` + +or, with a config file: + +```yaml +# dpo_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +dataset_name: anthropic/hh-rlhf +accelerate_config: zero2 # or path/to/my/accelerate/config.yaml +``` + +Launch with: + +```bash +trl dpo --config dpo_config.yaml +``` + + + + +```bash +trl reward \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name trl-lib/ultrafeedback_binarized \ + --accelerate_config zero2 # or path/to/my/accelerate/config.yaml +``` + +or, with a config file: + +```yaml +# reward_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +dataset_name: trl-lib/ultrafeedback_binarized +accelerate_config: zero2 # or path/to/my/accelerate/config.yaml +``` + +Launch with: + +```bash +trl reward --config reward_config.yaml +``` + + + + +```bash +trl grpo \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name HuggingFaceH4/Polaris-Dataset-53K \ + --reward_funcs accuracy_reward \ + --accelerate_config zero2 # or path/to/my/accelerate/config.yaml +``` + +or, with a config file: + +```yaml +# grpo_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +dataset_name: HuggingFaceH4/Polaris-Dataset-53K +reward_funcs: + - accuracy_reward +accelerate_config: zero2 # or path/to/my/accelerate/config.yaml +``` + +Launch with: + +```bash +trl grpo --config grpo_config.yaml +``` + + + + +```bash +trl rloo \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name HuggingFaceH4/Polaris-Dataset-53K \ + --reward_funcs accuracy_reward \ + --accelerate_config zero2 # or path/to/my/accelerate/config.yaml +``` + +or, with a config file: + +```yaml +# rloo_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +dataset_name: HuggingFaceH4/Polaris-Dataset-53K +reward_funcs: + - accuracy_reward +accelerate_config: zero2 # or path/to/my/accelerate/config.yaml +``` + +Launch with: + +```bash +trl rloo --config rloo_config.yaml +``` + + + + +```bash +trl kto \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name trl-lib/kto-mix-14k \ + --accelerate_config zero2 # or path/to/my/accelerate/config.yaml +``` + +or, with a config file: + +```yaml +# kto_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +dataset_name: trl-lib/kto-mix-14k +accelerate_config: zero2 # or path/to/my/accelerate/config.yaml +``` + +Launch with: + +```bash +trl kto --config kto_config.yaml +``` + + + + +### Using dataset mixtures + +You can use dataset mixtures to combine multiple datasets into a single training dataset. This is useful for training on diverse data sources or when you want to mix different types of data. + + + + +```yaml +# sft_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +datasets: + - path: stanfordnlp/imdb + - path: roneneldan/TinyStories +``` + +Launch with: + +```bash +trl sft --config sft_config.yaml +``` + + + + +```yaml +# dpo_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +datasets: + - path: BAAI/Infinity-Preference + - path: argilla/Capybara-Preferences +``` + +Launch with: + +```bash +trl dpo --config dpo_config.yaml +``` + + + + +```yaml +# reward_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +datasets: + - path: trl-lib/tldr-preference + - path: trl-lib/lm-human-preferences-sentiment +``` + +Launch with: + +```bash +trl reward --config reward_config.yaml +``` + + + + +```yaml +# grpo_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +datasets: + - path: HuggingFaceH4/Polaris-Dataset-53K + - path: trl-lib/DeepMath-103K +reward_funcs: + - accuracy_reward +``` + +Launch with: + +```bash +trl grpo --config grpo_config.yaml +``` + + + + +```yaml +# rloo_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +datasets: + - path: HuggingFaceH4/Polaris-Dataset-53K + - path: trl-lib/DeepMath-103K +reward_funcs: + - accuracy_reward +``` + +Launch with: + +```bash +trl rloo --config rloo_config.yaml +``` + + + + +```yaml +# kto_config.yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +datasets: + - path: trl-lib/kto-mix-14k + - path: argilla/ultrafeedback-binarized-preferences-cleaned +``` + +Launch with: + +```bash +trl kto --config kto_config.yaml +``` + + + + +To see all the available keywords for defining dataset mixtures, refer to the [`scripts.utils.DatasetConfig`] and [`DatasetMixtureConfig`] classes. + +## Getting the System Information + +You can get the system information by running the following command: + +```bash +trl env +``` + +This will print out the system information, including the GPU information, the CUDA version, the PyTorch version, the transformers version, the TRL version, and any optional dependencies that are installed. + +```txt +Copy-paste the following information when reporting an issue: + +- Platform: Linux-5.15.0-1048-aws-x86_64-with-glibc2.31 +- Python version: 3.11.9 +- PyTorch version: 2.4.1 +- accelerator(s): NVIDIA H100 80GB HBM3 +- Transformers version: 4.45.0.dev0 +- Accelerate version: 0.34.2 +- Accelerate config: + - compute_environment: LOCAL_MACHINE + - distributed_type: DEEPSPEED + - mixed_precision: no + - use_cpu: False + - debug: False + - num_processes: 4 + - machine_rank: 0 + - num_machines: 1 + - rdzv_backend: static + - same_network: True + - main_training_function: main + - enable_cpu_affinity: False + - deepspeed_config: {'gradient_accumulation_steps': 4, 'offload_optimizer_device': 'none', 'offload_param_device': 'none', 'zero3_init_flag': False, 'zero_stage': 2} + - downcast_bf16: no + - tpu_use_cluster: False + - tpu_use_sudo: False + - tpu_env: [] +- Datasets version: 3.0.0 +- HF Hub version: 0.24.7 +- TRL version: 0.12.0.dev0+acb4d70 +- bitsandbytes version: 0.41.1 +- DeepSpeed version: 0.15.1 +- Diffusers version: 0.30.3 +- Liger-Kernel version: 0.3.0 +- LLM-Blender version: 0.0.2 +- OpenAI version: 1.46.0 +- PEFT version: 0.12.0 +- vLLM version: not installed +``` + +This information is required when reporting an issue. diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/community_tutorials.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/community_tutorials.md new file mode 100644 index 0000000000000000000000000000000000000000..81eda22088afb593407f1b06e747c47b2404e85b --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/community_tutorials.md @@ -0,0 +1,66 @@ +# Community Tutorials + +Community tutorials are made by active members of the Hugging Face community who want to share their knowledge and expertise with others. They are a great way to learn about the library and its features, and to get started with core classes and modalities. + +## Language Models + +### Tutorials + +| Task | Class | Description | Author | Tutorial | Colab | +| --- | --- | --- | --- | --- | --- | +| Reinforcement Learning | [`GRPOTrainer`] | Efficient Online Training with GRPO and vLLM in TRL | [Sergio Paniego](https://huggingface.co/sergiopaniego) | [Link](https://huggingface.co/learn/cookbook/grpo_vllm_online_training) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/cookbook/blob/main/notebooks/en/grpo_vllm_online_training.ipynb) | +| Reinforcement Learning | [`GRPOTrainer`] | Post training an LLM for reasoning with GRPO in TRL | [Sergio Paniego](https://huggingface.co/sergiopaniego) | [Link](https://huggingface.co/learn/cookbook/fine_tuning_llm_grpo_trl) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/cookbook/blob/main/notebooks/en/fine_tuning_llm_grpo_trl.ipynb) | +| Reinforcement Learning | [`GRPOTrainer`] | Mini-R1: Reproduce Deepseek R1 „aha moment“ a RL tutorial | [Philipp Schmid](https://huggingface.co/philschmid) | [Link](https://www.philschmid.de/mini-deepseek-r1) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/philschmid/deep-learning-pytorch-huggingface/blob/main/training/mini-deepseek-r1-aha-grpo.ipynb) | +| Reinforcement Learning | [`GRPOTrainer`] | RL on LLaMA 3.1-8B with GRPO and Unsloth optimizations | [Andrea Manzoni](https://huggingface.co/AManzoni) | [Link](https://colab.research.google.com/github/amanzoni1/fine_tuning/blob/main/RL_LLama3_1_8B_GRPO.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/amanzoni1/fine_tuning/blob/main/RL_LLama3_1_8B_GRPO.ipynb) | +| Instruction tuning | [`SFTTrainer`] | Fine-tuning Google Gemma LLMs using ChatML format with QLoRA | [Philipp Schmid](https://huggingface.co/philschmid) | [Link](https://www.philschmid.de/fine-tune-google-gemma) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/philschmid/deep-learning-pytorch-huggingface/blob/main/training/gemma-lora-example.ipynb) | +| Structured Generation | [`SFTTrainer`] | Fine-tuning Llama-2-7B to generate Persian product catalogs in JSON using QLoRA and PEFT | [Mohammadreza Esmaeilian](https://huggingface.co/Mohammadreza) | [Link](https://huggingface.co/learn/cookbook/en/fine_tuning_llm_to_generate_persian_product_catalogs_in_json_format) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/cookbook/blob/main/notebooks/en/fine_tuning_llm_to_generate_persian_product_catalogs_in_json_format.ipynb) | +| Preference Optimization | [`DPOTrainer`] | Align Mistral-7b using Direct Preference Optimization for human preference alignment | [Maxime Labonne](https://huggingface.co/mlabonne) | [Link](https://mlabonne.github.io/blog/posts/Fine_tune_Mistral_7b_with_DPO.html) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/mlabonne/llm-course/blob/main/Fine_tune_a_Mistral_7b_model_with_DPO.ipynb) | +| Preference Optimization | [`experimental.orpo.ORPOTrainer`] | Fine-tuning Llama 3 with ORPO combining instruction tuning and preference alignment | [Maxime Labonne](https://huggingface.co/mlabonne) | [Link](https://mlabonne.github.io/blog/posts/2024-04-19_Fine_tune_Llama_3_with_ORPO.html) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1eHNWg9gnaXErdAa8_mcvjMupbSS6rDvi) | +| Instruction tuning | [`SFTTrainer`] | How to fine-tune open LLMs in 2025 with Hugging Face | [Philipp Schmid](https://huggingface.co/philschmid) | [Link](https://www.philschmid.de/fine-tune-llms-in-2025) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/philschmid/deep-learning-pytorch-huggingface/blob/main/training/fine-tune-llms-in-2025.ipynb) | +| Step-Level Reasoning | [`GRPOTrainer`] | Supervised Reinforcement Learning (SRL) for step-by-step reasoning with vLLM | [Deepak Swaminathan](https://huggingface.co/s23deepak) | [Link](https://github.com/s23deepak/Supervised-Reinforcement-Learning) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/s23deepak/Supervised-Reinforcement-Learning/blob/main/notebooks/srl_grpo_tutorial.ipynb) | + +### Videos + +| Task | Title | Author | Video | +| --- | --- | --- | --- | +| Instruction tuning | Fine-tuning open AI models using Hugging Face TRL | [Wietse Venema](https://huggingface.co/wietsevenema) | [](https://youtu.be/cnGyyM0vOes) | +| Instruction tuning | How to fine-tune a smol-LM with Hugging Face, TRL, and the smoltalk Dataset | [Mayurji](https://huggingface.co/iammayur) | [](https://youtu.be/jKdXv3BiLu0) | + + +
+⚠️ Deprecated features notice for "How to fine-tune a smol-LM with Hugging Face, TRL, and the smoltalk Dataset" (click to expand) + +> [!WARNING] +> The tutorial uses two deprecated features: +> +> - `SFTTrainer(..., tokenizer=tokenizer)`: Use `SFTTrainer(..., processing_class=tokenizer)` instead, or simply omit it (it will be inferred from the model). +> - `setup_chat_format(model, tokenizer)`: Use `SFTConfig(..., chat_template_path="Qwen/Qwen3-0.6B")`, where `chat_template_path` specifies the model whose chat template you want to copy. + +
+ +## Vision Language Models + +### Tutorials + +| Task | Class | Description | Author | Tutorial | Colab | +| --- | --- | --- | --- | --- | --- | +| Visual QA | [`SFTTrainer`] | Fine-tuning Qwen2-VL-7B for visual question answering on ChartQA dataset | [Sergio Paniego](https://huggingface.co/sergiopaniego) | [Link](https://huggingface.co/learn/cookbook/fine_tuning_vlm_trl) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/cookbook/blob/main/notebooks/en/fine_tuning_vlm_trl.ipynb) | +| Visual QA | [`SFTTrainer`] | Fine-tuning SmolVLM with TRL on a consumer GPU | [Sergio Paniego](https://huggingface.co/sergiopaniego) | [Link](https://huggingface.co/learn/cookbook/fine_tuning_smol_vlm_sft_trl) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/cookbook/blob/main/notebooks/en/fine_tuning_smol_vlm_sft_trl.ipynb) | +| SEO Description | [`SFTTrainer`] | Fine-tuning Qwen2-VL-7B for generating SEO-friendly descriptions from images | [Philipp Schmid](https://huggingface.co/philschmid) | [Link](https://www.philschmid.de/fine-tune-multimodal-llms-with-trl) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/philschmid/deep-learning-pytorch-huggingface/blob/main/training/fine-tune-multimodal-llms-with-trl.ipynb) | +| Visual QA | [`DPOTrainer`] | PaliGemma 🤝 Direct Preference Optimization | [Merve Noyan](https://huggingface.co/merve) | [Link](https://github.com/merveenoyan/smol-vision/blob/main/PaliGemma_DPO.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/merveenoyan/smol-vision/blob/main/PaliGemma_DPO.ipynb) | +| Visual QA | [`DPOTrainer`] | Fine-tuning SmolVLM using direct preference optimization (DPO) with TRL on a consumer GPU | [Sergio Paniego](https://huggingface.co/sergiopaniego) | [Link](https://huggingface.co/learn/cookbook/fine_tuning_vlm_dpo_smolvlm_instruct) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/cookbook/blob/main/notebooks/en/fine_tuning_vlm_dpo_smolvlm_instruct.ipynb) | +| Object Detection Grounding | [`SFTTrainer`] | Fine tuning a VLM for Object Detection Grounding using TRL | [Sergio Paniego](https://huggingface.co/sergiopaniego) | [Link](https://huggingface.co/learn/cookbook/fine_tuning_vlm_object_detection_grounding) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/cookbook/blob/main/notebooks/en/fine_tuning_vlm_object_detection_grounding.ipynb) | +| Visual QA | [`DPOTrainer`] | Fine-Tuning a Vision Language Model with TRL using MPO | [Sergio Paniego](https://huggingface.co/sergiopaniego) | [Link](https://huggingface.co/learn/cookbook/fine_tuning_vlm_mpo) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/cookbook/blob/main/notebooks/en/fine_tuning_vlm_mpo.ipynb) | +| Reinforcement Learning | [`GRPOTrainer`] | Post training a VLM for reasoning with GRPO using TRL | [Sergio Paniego](https://huggingface.co/sergiopaniego) | [Link](https://huggingface.co/learn/cookbook/fine_tuning_vlm_grpo_trl) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/cookbook/blob/main/notebooks/en/fine_tuning_vlm_grpo_trl.ipynb) | + +## Speech Language Models + +### Tutorials + +| Task | Class | Description | Author | Tutorial | +| --- | --- | --- | --- | --- | +| Text-to-Speech | [`GRPOTrainer`] | Post training a Speech Language Model with GRPO using TRL | [Steven Zheng](https://huggingface.co/Steveeeeeeen) | [Link](https://huggingface.co/blog/Steveeeeeeen/llasa-grpo) | + +## Contributing + +If you have a tutorial that you would like to add to this list, please open a PR to add it. We will review it and merge it if it is relevant to the community. diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/cpo_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/cpo_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..e1ff2a198a4212272cd5d3ce2b5c5c57edaaea34 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/cpo_trainer.md @@ -0,0 +1,126 @@ +# CPO Trainer + +[![model badge](https://img.shields.io/badge/All_models-CPO-blue)](https://huggingface.co/models?other=cpo,trl) + +## Overview + +Contrastive Preference Optimization (CPO) as introduced in the paper [Contrastive Preference Optimization: Pushing the Boundaries of LLM Performance in Machine Translation](https://huggingface.co/papers/2401.08417) by [Haoran Xu](https://huggingface.co/haoranxu), [Amr Sharaf](https://huggingface.co/amrsharaf), [Yunmo Chen](https://huggingface.co/yunmochen), Weiting Tan, Lingfeng Shen, Benjamin Van Durme, [Kenton Murray](https://huggingface.co/Kenton), and [Young Jin Kim](https://huggingface.co/ykim362). At a high level, CPO trains models to avoid generating adequate, but not perfect, translations in Machine Translation (MT) tasks. However, CPO is a general approximation of the DPO loss and can be applied to other domains, such as chat. + +CPO aims to mitigate two fundamental shortcomings of SFT. First, SFT’s methodology of minimizing the discrepancy between predicted outputs and gold-standard references inherently caps model performance at the quality level of the training data. Secondly, SFT lacks a mechanism to prevent the model from rejecting mistakes in translations. The CPO objective is derived from the DPO objective. + +## Quick start + +This example demonstrates how to train a model using the CPO method. We use the [Qwen 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) as the base model. We use the preference data from the [UltraFeedback dataset](https://huggingface.co/datasets/openbmb/UltraFeedback). You can view the data in the dataset here: + + + +Below is the script to train the model: + +```python +# train_cpo.py +from datasets import load_dataset +from trl.experimental.cpo import CPOConfig, CPOTrainer +from transformers import AutoModelForCausalLM, AutoTokenizer + +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +train_dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") + +training_args = CPOConfig(output_dir="Qwen2-0.5B-CPO") +trainer = CPOTrainer(model=model, args=training_args, processing_class=tokenizer, train_dataset=train_dataset) +trainer.train() +``` + +Execute the script using the following command: + +```bash +accelerate launch train_cpo.py +``` + +## Expected dataset type + +CPO requires a [preference dataset](dataset_formats#preference). The [`experimental.cpo.CPOTrainer`] supports both [conversational](dataset_formats#conversational) and [standard](dataset_formats#standard) dataset formats. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset. + +## Example script + +We provide an example script to train a model using the CPO method. The script is available in [`examples/scripts/cpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/cpo.py) + +To test the CPO script with the [Qwen2 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) on the [UltraFeedback dataset](https://huggingface.co/datasets/trl-lib/ultrafeedback_binarized), run the following command: + +```bash +accelerate launch examples/scripts/cpo.py \ + --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ + --dataset_name trl-lib/ultrafeedback_binarized \ + --num_train_epochs 1 \ + --output_dir Qwen2-0.5B-CPO +``` + +## Logged metrics + +While training and evaluating, we record the following reward metrics: + +* `rewards/chosen`: the mean log probabilities of the policy model for the chosen responses scaled by beta +* `rewards/rejected`: the mean log probabilities of the policy model for the rejected responses scaled by beta +* `rewards/accuracies`: mean of how often the chosen rewards are > than the corresponding rejected rewards +* `rewards/margins`: the mean difference between the chosen and corresponding rejected rewards +* `nll_loss`: the mean negative log likelihood loss of the policy model for the chosen responses + +## CPO variants + +### Simple Preference Optimization (SimPO) + +[Simple Preference Optimization](https://huggingface.co/papers/2405.14734) (SimPO) by [Yu Meng](https://huggingface.co/yumeng5), [Mengzhou Xia](https://huggingface.co/mengzhouxia), and [Danqi Chen](https://huggingface.co/cdq10131) proposes a simpler and more effective preference optimization algorithm than DPO without using a reference model. The key designs in SimPO are (1) using length-normalized log likelihood as the implicit reward, and (2) incorporating a target reward margin in the Bradley-Terry ranking objective. The official code can be found at [princeton-nlp/SimPO](https://github.com/princeton-nlp/SimPO). + +The abstract from the paper is the following: + +> Direct Preference Optimization (DPO) is a widely used offline preference optimization algorithm that reparameterizes reward functions in reinforcement learning from human feedback (RLHF) to enhance simplicity and training stability. In this work, we propose SimPO, a simpler yet more effective approach. The effectiveness of SimPO is attributed to a key design: using the average log probability of a sequence as the implicit reward. This reward formulation better aligns with model generation and eliminates the need for a reference model, making it more compute and memory efficient. Additionally, we introduce a target reward margin to the Bradley-Terry objective to encourage a larger margin between the winning and losing responses, further enhancing the algorithm's performance. We compare SimPO to DPO and its latest variants across various state-of-the-art training setups, including both base and instruction-tuned models like Mistral and Llama3. We evaluated on extensive instruction-following benchmarks, including AlpacaEval 2, MT-Bench, and the recent challenging Arena-Hard benchmark. Our results demonstrate that SimPO consistently and significantly outperforms existing approaches without substantially increasing response length. Specifically, SimPO outperforms DPO by up to 6.4 points on AlpacaEval 2 and by up to 7.5 points on Arena-Hard. Our top-performing model, built on Llama3-8B-Instruct, achieves a remarkable 44.7 length-controlled win rate on AlpacaEval 2 -- surpassing Claude 3 Opus on the leaderboard, and a 33.8 win rate on Arena-Hard -- making it the strongest 8B open-source model. + +The SimPO loss is integrated in the [`experimental.cpo.CPOTrainer`], as it's an alternative loss that adds a reward margin, allows for length normalization, and does not use BC regularization. To use this loss, just turn on `loss_type="simpo"` and `cpo_alpha=0.0` in the [`experimental.cpo.CPOConfig`] and set the `simpo_gamma` to a recommended value. + +### CPO-SimPO + +We also offer the combined use of CPO and SimPO, which enables more stable training and improved performance. Learn more details at [CPO-SimPO GitHub](https://github.com/fe1ixxu/CPO_SIMPO). To use this method, simply enable SimPO by setting `loss_type="simpo"` and a non-zero `cpo_alpha` in the [`experimental.cpo.CPOConfig`]. + +### AlphaPO + +The [AlphaPO -- Reward shape matters for LLM alignment](https://huggingface.co/papers/2501.03884) (AlphaPO) method by Aman Gupta, Shao Tang, Qingquan Song, Sirou Zhu, [Jiwoo Hong](https://huggingface.co/JW17), Ankan Saha, Viral Gupta, Noah Lee, Eunki Kim, Jason Zhu, Natesh Pillai, and S. Sathiya Keerthi is also implemented in the [`experimental.cpo.CPOTrainer`]. AlphaPO is an alternative method that applies a transformation to the reward function shape in the context of SimPO loss. The abstract from the paper is the following: + +> Reinforcement Learning with Human Feedback (RLHF) and its variants have made huge strides toward the effective alignment of large language models (LLMs) to follow instructions and reflect human values. More recently, Direct Alignment Algorithms (DAAs) have emerged in which the reward modeling stage of RLHF is skipped by characterizing the reward directly as a function of the policy being learned. Some popular examples of DAAs include Direct Preference Optimization (DPO) and Simple Preference Optimization (SimPO). These methods often suffer from likelihood displacement, a phenomenon by which the probabilities of preferred responses are often reduced undesirably. In this paper, we argue that, for DAAs the reward (function) shape matters. We introduce AlphaPO, a new DAA method that leverages an α-parameter to help change the shape of the reward function beyond the standard log reward. AlphaPO helps maintain fine-grained control over likelihood displacement and overoptimization. Compared to SimPO, one of the best performing DAAs, AlphaPO leads to about 7% to 10% relative improvement in alignment performance for the instruct versions of Mistral-7B and Llama3-8B while achieving 15% to 50% relative improvement over DPO on the same models. The analysis and results presented highlight the importance of the reward shape and how one can systematically change it to affect training dynamics, as well as improve alignment performance. + +To use this loss as described in the paper, we can set the `loss_type="alphapo"` which automatically sets `loss_type="simpo"` and `cpo_alpha=0.0`, together with `alpha` and `simpo_gamma` to recommended values in the [`experimental.cpo.CPOConfig`]. Alternatively, you can manually set `loss_type="simpo"`, `cpo_alpha=0.0`, together with `alpha` and `simpo_gamma` to recommended values. Other variants of this method are also possible, such as setting `loss_type="ipo"` and `alpha` to any non-zero value. + +## Loss functions + +The CPO algorithm supports several loss functions. The loss function can be set using the `loss_type` parameter in the [`experimental.cpo.CPOConfig`]. The following loss functions are supported: + +| `loss_type=` | Description | +| --- | --- | +| `"sigmoid"` (default) | Given the preference data, we can fit a binary classifier according to the Bradley-Terry model, and in fact, the [DPO](https://huggingface.co/papers/2305.18290) authors propose the sigmoid loss on the normalized likelihood via the `logsigmoid` to fit a logistic regression. | +| `"hinge"` | The [RSO](https://huggingface.co/papers/2309.06657) authors propose to use a hinge loss on the normalized likelihood from the [SLiC](https://huggingface.co/papers/2305.10425) paper. In this case, the `beta` is the reciprocal of the margin. | +| `"ipo"` | The [IPO](https://huggingface.co/papers/2310.12036) authors provide a deeper theoretical understanding of the DPO algorithms and identify an issue with overfitting and propose an alternative loss. In this case, the `beta` is the reciprocal of the gap between the log-likelihood ratios of the chosen vs the rejected completion pair, and thus the smaller the `beta`, the larger this gap is. As per the paper, the loss is averaged over log-likelihoods of the completion (unlike DPO, which is summed only). | +| `"simpo"` | The [SimPO](https://huggingface.co/papers/2405.14734) method is also implemented in the [`experimental.cpo.CPOTrainer`]. SimPO is an alternative loss that adds a reward margin, allows for length normalization, and does not use BC regularization. To use this loss, simply set `loss_type="simpo"` and `cpo_alpha=0.0` in the [`experimental.cpo.CPOConfig`] and `simpo_gamma` to a recommended value. | +| `"alphapo"` | The [AlphaPO](https://huggingface.co/papers/2501.03884) method is also implemented in the [`experimental.cpo.CPOTrainer`]. This is syntactic sugar that automatically sets `loss_type="simpo"` and `cpo_alpha=0.0`. AlphaPO applies a transformation to the reward function shape in the context of SimPO loss when the `alpha` parameter is non-zero. | + +### For Mixture of Experts Models: Enabling the auxiliary loss + +MOEs are the most efficient if the load is about equally distributed between experts. +To ensure that we train MOEs similarly during preference-tuning, it is beneficial to add the auxiliary loss from the load balancer to the final loss. + +This option is enabled by setting `output_router_logits=True` in the model config (e.g., [`~transformers.MixtralConfig`]). +To scale how much the auxiliary loss contributes to the total loss, use the hyperparameter `router_aux_loss_coef=...` (default: `0.001`) in the model config. + +## CPOTrainer + +[[autodoc]] experimental.cpo.CPOTrainer + - train + - save_model + - push_to_hub + +## CPOConfig + +[[autodoc]] experimental.cpo.CPOConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/customization.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/customization.md new file mode 100644 index 0000000000000000000000000000000000000000..e3051b7c61e67982aa9e7cc2488422bd0e174774 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/customization.md @@ -0,0 +1,113 @@ +# Training customization + +TRL is designed with modularity in mind so that users are able to efficiently customize the training loop for their needs. Below are examples on how you can apply and test different techniques. + +> [!NOTE] +> Although these examples use the [`DPOTrainer`], these customization methods apply to most (if not all) trainers in TRL. + +## Use different optimizers and schedulers + +By default, the [`DPOTrainer`] creates a `torch.optim.AdamW` optimizer. You can create and define a different optimizer and pass it to [`DPOTrainer`] as follows: + +```python +from datasets import load_dataset +from torch import optim +from transformers import AutoModelForCausalLM +from trl import DPOTrainer + +dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") +optimizer = optim.SGD(model.parameters(), lr=1e-6) + +trainer = DPOTrainer( + model=model, + train_dataset=dataset, + optimizers=(optimizer, None), +) +trainer.train() +``` + +### Add a learning rate scheduler + +You can also add learning rate schedulers by passing both optimizer and scheduler: + +```python +from torch import optim + +optimizer = optim.AdamW(model.parameters(), lr=1e-6) +lr_scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=30, gamma=0.1) + +trainer = DPOTrainer(..., optimizers=(optimizer, lr_scheduler)) +``` + +## Pass 8-bit reference models + +Since `trl` supports all keyword arguments when loading a model from `transformers` using `from_pretrained`, you can also leverage `load_in_8bit` from `transformers` for more memory efficient fine-tuning. + +Read more about 8-bit model loading in `transformers` [Load in 8bit or 4bit](https://huggingface.co/docs/transformers/en/peft). + +```python +from transformers import AutoModelForCausalLM, BitsAndBytesConfig + +quantization_config = BitsAndBytesConfig(load_in_8bit=True) +ref_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct", quantization_config=quantization_config) + +trainer = DPOTrainer(..., ref_model=ref_model) +``` + +## Add custom callbacks + +You can customize the training loop by adding callbacks for logging, monitoring, or early stopping. Callbacks allow you to execute custom code at specific points during training. + +```python +from transformers import TrainerCallback + + +class CustomLoggingCallback(TrainerCallback): + def on_log(self, args, state, control, logs=None, **kwargs): + if logs is not None: + print(f"Step {state.global_step}: {logs}") + + +trainer = DPOTrainer(..., callbacks=[CustomLoggingCallback()]) +``` + +## Add custom evaluation metrics + +You can define custom evaluation metrics to track during training. This is useful for monitoring model performance on specific tasks. + +```python +def compute_metrics(eval_preds): + logits, labels = eval_preds + # Add your metric computation here + return {"custom_metric": 0.0} + + +training_args = DPOConfig(..., eval_strategy="steps", eval_steps=100) + +trainer = DPOTrainer(..., eval_dataset=eval_dataset, compute_metrics=compute_metrics) +``` + +## Use mixed precision training + +Mixed precision training can significantly speed up training and reduce memory usage. You can enable it by setting `bf16=True` or `fp16=True` in the training config. + +```python +# Use bfloat16 precision (recommended for modern GPUs) +training_args = DPOConfig(..., bf16=True) +``` + +Note: Use `bf16=True` for Ampere GPUs (A100, RTX 30xx) or newer, and `fp16=True` for older GPUs. + +## Use gradient accumulation + +When training with limited GPU memory, gradient accumulation allows you to simulate larger batch sizes by accumulating gradients over multiple steps before updating weights. + +```python +# Simulate a batch size of 32 with per_device_train_batch_size=4 and gradient_accumulation_steps=8 +training_args = DPOConfig( + ..., + per_device_train_batch_size=4, + gradient_accumulation_steps=8, +) +``` diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/data_utils.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/data_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..19622d249da62b5ba42b30ab91cd51f8b3a2810f --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/data_utils.md @@ -0,0 +1,17 @@ +# Data Utilities + +## is_conversational + +[[autodoc]] is_conversational + +## maybe_convert_to_chatml + +[[autodoc]] maybe_convert_to_chatml + +## extract_prompt + +[[autodoc]] extract_prompt + +## unpair_preference_dataset + +[[autodoc]] unpair_preference_dataset diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/dataset_formats.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/dataset_formats.md new file mode 100644 index 0000000000000000000000000000000000000000..f2214bbf75fe9008561cbb5400b05666c773a2c8 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/dataset_formats.md @@ -0,0 +1,1012 @@ +# Dataset formats and types + +This guide provides an overview of the dataset formats and types supported by each trainer in TRL. + +## Overview of the dataset formats and types + +- The *format* of a dataset refers to how the data is structured, typically categorized as either *standard* or *conversational*. +- The *type* is associated with the specific task the dataset is designed for, such as *prompt-only* or *preference*. Each type is characterized by its columns, which vary according to the task, as shown in the table. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Type \ FormatStandardConversational
Language modeling +
{"text": "The sky is blue."}
+
+
{"messages": [{"role": "user", "content": "What color is the sky?"},
+              {"role": "assistant", "content": "It is blue."}]}
+
Prompt-only +
{"prompt": "The sky is"}
+
+
{"prompt": [{"role": "user", "content": "What color is the sky?"}]}
+
Prompt-completion +
{"prompt": "The sky is",
+ "completion": " blue."}
+
+
{"prompt": [{"role": "user", "content": "What color is the sky?"}],
+ "completion": [{"role": "assistant", "content": "It is blue."}]}
+
Preference +
{"prompt": "The sky is",
+ "chosen": " blue.",
+ "rejected": " green."}
+ or, with implicit prompt: +
{"chosen": "The sky is blue.",
+ "rejected": "The sky is green."}
+
+
{"prompt": [{"role": "user", "content": "What color is the sky?"}],
+ "chosen": [{"role": "assistant", "content": "It is blue."}],
+ "rejected": [{"role": "assistant", "content": "It is green."}]}
+ or, with implicit prompt: +
{"chosen": [{"role": "user", "content": "What color is the sky?"},
+              {"role": "assistant", "content": "It is blue."}],
+ "rejected": [{"role": "user", "content": "What color is the sky?"},
+                {"role": "assistant", "content": "It is green."}]}
+
Unpaired preference +
{"prompt": "The sky is",
+ "completion": " blue.",
+ "label": True}
+
+
{"prompt": [{"role": "user", "content": "What color is the sky?"}],
+ "completion": [{"role": "assistant", "content": "It is green."}],
+ "label": False}
+
Stepwise supervision +
{"prompt": "Which number is larger, 9.8 or 9.11?",
+ "completions": ["The fractional part of 9.8 is 0.8.",
+                 "The fractional part of 9.11 is 0.11.",
+                 "0.11 is greater than 0.8.",
+                 "Hence, 9.11 > 9.8."],
+ "labels": [True, True, False, False]}
+
+ +### Formats + +#### Standard + +The standard dataset format typically consists of plain text strings. The columns in the dataset vary depending on the task. This is the format expected by TRL trainers. Below are examples of standard dataset formats for different tasks: + +```python +# Language modeling +language_modeling_example = {"text": "The sky is blue."} +# Preference +preference_example = {"prompt": "The sky is", "chosen": " blue.", "rejected": " green."} +# Unpaired preference +unpaired_preference_example = {"prompt": "The sky is", "completion": " blue.", "label": True} +``` + +#### Conversational + +Conversational datasets are used for tasks involving dialogues or chat interactions between users and assistants. Unlike standard dataset formats, these contain sequences of messages where each message has a `role` (e.g., `"user"` or `"assistant"`) and `content` (the message text). + +```python +messages = [ + {"role": "user", "content": "Hello, how are you?"}, + {"role": "assistant", "content": "I'm doing great. How can I help you today?"}, + {"role": "user", "content": "I'd like to show off how chat templating works!"}, +] +``` + +Just like standard datasets, the columns in conversational datasets vary depending on the task. Below are examples of conversational dataset formats for different tasks: + +```python +# Prompt-completion +prompt_completion_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}], + "completion": [{"role": "assistant", "content": "It is blue."}]} +# Preference +preference_example = { + "prompt": [{"role": "user", "content": "What color is the sky?"}], + "chosen": [{"role": "assistant", "content": "It is blue."}], + "rejected": [{"role": "assistant", "content": "It is green."}], +} +``` + +#### Tool Calling + +Some chat templates support *tool calling*, which allows the model to interact with external functions—referred to as **tools**—during generation. This extends the conversational capabilities of the model by enabling it to output a `"tool_calls"` field instead of a standard `"content"` message whenever it decides to invoke a tool. + +After the assistant initiates a tool call, the tool executes and returns its output. The assistant can then process this output and continue the conversation accordingly. + +Here’s a simple example of a tool-calling interaction: + +```python +messages = [ + {"role": "user", "content": "Turn on the living room lights."}, + {"role": "assistant", "tool_calls": [ + {"type": "function", "function": { + "name": "control_light", + "arguments": {"room": "living room", "state": "on"} + }}] + }, + {"role": "tool", "name": "control_light", "content": "The lights in the living room are now on."}, + {"role": "assistant", "content": "Done!"} +] +``` + +When preparing datasets for Supervised Fine-Tuning (SFT) with tool calling, it is important that your dataset includes an additional column named `tools`. This column contains the list of available tools for the model, which is usually used by the chat template to construct the system prompt. + +The tools must be specified in a codified JSON schema format. You can automatically generate this schema from Python function signatures using the [`~transformers.utils.get_json_schema`] utility: + +```python +import json +from transformers.utils import get_json_schema + +def control_light(room: str, state: str) -> str: + """ + Controls the lights in a room. + + Args: + room: The name of the room. + state: The desired state of the light ("on" or "off"). + + Returns: + str: A message indicating the new state of the lights. + """ + return f"The lights in {room} are now {state}." + +# Generate JSON schema +json_schema = get_json_schema(control_light) +``` + +The generated schema would look like: + +```python +{"type": "function", "function": {"name": "control_light", "description": "Controls the lights in a room.", "parameters": {"type": "object", "properties": {"room": {"type": "string", "description": "The name of the room."}, "state": {"type": "string", "description": "The desired state of the light (\"on\" or \"off\")."}}, "required": ["room", "state"]}, "return": {"type": "string", "description": "str: A message indicating the new state of the lights."}}} +``` + +A complete dataset entry for SFT might look like: + +```python +{"messages": messages, "tools": [json_schema]} +``` + +To get a `Dataset` you need to use the `Json()` type for tool arguments since they are arbitrary JSON objects, and not dictionaries with fixed fields and types: + +```python +from datasets import Dataset + +data = [ + {"messages": messages1, "tools": [json_schema1]}, + {"messages": messages2, "tools": [json_schema2]}, +] +# auto-apply the Json() type +dataset = Dataset.from_list(data, on_mixed_types="use_json") + +# or specify the features manually +from datasets import Features, Json, List, Value + +features = Features( + { + "messages": List({"role": Value("string"), "content": Value("string"), "tool_calls": List(Json())}), + "tools": List(Json()), + } +) +dataset = Dataset.from_list(data, features=features) +``` + +On older versions of `datasets` (<4.7.0) that don't have the `Json()` type, you should store `tools` as a JSON `str` (with `json.dumps([...])`): + +```python +dataset = Dataset.from_list( + [{"messages": messages1, "tools": json.dumps([json_schema1])}, + {"messages": messages2, "tools": json.dumps([json_schema2])}] +) +``` + +For more detailed information on tool calling, refer to the [Tool Calling section in the `transformers` documentation](https://huggingface.co/docs/transformers/chat_extras#tools-and-rag) and the blog post [Tool Use, Unified](https://huggingface.co/blog/unified-tool-use). + +### Harmony + +The [Harmony response format](https://cookbook.openai.com/articles/openai-harmony) was introduced with the [OpenAI GPT OSS models](https://huggingface.co/collections/openai/gpt-oss-68911959590a1634ba11c7a4). It extends the conversational format by adding richer structure for reasoning, function calls, and metadata about the model’s behavior. Key features include: + +- **Developer role** – Provides high level instructions (similar to a system prompt) and lists available tools. +- **Channels** – Separate types of assistant output into distinct streams: + + - `analysis` – for internal reasoning, from the key `"thinking"` + - `final` – for the user-facing answer, from the key `"content"` + - `commentary` – for tool calls or meta notes + +- **Reasoning effort** – Signals how much thinking the model should show (e.g., `"low"`, `"medium"`, `"high"`). +- **Model identity** – Explicitly defines the assistant’s persona. + +```python +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("openai/gpt-oss-20b") + +messages = [ + {"role": "developer", "content": "Use a friendly tone."}, + {"role": "user", "content": "What is the meaning of life?"}, + {"role": "assistant", "thinking": "Deep reflection...", "content": "The final answer is..."}, +] + +print( + tokenizer.apply_chat_template( + messages, + tokenize=False, + reasoning_effort="low", + model_identity="You are HuggingGPT, a large language model trained by Hugging Face.", + ) +) +``` + +This produces: + +```txt +<|start|>system<|message|>You are HuggingGPT, a large language model trained by Hugging Face. +Knowledge cutoff: 2024-06 +Current date: 2025-08-03 + +Reasoning: low + +# Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions + +Use a friendly tone.<|end|><|start|>user<|message|>What is the meaning of life?<|end|><|start|>assistant<|channel|>analysis<|message|>Deep reflection...<|end|><|start|>assistant<|channel|>final<|message|>The final answer is...<|return|> +``` + +For full details on message structure, supported fields, and advanced usage, see the [Harmony documentation](https://cookbook.openai.com/articles/openai-harmony). + +### Types + +#### Language modeling + +A language modeling dataset consists of a column `"text"` (or `"messages"` for conversational datasets) containing a full sequence of text. + +```python +# Standard format +language_modeling_example = {"text": "The sky is blue."} +# Conversational format +language_modeling_example = {"messages": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."} +]} +``` + +#### Prompt-only + +In a prompt-only dataset, only the initial prompt (the question or partial sentence) is provided under the key `"prompt"`. The training typically involves generating completion based on this prompt, where the model learns to continue or complete the given input. + +```python +# Standard format +prompt_only_example = {"prompt": "The sky is"} +# Conversational format +prompt_only_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}]} +``` + +For examples of prompt-only datasets, refer to the [Prompt-only datasets collection](https://huggingface.co/collections/trl-lib/prompt-only-datasets-677ea25245d20252cea00368). + +> [!TIP] +> While both the prompt-only and language modeling types are similar, they differ in how the input is handled. In the prompt-only type, the prompt represents a partial input that expects the model to complete or continue, while in the language modeling type, the input is treated as a complete sentence or sequence. These two types are processed differently by TRL. Below is an example showing the difference in the output of the `apply_chat_template` function for each type: +> +> ```python +> from transformers import AutoTokenizer +> from trl import apply_chat_template +> +> tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-128k-instruct") +> +> # Example for prompt-only type +> prompt_only_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}]} +> apply_chat_template(prompt_only_example, tokenizer) +> # Output: {'prompt': '<|user|>\nWhat color is the sky?<|end|>\n<|assistant|>\n'} +> +> # Example for language modeling type +> lm_example = {"messages": [{"role": "user", "content": "What color is the sky?"}]} +> apply_chat_template(lm_example, tokenizer) +> # Output: {'text': '<|user|>\nWhat color is the sky?<|end|>\n<|endoftext|>'} +> ``` +> +> - The prompt-only output includes a `'<|assistant|>\n'`, indicating the beginning of the assistant’s turn and expecting the model to generate a completion. +> - In contrast, the language modeling output treats the input as a complete sequence and terminates it with `'<|endoftext|>'`, signaling the end of the text and not expecting any additional content. + +#### Prompt-completion + +A prompt-completion dataset includes a `"prompt"` and a `"completion"`. + +```python +# Standard format +prompt_completion_example = {"prompt": "The sky is", "completion": " blue."} +# Conversational format +prompt_completion_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}], + "completion": [{"role": "assistant", "content": "It is blue."}]} +``` + +For examples of prompt-completion datasets, refer to the [Prompt-completion datasets collection](https://huggingface.co/collections/trl-lib/prompt-completion-datasets-677ea2bb20bbb6bdccada216). + +#### Preference + +A preference dataset is used for tasks where the model is trained to choose between two or more possible completions to the same prompt. This dataset includes a `"prompt"`, a `"chosen"` completion, and a `"rejected"` completion. The model is trained to select the `"chosen"` response over the `"rejected"` response. +Some datasets may not include the `"prompt"` column, in which case the prompt is implicit and directly included in the `"chosen"` and `"rejected"` completions. We recommend using explicit prompts whenever possible. + +```python +# Standard format +## Explicit prompt (recommended) +preference_example = {"prompt": "The sky is", "chosen": " blue.", "rejected": " green."} +# Implicit prompt +preference_example = {"chosen": "The sky is blue.", "rejected": "The sky is green."} + +# Conversational format +## Explicit prompt (recommended) +preference_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}], + "chosen": [{"role": "assistant", "content": "It is blue."}], + "rejected": [{"role": "assistant", "content": "It is green."}]} +## Implicit prompt +preference_example = {"chosen": [{"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}], + "rejected": [{"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is green."}]} +``` + +For examples of preference datasets, refer to the [Preference datasets collection](https://huggingface.co/collections/trl-lib/preference-datasets-677e99b581018fcad9abd82c). + +Some preference datasets can be found with [the tag `dpo` on Hugging Face Hub](https://huggingface.co/datasets?other=dpo). You can also explore the [librarian-bots' DPO Collections](https://huggingface.co/collections/librarian-bots/direct-preference-optimization-datasets-66964b12835f46289b6ef2fc) to identify preference datasets. + +#### Unpaired preference + +An unpaired preference dataset is similar to a preference dataset but instead of having `"chosen"` and `"rejected"` completions for the same prompt, it includes a single `"completion"` and a `"label"` indicating whether the completion is preferred or not. + +```python +# Standard format +unpaired_preference_example = {"prompt": "The sky is", "completion": " blue.", "label": True} +# Conversational format +unpaired_preference_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}], + "completion": [{"role": "assistant", "content": "It is blue."}], + "label": True} +``` + +For examples of unpaired preference datasets, refer to the [Unpaired preference datasets collection](https://huggingface.co/collections/trl-lib/unpaired-preference-datasets-677ea22bf5f528c125b0bcdf). + +#### Stepwise supervision + +A stepwise (or process) supervision dataset is similar to an [unpaired preference](#unpaired-preference) dataset but includes multiple steps of completions, each with its own label. This structure is useful for tasks that need detailed, step-by-step labeling, such as reasoning tasks. By evaluating each step separately and providing targeted labels, this approach helps identify precisely where the reasoning is correct and where errors occur, allowing for targeted feedback on each part of the reasoning process. + +```python +stepwise_example = { + "prompt": "Which number is larger, 9.8 or 9.11?", + "completions": ["The fractional part of 9.8 is 0.8, while the fractional part of 9.11 is 0.11.", "Since 0.11 is greater than 0.8, the number 9.11 is larger than 9.8."], + "labels": [True, False] +} +``` + +For examples of stepwise supervision datasets, refer to the [Stepwise supervision datasets collection](https://huggingface.co/collections/trl-lib/stepwise-supervision-datasets-677ea27fd4c5941beed7a96e). + +## Which dataset type to use? + +Choosing the right dataset type depends on the task you are working on and the specific requirements of the TRL trainer you are using. Below is a brief overview of the dataset types supported by each TRL trainer. + +| Trainer | Expected dataset type | +| --- | --- | +| [`DPOTrainer`] | [Preference (explicit prompt recommended)](#preference) | +| [`GRPOTrainer`] | [Prompt-only](#prompt-only) | +| [`RewardTrainer`] | [Preference (implicit prompt recommended)](#preference) | +| [`RLOOTrainer`] | [Prompt-only](#prompt-only) | +| [`SFTTrainer`] | [Language modeling](#language-modeling) or [Prompt-completion](#prompt-completion) | +| [`experimental.bco.BCOTrainer`] | [Unpaired preference](#unpaired-preference) or [Preference (explicit prompt recommended)](#preference) | +| [`experimental.cpo.CPOTrainer`] | [Preference (explicit prompt recommended)](#preference) | +| [`experimental.gkd.GKDTrainer`] | [Prompt-completion](#prompt-completion) | +| [`experimental.kto.KTOTrainer`] | [Unpaired preference](#unpaired-preference) or [Preference (explicit prompt recommended)](#preference) | +| [`experimental.nash_md.NashMDTrainer`] | [Prompt-only](#prompt-only) | +| [`experimental.online_dpo.OnlineDPOTrainer`] | [Prompt-only](#prompt-only) | +| [`experimental.orpo.ORPOTrainer`] | [Preference (explicit prompt recommended)](#preference) | +| [`experimental.ppo.PPOTrainer`] | Tokenized language modeling | +| [`experimental.prm.PRMTrainer`] | [Stepwise supervision](#stepwise-supervision) | +| [`experimental.xpo.XPOTrainer`] | [Prompt-only](#prompt-only) | + +## Using any dataset with TRL: preprocessing and conversion + +Many datasets come in formats tailored to specific tasks, which might not be directly compatible with TRL. To use such datasets with TRL, you may need to preprocess and convert them into the required format. + +To make this easier, we provide a set of [example scripts](https://github.com/huggingface/trl/tree/main/examples/datasets) that cover common dataset conversions. + +### Example: UltraFeedback dataset + +Let’s take the [UltraFeedback dataset](https://huggingface.co/datasets/openbmb/UltraFeedback) as an example. Here's a preview of the dataset: + + + +As shown above, the dataset format does not match the expected structure. It’s not in a conversational format, the column names differ, and the results pertain to different models (e.g., Bard, GPT-4) and aspects (e.g., "helpfulness", "honesty"). + +By using the provided conversion script [`examples/datasets/ultrafeedback.py`](https://github.com/huggingface/trl/tree/main/examples/datasets/ultrafeedback.py), you can transform this dataset into an unpaired preference type, and push it to the Hub: + +```sh +python examples/datasets/ultrafeedback.py --push_to_hub --repo_id trl-lib/ultrafeedback-gpt-3.5-turbo-helpfulness +``` + +Once converted, the dataset will look like this: + + + +Now, you can use this dataset with TRL! + +By adapting the provided scripts or creating your own, you can convert any dataset into a format compatible with TRL. + +## Utilities for converting dataset types + +This section provides example code to help you convert between different dataset types. While some conversions can be performed after applying the chat template (i.e., in the standard format), we recommend performing the conversion before applying the chat template to ensure it works consistently. + +For simplicity, some of the examples below do not follow this recommendation and use the standard format. However, the conversions can be applied directly to the conversational format without modification. + +| From \ To | Language modeling | Prompt-completion | Prompt-only | Preference with implicit prompt | Preference | Unpaired preference | Stepwise supervision | +| --- | --- | --- | --- | --- | --- | --- | --- | +| Language modeling | N/A | N/A | N/A | N/A | N/A | N/A | N/A | +| Prompt-completion | [🔗](#from-prompt-completion-to-language-modeling-dataset) | N/A | [🔗](#from-prompt-completion-to-prompt-only-dataset) | N/A | N/A | N/A | N/A | +| Prompt-only | N/A | N/A | N/A | N/A | N/A | N/A | N/A | +| Preference with implicit prompt | [🔗](#from-preference-with-implicit-prompt-to-language-modeling-dataset) | [🔗](#from-preference-with-implicit-prompt-to-prompt-completion-dataset) | [🔗](#from-preference-with-implicit-prompt-to-prompt-only-dataset) | N/A | [🔗](#from-implicit-to-explicit-prompt-preference-dataset) | [🔗](#from-preference-with-implicit-prompt-to-unpaired-preference-dataset) | N/A | +| Preference | [🔗](#from-preference-to-language-modeling-dataset) | [🔗](#from-preference-to-prompt-completion-dataset) | [🔗](#from-preference-to-prompt-only-dataset) | [🔗](#from-explicit-to-implicit-prompt-preference-dataset) | N/A | [🔗](#from-preference-to-unpaired-preference-dataset) | N/A | +| Unpaired preference | [🔗](#from-unpaired-preference-to-language-modeling-dataset) | [🔗](#from-unpaired-preference-to-prompt-completion-dataset) | [🔗](#from-unpaired-preference-to-prompt-only-dataset) | N/A | N/A | N/A | N/A | +| Stepwise supervision | [🔗](#from-stepwise-supervision-to-language-modeling-dataset) | [🔗](#from-stepwise-supervision-to-prompt-completion-dataset) | [🔗](#from-stepwise-supervision-to-prompt-only-dataset) | N/A | N/A | [🔗](#from-stepwise-supervision-to-unpaired-preference-dataset) | N/A | + +### From prompt-completion to language modeling dataset + +To convert a prompt-completion dataset into a language modeling dataset, concatenate the prompt and the completion. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["The sky is", "The sun is"], + "completion": [" blue.", " in the sky."], +}) + +def concat_prompt_completion(example): + return {"text": example["prompt"] + example["completion"]} + +dataset = dataset.map(concat_prompt_completion, remove_columns=["prompt", "completion"]) +``` + +```python +>>> dataset[0] +{'text': 'The sky is blue.'} +``` + +### From prompt-completion to prompt-only dataset + +To convert a prompt-completion dataset into a prompt-only dataset, remove the completion. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["The sky is", "The sun is"], + "completion": [" blue.", " in the sky."], +}) + +dataset = dataset.remove_columns("completion") +``` + +```python +>>> dataset[0] +{'prompt': 'The sky is'} +``` + +### From preference with implicit prompt to language modeling dataset + +To convert a preference with implicit prompt dataset into a language modeling dataset, remove the rejected, and rename the column `"chosen"` to `"text"`. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "chosen": ["The sky is blue.", "The sun is in the sky."], + "rejected": ["The sky is green.", "The sun is in the sea."], +}) + +dataset = dataset.rename_column("chosen", "text").remove_columns("rejected") +``` + +```python +>>> dataset[0] +{'text': 'The sky is blue.'} +``` + +### From preference with implicit prompt to prompt-completion dataset + +To convert a preference dataset with implicit prompt into a prompt-completion dataset, extract the prompt with [`extract_prompt`], remove the rejected, and rename the column `"chosen"` to `"completion"`. + +```python +from datasets import Dataset +from trl import extract_prompt + +dataset = Dataset.from_dict({ + "chosen": [ + [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is blue."}], + [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sky."}], + ], + "rejected": [ + [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is green."}], + [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sea."}], + ], +}) +dataset = dataset.map(extract_prompt).remove_columns("rejected").rename_column("chosen", "completion") +``` + +```python +>>> dataset[0] +{'prompt': [{'role': 'user', 'content': 'What color is the sky?'}], 'completion': [{'role': 'assistant', 'content': 'It is blue.'}]} +``` + +### From preference with implicit prompt to prompt-only dataset + +To convert a preference dataset with implicit prompt into a prompt-only dataset, extract the prompt with [`extract_prompt`], and remove the rejected and the chosen. + +```python +from datasets import Dataset +from trl import extract_prompt + +dataset = Dataset.from_dict({ + "chosen": [ + [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is blue."}], + [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sky."}], + ], + "rejected": [ + [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is green."}], + [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sea."}], + ], +}) +dataset = dataset.map(extract_prompt).remove_columns(["chosen", "rejected"]) +``` + +```python +>>> dataset[0] +{'prompt': [{'role': 'user', 'content': 'What color is the sky?'}]} +``` + +### From implicit to explicit prompt preference dataset + +To convert a preference dataset with implicit prompt into a preference dataset with explicit prompt, extract the prompt with [`extract_prompt`]. + +```python +from datasets import Dataset +from trl import extract_prompt + +dataset = Dataset.from_dict({ + "chosen": [ + [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is blue."}], + [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sky."}], + ], + "rejected": [ + [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is green."}], + [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sea."}], + ], +}) + +dataset = dataset.map(extract_prompt) +``` + +```python +>>> dataset[0] +{'prompt': [{'role': 'user', 'content': 'What color is the sky?'}], + 'chosen': [{'role': 'assistant', 'content': 'It is blue.'}], + 'rejected': [{'role': 'assistant', 'content': 'It is green.'}]} +``` + +### From preference with implicit prompt to unpaired preference dataset + +To convert a preference dataset with implicit prompt into an unpaired preference dataset, extract the prompt with [`extract_prompt`], and unpair the dataset with [`unpair_preference_dataset`]. + +```python +from datasets import Dataset +from trl import extract_prompt, unpair_preference_dataset + +dataset = Dataset.from_dict({ + "chosen": [ + [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is blue."}], + [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sky."}], + ], + "rejected": [ + [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is green."}], + [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sea."}], + ], +}) + +dataset = dataset.map(extract_prompt) +dataset = unpair_preference_dataset(dataset) +``` + +```python +>>> dataset[0] +{'prompt': [{'role': 'user', 'content': 'What color is the sky?'}], + 'completion': [{'role': 'assistant', 'content': 'It is blue.'}], + 'label': True} +``` + +> [!WARNING] +> Keep in mind that the `"chosen"` and `"rejected"` completions in a preference dataset can be both good or bad. +> Before applying [`unpair_preference_dataset`], please ensure that all `"chosen"` completions can be labeled as good and all `"rejected"` completions as bad. +> This can be ensured by checking absolute rating of each completion, e.g. from a reward model. + +### From preference to language modeling dataset + +To convert a preference dataset into a language modeling dataset, remove the rejected, concatenate the prompt and the chosen into the `"text"` column. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["The sky is", "The sun is"], + "chosen": [" blue.", " in the sky."], + "rejected": [" green.", " in the sea."], +}) + +def concat_prompt_chosen(example): + return {"text": example["prompt"] + example["chosen"]} + +dataset = dataset.map(concat_prompt_chosen, remove_columns=["prompt", "chosen", "rejected"]) +``` + +```python +>>> dataset[0] +{'text': 'The sky is blue.'} +``` + +### From preference to prompt-completion dataset + +To convert a preference dataset into a prompt-completion dataset, remove the rejected, and rename the column `"chosen"` to `"completion"`. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["The sky is", "The sun is"], + "chosen": [" blue.", " in the sky."], + "rejected": [" green.", " in the sea."], +}) + +dataset = dataset.remove_columns("rejected").rename_column("chosen", "completion") +``` + +```python +>>> dataset[0] +{'prompt': 'The sky is', 'completion': ' blue.'} +``` + +### From preference to prompt-only dataset + +To convert a preference dataset into a prompt-only dataset, remove the rejected and the chosen. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["The sky is", "The sun is"], + "chosen": [" blue.", " in the sky."], + "rejected": [" green.", " in the sea."], +}) + +dataset = dataset.remove_columns(["chosen", "rejected"]) +``` + +```python +>>> dataset[0] +{'prompt': 'The sky is'} +``` + +### From explicit to implicit prompt preference dataset + +To convert a preference dataset with explicit prompt into a preference dataset with implicit prompt, concatenate the prompt to both chosen and rejected, and remove the prompt. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": [ + [{"role": "user", "content": "What color is the sky?"}], + [{"role": "user", "content": "Where is the sun?"}], + ], + "chosen": [ + [{"role": "assistant", "content": "It is blue."}], + [{"role": "assistant", "content": "In the sky."}], + ], + "rejected": [ + [{"role": "assistant", "content": "It is green."}], + [{"role": "assistant", "content": "In the sea."}], + ], +}) + +def concat_prompt_to_completions(example): + return {"chosen": example["prompt"] + example["chosen"], "rejected": example["prompt"] + example["rejected"]} + +dataset = dataset.map(concat_prompt_to_completions, remove_columns="prompt") +``` + +```python +>>> dataset[0] +{'chosen': [{'role': 'user', 'content': 'What color is the sky?'}, {'role': 'assistant', 'content': 'It is blue.'}], + 'rejected': [{'role': 'user', 'content': 'What color is the sky?'}, {'role': 'assistant', 'content': 'It is green.'}]} +``` + +### From preference to unpaired preference dataset + +To convert dataset into an unpaired preference dataset, unpair the dataset with [`unpair_preference_dataset`]. + +```python +from datasets import Dataset +from trl import unpair_preference_dataset + +dataset = Dataset.from_dict({ + "prompt": [ + [{"role": "user", "content": "What color is the sky?"}], + [{"role": "user", "content": "Where is the sun?"}], + ], + "chosen": [ + [{"role": "assistant", "content": "It is blue."}], + [{"role": "assistant", "content": "In the sky."}], + ], + "rejected": [ + [{"role": "assistant", "content": "It is green."}], + [{"role": "assistant", "content": "In the sea."}], + ], +}) + +dataset = unpair_preference_dataset(dataset) +``` + +```python +>>> dataset[0] +{'prompt': [{'role': 'user', 'content': 'What color is the sky?'}], + 'completion': [{'role': 'assistant', 'content': 'It is blue.'}], + 'label': True} +``` + +> [!WARNING] +> Keep in mind that the `"chosen"` and `"rejected"` completions in a preference dataset can be both good or bad. +> Before applying [`unpair_preference_dataset`], please ensure that all `"chosen"` completions can be labeled as good and all `"rejected"` completions as bad. +> This can be ensured by checking absolute rating of each completion, e.g. from a reward model. + +### From unpaired preference to language modeling dataset + +To convert an unpaired preference dataset into a language modeling dataset, concatenate prompts with good completions into the `"text"` column, and remove the prompt, completion and label columns. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["The sky is", "The sun is", "The sky is", "The sun is"], + "completion": [" blue.", " in the sky.", " green.", " in the sea."], + "label": [True, True, False, False], +}) + +def concatenate_prompt_completion(example): + return {"text": example["prompt"] + example["completion"]} + +dataset = dataset.filter(lambda x: x["label"]).map(concatenate_prompt_completion).remove_columns(["prompt", "completion", "label"]) +``` + +```python +>>> dataset[0] +{'text': 'The sky is blue.'} +``` + +### From unpaired preference to prompt-completion dataset + +To convert an unpaired preference dataset into a prompt-completion dataset, filter for good labels, then remove the label columns. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["The sky is", "The sun is", "The sky is", "The sun is"], + "completion": [" blue.", " in the sky.", " green.", " in the sea."], + "label": [True, True, False, False], +}) + +dataset = dataset.filter(lambda x: x["label"]).remove_columns(["label"]) +``` + +```python +>>> dataset[0] +{'prompt': 'The sky is', 'completion': ' blue.'} +``` + +### From unpaired preference to prompt-only dataset + +To convert an unpaired preference dataset into a prompt-only dataset, remove the completion and the label columns. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["The sky is", "The sun is", "The sky is", "The sun is"], + "completion": [" blue.", " in the sky.", " green.", " in the sea."], + "label": [True, True, False, False], +}) + +dataset = dataset.remove_columns(["completion", "label"]) +``` + +```python +>>> dataset[0] +{'prompt': 'The sky is'} +``` + +### From stepwise supervision to language modeling dataset + +To convert a stepwise supervision dataset into a language modeling dataset, concatenate prompts with good completions into the `"text"` column. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["Blue light", "Water"], + "completions": [[" scatters more in the atmosphere,", " so the sky is green."], + [" forms a less dense structure in ice,", " which causes it to expand when it freezes."]], + "labels": [[True, False], [True, True]], +}) + +def concatenate_prompt_completions(example): + completion = "".join(example["completions"]) + return {"text": example["prompt"] + completion} + +dataset = dataset.filter(lambda x: all(x["labels"])).map(concatenate_prompt_completions, remove_columns=["prompt", "completions", "labels"]) +``` + +```python +>>> dataset[0] +{'text': 'Blue light scatters more in the atmosphere, so the sky is green.'} +``` + +### From stepwise supervision to prompt-completion dataset + +To convert a stepwise supervision dataset into a prompt-completion dataset, join the good completions and remove the labels. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["Blue light", "Water"], + "completions": [[" scatters more in the atmosphere,", " so the sky is green."], + [" forms a less dense structure in ice,", " which causes it to expand when it freezes."]], + "labels": [[True, False], [True, True]], +}) + +def join_completions(example): + completion = "".join(example["completions"]) + return {"completion": completion} + +dataset = dataset.filter(lambda x: all(x["labels"])).map(join_completions, remove_columns=["completions", "labels"]) +``` + +```python +>>> dataset[0] +{'prompt': 'Blue light', 'completion': ' scatters more in the atmosphere, so the sky is green.'} +``` + +### From stepwise supervision to prompt-only dataset + +To convert a stepwise supervision dataset into a prompt-only dataset, remove the completions and the labels. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["Blue light", "Water"], + "completions": [[" scatters more in the atmosphere,", " so the sky is green."], + [" forms a less dense structure in ice,", " which causes it to expand when it freezes."]], + "labels": [[True, False], [True, True]], +}) + +dataset = dataset.remove_columns(["completions", "labels"]) +``` + +```python +>>> dataset[0] +{'prompt': 'Blue light'} +``` + +### From stepwise supervision to unpaired preference dataset + +To convert a stepwise supervision dataset into an unpaired preference dataset, join the completions and merge the labels. + +The method for merging the labels depends on the specific task. In this example, we use the logical AND operation. This means that if the step labels indicate the correctness of individual steps, the resulting label will reflect the correctness of the entire sequence. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["Blue light", "Water"], + "completions": [[" scatters more in the atmosphere,", " so the sky is green."], + [" forms a less dense structure in ice,", " which causes it to expand when it freezes."]], + "labels": [[True, False], [True, True]], +}) + +def merge_completions_and_labels(example): + return {"prompt": example["prompt"], "completion": "".join(example["completions"]), "label": all(example["labels"])} + +dataset = dataset.map(merge_completions_and_labels, remove_columns=["completions", "labels"]) +``` + +```python +>>> dataset[0] +{'prompt': 'Blue light', 'completion': ' scatters more in the atmosphere, so the sky is green.', 'label': False} +``` + +## Vision datasets + +Some trainers also support fine-tuning vision-language models (VLMs) using image-text pairs. In this scenario, it's recommended to use a conversational format, as each model handles image placeholders in text differently. + +A conversational vision dataset differs from a standard conversational dataset in two key ways: + +1. The dataset must contain the key `images` with the image data (as lists of PIL images) or `image` with a single PIL image. +2. The `"content"` field in messages must be a list of dictionaries, where each dictionary specifies the type of data: `"image"` or `"text"`. + +Example: + +```python +# Textual dataset: +"content": "What color is the sky?" + +# Vision dataset: +"content": [ + {"type": "image"}, + {"type": "text", "text": "What color is the sky in the image?"} +] +``` + +An example of a conversational vision dataset is the [openbmb/RLAIF-V-Dataset](https://huggingface.co/datasets/openbmb/RLAIF-V-Dataset). Below is an embedded view of the dataset's training data, allowing you to explore it directly: + + + +> [!NOTE] +> Mixing text-only and vision-language data in the dataset is possible, but it requires `transformers` version 4.57.0 or later. Example: +> +> ```python +> dataset = Dataset.from_dict({ +> "prompt": [ +> [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What color is the sky in the image?"}]}], +> [{"role": "user", "content": [{"type": "text", "text": "What is the capital of France?"}]}], +> ], +> "completion": [ +> [{"role": "assistant", "content": [{"type": "text", "text": "It is blue."}]}], +> [{"role": "assistant", "content": [{"type": "text", "text": "Paris."}]}], +> ], +> "images": [ +> [PIL.Image.open("path/to/sky_image1.png")], +> [], +> ], +> }) +> ``` diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/deepspeed_integration.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/deepspeed_integration.md new file mode 100644 index 0000000000000000000000000000000000000000..a605787972e3578949f820364be8e3d951657637 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/deepspeed_integration.md @@ -0,0 +1,36 @@ +# DeepSpeed Integration + +> [!WARNING] +> Section under construction. Feel free to contribute! + +TRL supports training with DeepSpeed, a library that implements advanced training optimization techniques. These include optimizer state partitioning, offloading, gradient partitioning, and more. + +DeepSpeed integrates the [Zero Redundancy Optimizer (ZeRO)](https://huggingface.co/papers/1910.02054), which allows to scale the model size proportional to the number of devices with sustained high efficiency. + +![ZeRO Stages](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/zero_stages.png) + +## Installation + +To use DeepSpeed with TRL, install it using the following command: + +```bash +pip install deepspeed +``` + +## Running Training Scripts with DeepSpeed + +No modifications to your training script are required. Simply run it with the DeepSpeed configuration file: + +```bash +accelerate launch --config_file train.py +``` + +We provide ready-to-use DeepSpeed configuration files in the [`examples/accelerate_configs`](https://github.com/huggingface/trl/tree/main/examples/accelerate_configs) directory. For example, to run training with ZeRO Stage 2, use the following command: + +```bash +accelerate launch --config_file examples/accelerate_configs/deepspeed_zero2.yaml train.py +``` + +## Additional Resources + +Consult the 🤗 Accelerate [documentation](https://huggingface.co/docs/accelerate/usage_guides/deepspeed) for more information about the DeepSpeed plugin. diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/distillation_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/distillation_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..c23e291a93dce020c7fa81f8215b7add5236fbd4 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/distillation_trainer.md @@ -0,0 +1,152 @@ +# Distillation Trainer + +## Overview + +The Distillation Trainer implements on-policy knowledge distillation as described in [On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes](https://huggingface.co/papers/2306.13649) by Rishabh Agarwal, Nino Vieillard, Yongchao Zhou, Piotr Stanczyk, Sabela Ramos, Matthieu Geist, and Olivier Bachem. + +> Knowledge distillation (KD) is widely used for compressing a teacher model to reduce its inference cost and memory footprint, by training a smaller student model. However, current KD methods for auto-regressive sequence models suffer from distribution mismatch between output sequences seen during training and those generated by the student during inference. To address this issue, we introduce Generalized Knowledge Distillation (GKD). Instead of solely relying on a fixed set of output sequences, GKD trains the student on its self-generated output sequences by leveraging feedback from the teacher on such sequences. Unlike supervised KD approaches, GKD also offers the flexibility to employ alternative loss functions between the student and teacher, which can be useful when the student lacks the expressivity to mimic the teacher's distribution. + +The `DistillationTrainer` is designed for distilling teacher models of all sizes into smaller students efficiently. It extends the ideas from the `GKDTrainer` with three key optimizations: + +1. **Generation buffer** – decouples the training microbatch size from the generation batch size, letting vLLM batch many prompts in a single call across gradient accumulation steps. This alone can speed up training by up to 40x. +2. **Teacher server support** – moves the teacher to an external vLLM server so it does not need to fit on the same GPUs as the student. +3. **Binary-encoded logprob payloads** – packs log-probabilities into base64-encoded NumPy arrays instead of nested JSON lists, shrinking transfer payloads by ~5x. + +> [!NOTE] +> The Distillation Trainer is currently part of the `trl.experimental` namespace. APIs may change without notice while the feature is iterated on. + +## Quick start + +```python +from datasets import load_dataset +from trl.experimental.distillation import DistillationConfig, DistillationTrainer + +# 1. Load dataset and format as prompt-only chat messages +dataset = load_dataset("openai/gsm8k", "main", split="train") +dataset = dataset.map( + lambda x: {"messages": [{"role": "user", "content": x["question"]}]}, + remove_columns=dataset.column_names, +) + +# 2. Configure distillation +config = DistillationConfig( + output_dir="results/distill-qwen-gsm8k", + num_train_epochs=1, + bf16=True, + save_strategy="no", + # Distillation + lmbda=1.0, # fully on-policy (student generates) + beta=1.0, # reverse KL + # Teacher + teacher_model_init_kwargs={"dtype": "bfloat16"}, +) + +# 3. Train +trainer = DistillationTrainer( + model="Qwen/Qwen2.5-1.5B-Instruct", + teacher_model="Qwen/Qwen2.5-7B-Instruct", + args=config, + train_dataset=dataset, +) +trainer.train() +trainer.save_model() +``` + +## Usage tips + +The [`experimental.distillation.DistillationTrainer`] needs three key parameters set via [`experimental.distillation.DistillationConfig`]: + +* `lmbda`: controls the student data fraction, i.e., the proportion of on-policy student-generated outputs. When `lmbda=0.0`, training is fully off-policy (dataset completions only). When `lmbda=1.0`, training is fully on-policy (student generates all completions). For values in between, each gradient accumulation slice is randomly assigned as on- or off-policy based on `lmbda`. +* `beta`: controls the interpolation in the Generalized Jensen-Shannon Divergence. When `beta=0.0` the loss approximates forward KL divergence, while `beta=1.0` approximates reverse KL divergence. Values in between interpolate. +* `loss_top_k`: number of top tokens to use for the KL/JSD loss. Set to `0` for exact full-vocabulary computation (local teacher only), or `> 0` for a top-k approximation. See more about top-k with external teacher server below. + +### On-policy vs. off-policy + +Setting `lmbda=1.0` (fully on-policy) generally outperforms off-policy distillation because the student learns from its own mistakes rather than imitating trajectories it may never produce. The generation buffer ensures on-policy training stays efficient: prompts across gradient accumulation steps are batched into a single vLLM call. + +### Using an external teacher server + +For teachers that do not fit on training GPUs (e.g., 100B+ parameters), host the teacher on a separate vLLM server and set `use_teacher_server=True` with `teacher_model_server_url`: + +```python +config = DistillationConfig( + output_dir="distilled-model", + use_teacher_server=True, + teacher_model_server_url="http://teacher-host:8000", + loss_top_k=1, # required with teacher server when beta > 0 + beta=1.0, + lmbda=1.0, +) + +trainer = DistillationTrainer( + model="Qwen/Qwen3-4B", + args=config, + train_dataset=dataset, +) +trainer.train() +``` + +When using the teacher server: +- `loss_top_k` must be `> 0` when `beta=0.0` (forward KL) +- `loss_top_k` must be exactly `1` when `beta > 0` (reverse KL or JSD) +- `reverse_kl_top_1_mode="argmax"` is not supported +- Liger kernel is not supported + +### Expected dataset type + +The dataset should be formatted as a [conversational](dataset_formats#conversational) [language modeling](dataset_formats#language-modeling) dataset: + +```python +{"messages": [{"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}]} +``` + +When using fully on-policy distillation (`lmbda=1.0`), the assistant turn can be omitted since the student will generate its own completions: + +```python +{"messages": [{"role": "user", "content": "What color is the sky?"}]} +``` + +## Example script + +Use [`examples/scripts/distillation.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/distillation.py) to launch distillation training from the command line. The script supports full training, mixed on/off-policy, and LoRA via the standard `ModelConfig` flags. + +```bash +# Full training (off-policy only, lmbda=0): +python examples/scripts/distillation.py \ + --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ + --teacher_model_name_or_path Qwen/Qwen2.5-1.5B-Instruct \ + --dataset_name trl-lib/chatbot_arena_completions \ + --learning_rate 2e-5 \ + --per_device_train_batch_size 4 \ + --gradient_accumulation_steps 8 \ + --lmbda 0.0 \ + --output_dir distilled-model \ + --num_train_epochs 1 +``` + +```bash +# Mixed on/off-policy (lmbda=0.5): +python examples/scripts/distillation.py \ + --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ + --teacher_model_name_or_path Qwen/Qwen2.5-1.5B-Instruct \ + --dataset_name trl-lib/chatbot_arena_completions \ + --learning_rate 2e-5 \ + --per_device_train_batch_size 4 \ + --gradient_accumulation_steps 8 \ + --lmbda 0.5 \ + --beta 0.5 \ + --output_dir distilled-model \ + --num_train_epochs 1 +``` + +## DistillationTrainer + +[[autodoc]] experimental.distillation.DistillationTrainer + - train + - save_model + - push_to_hub + +## DistillationConfig + +[[autodoc]] experimental.distillation.DistillationConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/distributing_training.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/distributing_training.md new file mode 100644 index 0000000000000000000000000000000000000000..b3d72fea50823581c0d110acd1b340d674166a8b --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/distributing_training.md @@ -0,0 +1,445 @@ +# Distributing Training + +> [!WARNING] +> Section under construction. Feel free to contribute! + +## Multi-GPU Training with TRL + +The trainers in TRL use [🤗 Accelerate](https://github.com/huggingface/accelerate) to enable distributed training across multiple GPUs or nodes. To do so, first create an [🤗 Accelerate](https://github.com/huggingface/accelerate) config file by running + +```bash +accelerate config +``` + +and answering the questions according to your multi-GPU / multi-node setup. You can then launch distributed training by running: + +```bash +accelerate launch train.py +``` + +We also provide config files in the [examples folder](https://github.com/huggingface/trl/tree/main/examples/accelerate_configs) that can be used as templates. To use these templates, simply pass the path to the config file when launching a job, e.g.: + +```shell +accelerate launch --config_file examples/accelerate_configs/multi_gpu.yaml train.py +``` + +This automatically distributes the workload across all available GPUs. + +Under the hood, [🤗 Accelerate](https://github.com/huggingface/accelerate) creates one model per GPU. Each process: + +- Processes its own batch of data +- Computes the loss and gradients for that batch +- Shares gradient updates across all GPUs + +![multi gpu](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/multi_gpu.png) + +The effective batch size is calculated as: + +$$ +\text{Batch Size} = \text{per\_device\_train\_batch\_size} \times \text{num\_devices} \times \text{gradient\_accumulation\_steps} +$$ + +To maintain a consistent batch size when scaling to multiple GPUs, make sure to update `per_device_train_batch_size` and `gradient_accumulation_steps` accordingly. + +Example, these configurations are equivalent, and should yield the same results: + +| Number of GPUs | Per device batch size | Gradient accumulation steps | Comments | +| --- | --- | --- | --- | +| 1 | 32 | 1 | Possibly high memory usage, but faster training | +| 1 | 4 | 8 | Lower memory usage, slower training | +| 8 | 4 | 1 | Multi-GPU to get the best of both worlds | + +> [!TIP] +> Having one model per GPU can lead to high memory usage, which may not be feasible for large models or low-memory GPUs. In such cases, you can leverage [DeepSpeed](https://github.com/deepspeedai/DeepSpeed), which provides optimizations like model sharding, Zero Redundancy Optimizer, mixed precision training, and offloading to CPU or NVMe. Check out our [DeepSpeed Integration](deepspeed_integration) guide for more details. + +## Sequence Parallelism for Long Context Training + +Sequence Parallelism (also called Context Parallelism) is a parallelization technique that enables training with longer sequences by splitting the sequence dimension across multiple GPUs. Each GPU processes a portion of the sequence, allowing you to train with sequences longer than what would fit on a single GPU's memory. + +> [!NOTE] +> **Terminology clarification:** This section describes parallelism techniques for splitting sequences to enable longer context training: +> - **Context Parallelism (CP)**: Splits sequences across GPUs (implemented as Ring Attention with FSDP2) +> - **Sequence Parallelism (SP)**: Another form of sequence splitting (implemented as ALST/Ulysses with DeepSpeed) +> +> Both CP and SP are different from traditional Sequence Parallelism used with Tensor Parallelism (TP+SP) to reduce activation memory. With the techniques here, parallelism dimensions multiply: `TP=2` and `CP=2` would require 4 GPUs (2×2), whereas traditional `TP+SP=2` only needs 2 GPUs as they share the same ranks. +> +> In Accelerate's `ParallelismConfig`: +> - Use `cp_size` with `cp_backend="torch"` for Ring Attention (FSDP2) +> - Use `sp_size` with `sp_backend="deepspeed"` for ALST/Ulysses (DeepSpeed) + +Sequence parallelism is particularly useful when: + +- You want to train with very long sequences (>32k tokens) +- Single GPU memory is insufficient for your desired sequence length +- You need to maintain sequence coherence across the full context + +### Available Implementations + +TRL supports two sequence parallelism implementations, each with different characteristics: + +1. **Ring Attention (FSDP2)** - Uses ring-based communication for memory-efficient processing of extremely long sequences +2. **ALST/Ulysses (DeepSpeed)** - Uses attention head parallelism for faster training with high-bandwidth interconnects + +> [!IMPORTANT] +> **Sequence Length Terminology:** When using Context Parallelism, the sequence is split across GPUs, introducing two concepts: +> - **Global sequence length**: The full sequence length before splitting across GPUs +> - **Micro sequence length**: The sequence length per GPU after splitting +> +> In TRL, `max_seq_length` (or `max_length`) refers to the **global sequence length**. The framework automatically handles splitting into micro sequences: +> - **Ring Attention (FSDP2)**: Uses `cp_size` to split sequences. With `max_seq_length=8192` and `cp_size=4`, each GPU processes 2048 tokens. +> - **ALST/Ulysses (DeepSpeed)**: Uses `sp_size` (with `sp_backend="deepspeed"`) to split sequences. With `max_seq_length=8192` and `sp_size=2`, each GPU processes 4096 tokens. +> +> The Trainer automatically accounts for context parallelism when calculating batch sizes and training metrics. + +### Choosing Between Ring Attention and Ulysses + +The comparison table below highlights the key differences between the two approaches: + +| Feature | Ring Attention (FSDP2) | ALST/Ulysses (DeepSpeed) | +|---------|----------|-------------------------| +| **Method** | Ring Self-Attention | Attention Head Parallelism | +| **Backend** | PyTorch FSDP2 | DeepSpeed ZeRO | +| **Attention** | SDPA only | Flash Attention 2 or SDPA | +| **Minimum Accelerate** | 1.11.0+ | 1.12.0+ | +| **Minimum DeepSpeed** | N/A | 0.18.1+ | +| **Sequence Divisibility** | `cp_size * 2` | `sp_size` | +| **Zero Stage** | N/A | ZeRO Stage 1/2/3 | + +**Ring Attention is better when:** +- You need to handle extremely long sequences (1M+ tokens) +- The model has limited attention heads (Ring Attention is not constrained by head count) +- You want flexibility in scaling to any sequence length +- Network topology is limited (Ring Attention works with simple P2P ring communication) + +**Ulysses is better when:** +- You have high-bandwidth, low-latency interconnects (NVLink, InfiniBand) +- The model has many attention heads that can be split across GPUs +- You want lower communication volume +- You want faster training speed for moderate sequence lengths (up to ~500k tokens) + +**Key Trade-offs:** +- **Communication Volume:** Ulysses has lower communication volume, making it more efficient with good interconnects. Ring Attention has higher communication volume but is more flexible with different network topologies. +- **Attention Head Constraints:** Ulysses is limited by the number of attention heads (requires `num_heads >= sp_size`). Ring Attention scales with sequence length regardless of model architecture. +- **Network Sensitivity:** Ulysses all-to-all communication is sensitive to network latency. Ring Attention uses P2P ring communication which is more tolerant of varying network conditions. + +For a detailed comparison, see the [Ulysses and Ring Attention blog post](https://huggingface.co/blog/exploding-gradients/ulysses-ring-attention). + +### Ring Attention Implementation (FSDP2) + +Ring Attention uses a ring-like communication pattern where each GPU processes a portion of the sequence and passes information to the next GPU in the ring. + +#### Requirements and Limitations + +1. **Accelerate 1.11.0 or higher** is required for Ring Attention / Context Parallelism support +2. **FSDP2 (PyTorch FSDP v2)** is required as the distributed training backend +3. **SDPA attention** - Flash Attention is currently not supported +4. **Sequence length divisibility** - sequences must be divisible by `cp_size * 2`. This is automatically handled using the `pad_to_multiple_of` parameter in the data collator. + +#### Configuration + +##### Accelerate Configuration + +Use one of the provided accelerate config files (e.g. [`context_parallel_2gpu.yaml`](https://github.com/huggingface/trl/blob/main/examples/accelerate_configs/context_parallel_2gpu.yaml) for 2 GPUs): + +```yaml +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: FSDP +downcast_bf16: 'no' +enable_cpu_affinity: false +fsdp_config: + fsdp_activation_checkpointing: true # Enable activation checkpointing for memory efficiency + fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP + fsdp_cpu_ram_efficient_loading: true + fsdp_offload_params: false + fsdp_reshard_after_forward: true + fsdp_state_dict_type: FULL_STATE_DICT + fsdp_version: 2 +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 2 # Number of GPUs +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false +parallelism_config: + parallelism_config_dp_replicate_size: 1 + parallelism_config_dp_shard_size: 1 + parallelism_config_tp_size: 1 + parallelism_config_cp_size: 2 # Context parallel size +``` + +##### Training Configuration + +```python +from trl import SFTConfig + +training_args = SFTConfig( + # required + pad_to_multiple_of=4, # ensures divisibility by cp_size * 2 + # to get the most out of CP + max_length=16384, # long sequence length + packing=True, # use packing to reduce padding + use_liger_kernel=True, # compatible with CP + gradient_checkpointing=False, # The activation_checkpointing in FSDP config and the gradient_checkpointing in training arg can't be set to True simultaneously + per_device_train_batch_size=1, + ... +) +``` + +Then, launch your training script with the appropriate accelerate config file: + +```bash +accelerate launch --config_file context_parallel_2gpu.yaml train.py +``` + +#### Best Practices + +1. **Use the `pad_to_multiple_of` parameter** - This is now the recommended way to ensure sequence length divisibility: + - For `cp_size=2`: use `pad_to_multiple_of=4` (since `cp_size * 2 = 4`) + - For `cp_size=4`: use `pad_to_multiple_of=8` (since `cp_size * 2 = 8`) + - The data collator automatically pads sequences to the required multiple, ensuring compatibility with CP + +2. **Use packing with padding** - The default BFD (Best Fit Decreasing) strategy works perfectly: + - Preserves sequence boundaries and maintains training quality + - Works seamlessly with both `padding_free=True` and standard padding modes + +3. **Combine with other memory optimizations** like Liger kernels, bfloat16, and gradient checkpointing + +4. **Start with smaller context parallel sizes** (2-4 GPUs) before scaling up + +5. **Monitor memory usage** across all GPUs to ensure balanced workload + +#### Benchmarking Ring Attention + +We benchmarked Ring Attention to highlight its potential improvements in training efficiency. +Our experiments were conducted using **1, 2, 4, and 8 H100 GPUs**, though the results can be extended to larger clusters with more nodes and GPUs. + +For the setup, we fine-tuned an **8B model** ([Qwen/Qwen3-8B](https://huggingface.co/Qwen/Qwen3-8B)) using the provided accelerate configuration +([`context_parallel_2gpu.yaml`](https://github.com/huggingface/trl/blob/main/examples/accelerate_configs/context_parallel_2gpu.yaml)). +We adjusted `num_processes` and `parallelism_config_cp_size` based on the number of GPUs for each run. +Training was performed with the [sft.py](https://github.com/huggingface/trl/blob/main/trl/scripts/sft.py) example script, combined with the parameters described above. + +The results below summarize the **maximum trainable sequence length** and **iterations per second** for different numbers of GPUs. A value marked as `OOM` indicates that the configuration ran out of memory and could not be trained. + +These results show that **Context Parallelism (CP) scales effectively with more GPUs**, enabling training on much longer sequences. With **8 GPUs**, context lengths of over **300k tokens** become feasible, unlocking training with extremely long contexts while maintaining reasonable throughput. + +
+ CP Max content length + CP seconds/iteration +
+ +> [!TIP] +> Accelerate also supports **N-Dimensional Parallelism (ND-parallelism)**, which enables you to combine different parallelization strategies to efficiently distribute model training across multiple GPUs. +> +> You can learn more and explore configuration examples in the [Accelerate ND-parallelism guide](https://github.com/huggingface/accelerate/blob/main/examples/torch_native_parallelism/README.md#nd-parallelism). + +### ALST/Ulysses Implementation (DeepSpeed) + +ALST (Arctic Long Sequence Training) / Ulysses uses attention head parallelism to split long sequences across GPUs, working with DeepSpeed's ZeRO optimizer. + +> [!NOTE] +> **Technical Note on Parallelism Configuration:** +> - **DeepSpeed ALST/Ulysses** uses `sp_size` with `sp_backend="deepspeed"` in both YAML and Python API +> - **Ring Attention (FSDP2)** uses `cp_size` with `cp_backend="torch"` +> +> The Trainer automatically accounts for both CP and SP when calculating effective batch sizes and training metrics. + +#### Requirements and Limitations + +1. **DeepSpeed 0.18.1 or higher** is required +2. **Accelerate 1.12.0 or higher** is required for ALST/Ulysses sequence parallelism support +3. **Attention implementation** - Flash Attention 2 recommended (clean output), SDPA works as fallback +4. **Sequence length divisibility** - sequences must be divisible by `sp_size`. Use `pad_to_multiple_of` in your training config. +5. **Parallelism configuration** - You must ensure `dp_replicate_size × dp_shard_size × sp_size = num_processes` + +#### Configuration + +##### Accelerate Configuration + +Use the provided accelerate config file ([`alst_ulysses_4gpu.yaml`](https://github.com/huggingface/trl/blob/main/examples/accelerate_configs/alst_ulysses_4gpu.yaml)): + +```yaml +compute_environment: LOCAL_MACHINE +debug: false +deepspeed_config: + zero_stage: 3 + seq_parallel_communication_data_type: bf16 +distributed_type: DEEPSPEED +mixed_precision: bf16 +num_machines: 1 +num_processes: 4 # Number of GPUs +parallelism_config: + parallelism_config_dp_replicate_size: 1 + parallelism_config_dp_shard_size: 2 # Enables 2D parallelism with SP + parallelism_config_tp_size: 1 + parallelism_config_sp_size: 2 # Sequence parallel size + parallelism_config_sp_backend: deepspeed + parallelism_config_sp_seq_length_is_variable: true + parallelism_config_sp_attn_implementation: flash_attention_2 +``` + +##### Training Configuration + +```python +from trl import SFTConfig + +training_args = SFTConfig( + # required + pad_to_multiple_of=2, # Must equal sp_size + # to get the most out of SP + max_length=4096, + packing=True, + attn_implementation="flash_attention_2", + per_device_train_batch_size=1, + ... +) +``` + +Then, launch your training script with the appropriate accelerate config file: + +```bash +accelerate launch --config_file examples/accelerate_configs/alst_ulysses_4gpu.yaml train.py +``` + +#### 2D Parallelism + +The 4 GPU configuration above automatically enables 2D parallelism by combining Data Parallelism (DP) with Sequence Parallelism (SP). With `sp_size=2` and `dp_shard_size=2`, the 4 GPUs are organized as: +- 2 sequence parallel groups (processing the same data split across sequences) +- 2 data parallel groups (processing different data) + +To adjust the parallelism for different GPU counts, modify the YAML config: + +| GPUs | sp_size | dp_shard_size | Use Case | YAML Changes | +|------|---------|---------------|----------|--------------| +| 4 | 2 | 2 | Balanced - longer sequences + more data | `num_processes: 4`, `sp_size: 2`, `dp_shard_size: 2` | +| 4 | 4 | 1 | Pure SP for maximum sequence length | `num_processes: 4`, `sp_size: 4`, `dp_shard_size: 1` | +| 8 | 2 | 4 | Large-scale training | `num_processes: 8`, `sp_size: 2`, `dp_shard_size: 4` | + +#### Best Practices + +1. **Use `pad_to_multiple_of`** to ensure sequences are divisible by `sp_size` +2. **Use Flash Attention 2** for clean output (SDPA works but shows packing warnings) +3. **Start with `sp_size=2`** before scaling to larger values +4. **Use DeepSpeed ZeRO Stage 3** for large models +5. **Combine with memory optimizations** like Liger kernels and gradient checkpointing +6. **Validate parallelism config**: Ensure `dp_replicate_size × dp_shard_size × sp_size = num_processes` + +#### Complete Example + +Here's how to run ALST/Ulysses training using the built-in [`sft.py`](https://github.com/huggingface/trl/blob/main/trl/scripts/sft.py) script with 4 GPUs: + +```bash +accelerate launch --config_file examples/accelerate_configs/alst_ulysses_4gpu.yaml \ + trl/scripts/sft.py \ + --model_name_or_path Qwen/Qwen2-0.5B \ + --dataset_name trl-lib/Capybara \ + --learning_rate 2e-4 \ + --max_steps 100 \ + --max_seq_length 4096 \ + --packing \ + --packing_strategy wrapped \ + --dtype bfloat16 \ + --attn_implementation flash_attention_2 \ + --output_dir output-alst-4gpu \ + --logging_steps 10 \ + --report_to trackio +``` + +This command automatically: +- Configures 2D parallelism (SP=2, DP=2) across 4 GPUs +- Uses Flash Attention 2 for clean training +- Enables packing with automatic padding to ensure sequence divisibility +- Leverages DeepSpeed ZeRO Stage 3 for memory efficiency + +### Further Reading + +#### General Resources +- [Hugging Face Blog: Understanding Ulysses and Ring Attention](https://huggingface.co/blog/exploding-gradients/ulysses-ring-attention) - Detailed comparison of Ring Attention vs Ulysses approaches +- [Accelerate: Context Parallelism Guide](https://huggingface.co/docs/accelerate/concept_guides/context_parallelism) +- [Hugging Face Blog: Enabling Long-Context Training with Sequence Parallelism in Axolotl](https://huggingface.co/blog/axolotl-ai-co/long-context-with-sequence-parallelism-in-axolotl) + +#### Ring Attention (FSDP2) +- [Ultrascale Playbook - Context Parallelism](https://huggingface.co/spaces/nanotron/ultrascale-playbook?section=context_parallelism) +- [Accelerate Example: 128k Sequence Length](https://github.com/huggingface/accelerate/blob/main/examples/torch_native_parallelism/README.md#context-parallelism-128k-sequence-length) +- [Accelerate ND-parallelism Guide](https://github.com/huggingface/accelerate/blob/main/examples/torch_native_parallelism/README.md#nd-parallelism) + +#### ALST/Ulysses (DeepSpeed) +- [DeepSpeed Sequence Parallelism Documentation](https://www.deepspeed.ai/tutorials/ds-sequence/) +- [Snowflake Engineering Blog: Arctic Long Sequence Training (ALST)](https://www.snowflake.com/en/engineering-blog/arctic-long-sequence-training-multi-million-token-ai/) + +## Multi-Node Training + +When a single machine doesn't have enough GPUs, TRL can scale training across multiple machines (nodes) using [🤗 Accelerate](https://huggingface.co/docs/accelerate/basic_tutorials/launch#multi-node-training). + +### Accelerate Configuration +Create an `accelerate` config file (e.g., `multi_node.yaml`) for multi-node training. Key fields: + +```yaml +compute_environment: LOCAL_MACHINE +distributed_type: MULTI_GPU +num_machines: 2 +machine_rank: 0 # 0 for main node, 1 for second node +main_process_ip: 10.0.0.1 # IP of rank 0 node +main_process_port: 29500 +num_processes: 16 # total processes across nodes +mixed_precision: bf16 +use_cpu: false +same_network: true +``` + +Adjust `num_processes` to match the total number of GPUs across all nodes. + +> [!NOTE] +> Replace `10.0.0.1` with the actual IP address of the rank 0 (main) node. + +### Launching + +#### Option 1: Manual Launch (Non-HPC) + +Run the following on each node manually: +```bash +# Node 0 (main node) +accelerate launch --config_file multi_node.yaml --machine_rank 0 train.py + +# Node 1 +accelerate launch --config_file multi_node.yaml --machine_rank 1 train.py +``` +#### Option 2: SLURM Launch (HPC Clusters) + +For clusters using SLURM job scheduler, create a job script (e.g., `slurm_job.sh`): +```bash +#!/bin/bash +#SBATCH --nodes=2 +#SBATCH --gpus-per-node=8 +#SBATCH --job-name=trl_multi + +srun accelerate launch --config_file multi_node.yaml train.py +``` + +Then submit the job: +```bash +sbatch slurm_job.sh +``` + +SLURM automatically distributes the training across all requested nodes and GPUs, and `srun` configures the necessary environment variables for multi-node communication. + +**Key SLURM directives:** +- `--nodes=2`: Request 2 compute nodes +- `--gpus-per-node=8`: Allocate 8 GPUs per node (16 total) +- `--job-name`: Label for tracking in the job queue + +You can combine multi-node with DeepSpeed by setting `distributed_type: DEEPSPEED` and adding a `deepspeed_config` block. See the [DeepSpeed integration guide](https://huggingface.co/docs/trl/en/deepspeed_integration). + +### Further Reading + +- [Accelerate: Launching Scripts](https://huggingface.co/docs/accelerate/basic_tutorials/launch) +- [Accelerate: Example Zoo](https://huggingface.co/docs/accelerate/usage_guides/training_zoo) +- [SLURM Workload Manager Documentation](https://slurm.schedmd.com/) - For cluster job scheduling + + + diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/dpo_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/dpo_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..3f33904d120ef1679ce4b9edc8fab130b223b8c2 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/dpo_trainer.md @@ -0,0 +1,296 @@ +# DPO Trainer + +[![All_models-DPO-blue](https://img.shields.io/badge/All_models-DPO-blue)](https://huggingface.co/models?other=dpo,trl) [![smol_course-Chapter_2-yellow](https://img.shields.io/badge/smol_course-Chapter_2-yellow)](https://github.com/huggingface/smol-course/tree/main/2_preference_alignment) + +## Overview + +TRL supports the Direct Preference Optimization (DPO) Trainer for training language models, as described in the paper [Direct Preference Optimization: Your Language Model is Secretly a Reward Model](https://huggingface.co/papers/2305.18290) by [Rafael Rafailov](https://huggingface.co/rmrafailov), Archit Sharma, Eric Mitchell, [Stefano Ermon](https://huggingface.co/ermonste), [Christopher D. Manning](https://huggingface.co/manning), [Chelsea Finn](https://huggingface.co/cbfinn). + +The abstract from the paper is the following: + +> While large-scale unsupervised language models (LMs) learn broad world knowledge and some reasoning skills, achieving precise control of their behavior is difficult due to the completely unsupervised nature of their training. Existing methods for gaining such steerability collect human labels of the relative quality of model generations and fine-tune the unsupervised LM to align with these preferences, often with reinforcement learning from human feedback (RLHF). However, RLHF is a complex and often unstable procedure, first fitting a reward model that reflects the human preferences, and then fine-tuning the large unsupervised LM using reinforcement learning to maximize this estimated reward without drifting too far from the original model. In this paper we introduce a new parameterization of the reward model in RLHF that enables extraction of the corresponding optimal policy in closed form, allowing us to solve the standard RLHF problem with only a simple classification loss. The resulting algorithm, which we call Direct Preference Optimization (DPO), is stable, performant, and computationally lightweight, eliminating the need for sampling from the LM during fine-tuning or performing significant hyperparameter tuning. Our experiments show that DPO can fine-tune LMs to align with human preferences as well as or better than existing methods. Notably, fine-tuning with DPO exceeds PPO-based RLHF in ability to control sentiment of generations, and matches or improves response quality in summarization and single-turn dialogue while being substantially simpler to implement and train. + +This post-training method was contributed by [Kashif Rasul](https://huggingface.co/kashif) and later refactored by [Quentin Gallouédec](https://huggingface.co/qgallouedec). + +## Quick start + +This example demonstrates how to train a language model using the [`DPOTrainer`] from TRL. We train a [Qwen 3 0.6B](https://huggingface.co/Qwen/Qwen3-0.6B) model on the [UltraFeedback dataset](https://huggingface.co/datasets/openbmb/UltraFeedback). + +```python +from trl import DPOTrainer +from datasets import load_dataset + +trainer = DPOTrainer( + model="Qwen/Qwen3-0.6B", + train_dataset=load_dataset("trl-lib/ultrafeedback_binarized", split="train"), +) +trainer.train() +``` + + + +## Expected dataset type and format + +DPO requires a [preference](dataset_formats#preference) dataset. The [`DPOTrainer`] is compatible with both [standard](dataset_formats#standard) and [conversational](dataset_formats#conversational) dataset formats. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset. + +```python +# Standard format +## Explicit prompt (recommended) +preference_example = {"prompt": "The sky is", "chosen": " blue.", "rejected": " green."} +# Implicit prompt +preference_example = {"chosen": "The sky is blue.", "rejected": "The sky is green."} + +# Conversational format +## Explicit prompt (recommended) +preference_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}], + "chosen": [{"role": "assistant", "content": "It is blue."}], + "rejected": [{"role": "assistant", "content": "It is green."}]} +## Implicit prompt +preference_example = {"chosen": [{"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}], + "rejected": [{"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is green."}]} +``` + +If your dataset is not in one of these formats, you can preprocess it to convert it into the expected format. Here is an example with the [Vezora/Code-Preference-Pairs](https://huggingface.co/datasets/Vezora/Code-Preference-Pairs) dataset: + +```python +from datasets import load_dataset + +dataset = load_dataset("Vezora/Code-Preference-Pairs") + + +def preprocess_function(example): + return { + "prompt": [{"role": "user", "content": example["input"]}], + "chosen": [{"role": "assistant", "content": example["accepted"]}], + "rejected": [{"role": "assistant", "content": example["rejected"]}], + } + + +dataset = dataset.map(preprocess_function, remove_columns=["instruction", "input", "accepted", "ID"]) +print(next(iter(dataset["train"]))) +``` + +```json +{ + "prompt": [{"role": "user", "content": "Create a nested loop to print every combination of numbers [...]"}], + "chosen": [{"role": "assistant", "content": "Here is an example of a nested loop in Python [...]"}], + "rejected": [{"role": "assistant", "content": "Here is an example of a nested loop in Python [...]"}], +} +``` + +## Looking deeper into the DPO method + +Direct Preference Optimization (DPO) is a training method designed to align a language model with preference data. Instead of supervised input–output pairs, the model is trained on pairs of completions to the same prompt, where one completion is preferred over the other. The objective directly optimizes the model to widen the margin between the log-likelihoods of preferred and dispreferred completions, relative to a reference model, without requiring an explicit reward model. In practice, this is typically achieved by suppressing the likelihood of dispreferred completions rather than by increasing the likelihood of preferred ones. + +This section breaks down how DPO works in practice, covering the key steps: **preprocessing** and **loss computation**. + +### Preprocessing and tokenization + +During training, each example is expected to contain a prompt along with a preferred (`chosen`) and a dispreferred (`rejected`) completion. For more details on the expected formats, see [Dataset formats](dataset_formats). +The [`DPOTrainer`] tokenizes each input using the model's tokenizer. + +### Computing the loss + +![dpo_figure](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/dpo_figure.png) + +The loss used in DPO is defined as follows: +$$ +\mathcal{L}_{\mathrm{DPO}}(\theta) = -\mathbb{E}_{(x,y^{+},y^{-})}\!\left[\log \sigma\!\left(\beta\Big(\log\frac{\pi_{\theta}(y^{+}\!\mid x)}{\pi_{\mathrm{ref}}(y^{+}\!\mid x)}-\log \frac{\pi_{\theta}(y^{-}\!\mid x)}{\pi_{\mathrm{ref}}(y^{-}\!\mid x)}\Big)\right)\right] +$$ + +where \\( x \\) is the prompt, \\( y^+ \\) is the preferred completion and \\( y^- \\) is the dispreferred completion. \\( \pi_{\theta} \\) is the policy model being trained, \\( \pi_{\mathrm{ref}} \\) is the reference model, \\( \sigma \\) is the sigmoid function, and \\( \beta > 0 \\) is a hyperparameter that controls the strength of the preference signal. + +#### Loss Types + +Several formulations of the objective have been proposed in the literature. Initially, the objective of DPO was defined as presented above. + +| `loss_type=` | Description | +| --- | --- | +| `"sigmoid"` (default) | Given the preference data, we can fit a binary classifier according to the Bradley-Terry model and in fact the [DPO](https://huggingface.co/papers/2305.18290) authors propose the sigmoid loss on the normalized likelihood via the `logsigmoid` to fit a logistic regression. | +| `"hinge"` | The [RSO](https://huggingface.co/papers/2309.06657) authors propose to use a hinge loss on the normalized likelihood from the [SLiC](https://huggingface.co/papers/2305.10425) paper. In this case, the `beta` is the reciprocal of the margin. | +| `"ipo"` | The [IPO](https://huggingface.co/papers/2310.12036) authors argue the logit transform can overfit and propose the identity transform to optimize preferences directly; TRL exposes this as `loss_type="ipo"`. | +| `"exo_pair"` | The [EXO](https://huggingface.co/papers/2402.00856) authors propose reverse-KL preference optimization. `label_smoothing` must be strictly greater than `0.0`; a recommended value is `1e-3` (see Eq. 16 for the simplified pairwise variant). The full method uses `K>2` SFT completions and approaches PPO as `K` grows. | +| `"nca_pair"` | The [NCA](https://huggingface.co/papers/2402.05369) authors shows that NCA optimizes the absolute likelihood for each response rather than the relative likelihood. | +| `"robust"` | The [Robust DPO](https://huggingface.co/papers/2403.00409) authors propose an unbiased DPO loss under noisy preferences. Use `label_smoothing` in [`DPOConfig`] to model label-flip probability; valid values are in the range `[0.0, 0.5)`. | +| `"bco_pair"` | The [BCO](https://huggingface.co/papers/2404.04656) authors train a binary classifier whose logit serves as a reward so that the classifier maps {prompt, chosen completion} pairs to 1 and {prompt, rejected completion} pairs to 0. For unpaired data, we recommend the dedicated [`experimental.bco.BCOTrainer`]. | +| `"sppo_hard"` | The [SPPO](https://huggingface.co/papers/2405.00675) authors claim that SPPO is capable of solving the Nash equilibrium iteratively by pushing the chosen rewards to be as large as 1/2 and the rejected rewards to be as small as -1/2 and can alleviate data sparsity issues. The implementation approximates this algorithm by employing hard label probabilities, assigning 1 to the winner and 0 to the loser. | +| `"aot"` or `loss_type="aot_unpaired"` | The [AOT](https://huggingface.co/papers/2406.05882) authors propose Distributional Preference Alignment via Optimal Transport. `loss_type="aot"` is for paired data; `loss_type="aot_unpaired"` is for unpaired data. Both enforce stochastic dominance via sorted quantiles; larger per-GPU batch sizes help. | +| `"apo_zero"` or `loss_type="apo_down"` | The [APO](https://huggingface.co/papers/2408.06266) method introduces an anchored objective. `apo_zero` boosts winners and downweights losers (useful when the model underperforms the winners). `apo_down` downweights both, with stronger pressure on losers (useful when the model already outperforms winners). | +| `"discopop"` | The [DiscoPOP](https://huggingface.co/papers/2406.08414) paper uses LLMs to discover more efficient offline preference optimization losses. In the paper the proposed DiscoPOP loss (which is a log-ratio modulated loss) outperformed other optimization losses on different tasks (IMDb positive text generation, Reddit TLDR summarization, and Alpaca Eval 2.0). | +| `"sft"` | SFT (Supervised Fine-Tuning) loss is the negative log likelihood loss, used to train the model to generate preferred responses. | +| `"sigmoid_norm"` | The [SimPO](https://huggingface.co/papers/2405.14734) authors address the length-bias in the original sigmoid loss by normalizing by the number of non-mask tokens; TRL exposes this as `loss_type="sigmoid_norm"`. | + +## Logged metrics + +While training and evaluating we record the following reward metrics: + +* `global_step`: The total number of optimizer steps taken so far. +* `epoch`: The current epoch number, based on dataset iteration. +* `num_tokens`: The total number of tokens processed so far. +* `loss`: The average cross-entropy loss computed over non-masked tokens in the current logging interval. +* `entropy`: The average entropy of the model's predicted token distribution over non-masked tokens. +* `mean_token_accuracy`: The proportion of non-masked tokens for which the model’s top-1 prediction matches the token from the chosen completion. +* `learning_rate`: The current learning rate, which may change dynamically if a scheduler is used. +* `grad_norm`: The L2 norm of the gradients, computed before gradient clipping. +* `logits/chosen`: The average logit values assigned by the model to the tokens in the chosen completion. +* `logits/rejected`: The average logit values assigned by the model to the tokens in the rejected completion. +* `logps/chosen`: The average log-probability assigned by the model to the tokens in the chosen completion. +* `logps/rejected`: The average log-probability assigned by the model to the tokens in the rejected completion. +* `rewards/chosen`: The average implicit reward computed for the chosen completion, computed as \\( \beta \log \frac{\pi_{\theta}(y^{+}\!\mid x)}{\pi_{\mathrm{ref}}(y^{+}\!\mid x)} \\). +* `rewards/rejected`: The average implicit reward computed for the rejected completion, computed as \\( \beta \log \frac{\pi_{\theta}(y^{-}\!\mid x)}{\pi_{\mathrm{ref}}(y^{-}\!\mid x)} \\). +* `rewards/margins`: The average implicit reward margin between the chosen and rejected completions. +* `rewards/accuracies`: The proportion of examples where the implicit reward for the chosen completion is higher than that for the rejected completion. + +## Customization + +### Compatibility and constraints + +Some argument combinations are intentionally restricted in the current [`DPOTrainer`] implementation: + +* `use_weighting=True` is not supported with `loss_type="aot"` or `loss_type="aot_unpaired"`. +* With `use_liger_kernel=True`: + * only a single `loss_type` is supported, + * `compute_metrics` is not supported, + * `precompute_ref_log_probs=True` is not supported. +* `sync_ref_model=True` is not supported when training with PEFT models that do not keep a standalone `ref_model`. +* `sync_ref_model=True` cannot be combined with `precompute_ref_log_probs=True`. +* `precompute_ref_log_probs=True` is not supported with `IterableDataset` (train or eval). + +### Multi-loss combinations + +The DPO trainer supports combining multiple loss functions with different weights, enabling more sophisticated optimization strategies. This is particularly useful for implementing algorithms like MPO (Mixed Preference Optimization). MPO is a training approach that combines multiple optimization objectives, as described in the paper [Enhancing the Reasoning Ability of Multimodal Large Language Models via Mixed Preference Optimization](https://huggingface.co/papers/2411.10442). + +To combine multiple losses, specify the loss types and corresponding weights as lists: + +```python +# MPO: Combines DPO (sigmoid) for preference and BCO (bco_pair) for quality +training_args = DPOConfig( + loss_type=["sigmoid", "bco_pair", "sft"], # loss types to combine + loss_weights=[0.8, 0.2, 1.0] # corresponding weights, as used in the MPO paper +) +``` + +### Model initialization + +You can directly pass the kwargs of the [`~transformers.AutoModelForCausalLM.from_pretrained()`] method to the [`DPOConfig`]. For example, if you want to load a model in a different precision, analogous to + +```python +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-0.6B", dtype=torch.bfloat16) +``` + +you can do so by passing the `model_init_kwargs={"dtype": torch.bfloat16}` argument to the [`DPOConfig`]. + +```python +from trl import DPOConfig + +training_args = DPOConfig( + model_init_kwargs={"dtype": torch.bfloat16}, +) +``` + +Note that all keyword arguments of [`~transformers.AutoModelForCausalLM.from_pretrained()`] are supported. + +### Train adapters with PEFT + +We support tight integration with 🤗 PEFT library, allowing any user to conveniently train adapters and share them on the Hub, rather than training the entire model. + +```python +from datasets import load_dataset +from trl import DPOTrainer +from peft import LoraConfig + +dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") + +trainer = DPOTrainer( + "Qwen/Qwen3-0.6B", + train_dataset=dataset, + peft_config=LoraConfig(), +) + +trainer.train() +``` + +You can also continue training your [`~peft.PeftModel`]. For that, first load a `PeftModel` outside [`DPOTrainer`] and pass it directly to the trainer without the `peft_config` argument being passed. + +```python +from datasets import load_dataset +from trl import DPOTrainer +from peft import AutoPeftModelForCausalLM + +model = AutoPeftModelForCausalLM.from_pretrained("trl-lib/Qwen3-4B-LoRA", is_trainable=True) +dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") + +trainer = DPOTrainer( + model=model, + train_dataset=dataset, +) + +trainer.train() +``` + +> [!TIP] +> When training adapters, you typically use a higher learning rate (≈1e‑5) than full fine-tuning since only new parameters are being learned. +> +> ```python +> DPOConfig(learning_rate=1e-5, ...) +> ``` + +### Train with Liger Kernel + +Liger Kernel is a collection of Triton kernels for LLM training that boosts multi-GPU throughput by 20%, cuts memory use by 60% (enabling up to 4× longer context), and works seamlessly with tools like FlashAttention, PyTorch FSDP, and DeepSpeed. For more information, see [Liger Kernel Integration](liger_kernel_integration). + +### Rapid Experimentation for DPO + +RapidFire AI is an open-source experimentation engine that sits on top of TRL and lets you launch multiple DPO configurations at once, even on a single GPU. Instead of trying configurations sequentially, RapidFire lets you **see all their learning curves earlier, stop underperforming runs, and clone promising ones with new settings in flight** without restarting. For more information, see [RapidFire AI Integration](rapidfire_integration). + +### Train with Unsloth + +Unsloth is an open‑source framework for fine‑tuning and reinforcement learning that trains LLMs (like Llama, Mistral, Gemma, DeepSeek, and more) up to 2× faster with up to 70% less VRAM, while providing a streamlined, Hugging Face–compatible workflow for training, evaluation, and deployment. For more information, see [Unsloth Integration](unsloth_integration). + +## Tool Calling with DPO + +The [`DPOTrainer`] fully supports fine-tuning models with _tool calling_ capabilities. In this case, each dataset example should include: + +* The conversation messages (prompt, chosen and rejected), including any tool calls (`tool_calls`) and tool responses (`tool` role messages) +* The list of available tools in the `tools` column, typically provided as JSON schemas + +For details on the expected dataset structure, see the [Dataset Format — Tool Calling](dataset_formats#tool-calling) section. + +## Training Vision Language Models + +[`DPOTrainer`] fully supports training Vision-Language Models (VLMs). To train a VLM, provide a dataset with either an `image` column (single image per sample) or an `images` column (list of images per sample). For more information on the expected dataset structure, see the [Dataset Format — Vision Dataset](dataset_formats#vision-dataset) section. +An example of such a dataset is the [RLAIF-V Dataset](https://huggingface.co/datasets/HuggingFaceH4/rlaif-v_formatted) dataset. + +```python +from trl import DPOConfig, DPOTrainer +from datasets import load_dataset + +trainer = DPOTrainer( + model="Qwen/Qwen2.5-VL-3B-Instruct", + args=DPOConfig(max_length=None), + train_dataset=load_dataset("HuggingFaceH4/rlaif-v_formatted", split="train"), +) +trainer.train() +``` + +> [!TIP] +> For VLMs, truncating may remove image tokens, leading to errors during training. To avoid this, set `max_length=None` in the [`DPOConfig`]. This allows the model to process the full sequence length without truncating image tokens. +> +> ```python +> DPOConfig(max_length=None, ...) +> ``` +> +> Only use `max_length` when you've verified that truncation won't remove image tokens for the entire dataset. + +## DPOTrainer + +[[autodoc]] DPOTrainer + - train + - save_model + - push_to_hub + +## DPOConfig + +[[autodoc]] DPOConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/example_overview.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/example_overview.md new file mode 100644 index 0000000000000000000000000000000000000000..570f8830d4f893596489a4b9dbedc8f7c41fe649 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/example_overview.md @@ -0,0 +1,131 @@ +# Examples + +This directory contains a collection of examples that demonstrate how to use the TRL library for various applications. We provide both **scripts** for advanced use cases and **notebooks** for an easy start and interactive experimentation. + +The notebooks are self-contained and can run on **free Colab**, while the scripts can run on **single GPU, multi-GPU, or DeepSpeed** setups. + +**Getting Started** + +Install TRL and additional dependencies as follows: + +```bash +pip install --upgrade trl[quantization] +``` + +Check for additional optional dependencies [here](https://github.com/huggingface/trl/blob/main/pyproject.toml). + +For scripts, you will also need an 🤗 Accelerate config (recommended for multi-gpu settings): + +```bash +accelerate config # will prompt you to define the training configuration +``` + +This allows you to run scripts with `accelerate launch` in single or multi-GPU settings. + +## Notebooks + +These notebooks are easier to run and are designed for quick experimentation with TRL. The list of notebooks can be found in the [`trl/examples/notebooks/`](https://github.com/huggingface/trl/tree/main/examples/notebooks/) directory. + + +| Notebook | Description | Open in Colab | +|----------|-------------|---------------| +| [`grpo_trl_lora_qlora.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/grpo_trl_lora_qlora.ipynb) | GRPO using QLoRA on free Colab | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/grpo_trl_lora_qlora.ipynb) | +| [`grpo_agent.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/grpo_agent.ipynb) | GRPO for agent training | Not available due to OOM with Colab GPUs | +| [`grpo_rnj_1_instruct.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/grpo_rnj_1_instruct.ipynb) | GRPO rnj-1-instruct with QLoRA using TRL on Colab to add reasoning capabilities | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/grpo_rnj_1_instruct.ipynb) | +| [`sft_ministral3_vl.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/sft_ministral3_vl.ipynb) | Supervised Fine-Tuning (SFT) Ministral 3 with QLoRA using TRL on free Colab | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/sft_ministral3_vl.ipynb) | +| [`grpo_ministral3_vl.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/grpo_ministral3_vl.ipynb) | GRPO Ministral 3 with QLoRA using TRL on free Colab | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/grpo_ministral3_vl.ipynb) | +| [`sft_nemotron_3.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/sft_nemotron_3.ipynb) | SFT with LoRA on NVIDIA Nemotron 3 models | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/sft_nemotron_3.ipynb) | +| [`sft_trl_lora_qlora.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/sft_trl_lora_qlora.ipynb) | Supervised Fine-Tuning (SFT) using QLoRA on free Colab | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/sft_trl_lora_qlora.ipynb) | +| [`sft_qwen_vl.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/sft_qwen_vl.ipynb) | Supervised Fine-Tuning (SFT) Qwen3-VL with QLoRA using TRL on free Colab | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/sft_qwen_vl.ipynb) | +| [`sft_tool_calling.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/sft_tool_calling.ipynb) | Teaching tool calling to a model without native tool-calling support using SFT with QLoRA | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/sft_tool_calling.ipynb) | +| [`grpo_qwen3_vl.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/grpo_qwen3_vl.ipynb) | GRPO Qwen3-VL with QLoRA using TRL on free Colab | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/grpo_qwen3_vl.ipynb) | + +### OpenEnv Notebooks + +These notebooks demonstrate how to train models with [OpenEnv](openenv) environments using [`GRPOTrainer`]'s `environment_factory`. The BrowserGym notebook uses the lower-level `rollout_func` API instead. See the [OpenEnv Integration](openenv) guide for more details. + +| Notebook | Description | Open in Colab | +|----------|-------------|---------------| +| [`openenv_wordle_grpo.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/openenv_wordle_grpo.ipynb) | GRPO to play Wordle on an OpenEnv environment | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/openenv_wordle_grpo.ipynb) | +| [`openenv_sudoku_grpo.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/openenv_sudoku_grpo.ipynb) | GRPO to play Sudoku on an OpenEnv environment | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/openenv_sudoku_grpo.ipynb) | +| [`grpo_functiongemma_browsergym_openenv.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/grpo_functiongemma_browsergym_openenv.ipynb) | GRPO on FunctionGemma in the BrowserGym environment | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/grpo_functiongemma_browsergym_openenv.ipynb) | + +## Scripts + +Scripts are maintained in the [`trl/scripts`](https://github.com/huggingface/trl/blob/main/trl/scripts) and [`examples/scripts`](https://github.com/huggingface/trl/blob/main/examples/scripts) directories. They show how to use different trainers such as [`SFTTrainer`], [`PPOTrainer`], [`DPOTrainer`], [`GRPOTrainer`], and more. + +| File | Description | +| --- | --- | +| [`examples/scripts/bco.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/bco.py) | This script shows how to use the [`experimental.kto.KTOTrainer`] with the BCO loss to fine-tune a model to increase instruction-following, truthfulness, honesty, and helpfulness using the [openbmb/UltraFeedback](https://huggingface.co/datasets/openbmb/UltraFeedback) dataset. | +| [`examples/scripts/cpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/cpo.py) | This script shows how to use the [`experimental.cpo.CPOTrainer`] to fine-tune a model to increase helpfulness and harmlessness using the [Anthropic/hh-rlhf](https://huggingface.co/datasets/Anthropic/hh-rlhf) dataset. | +| [`examples/scripts/distillation.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/distillation.py) | This script shows how to use the [`experimental.distillation.DistillationTrainer`] to distill a teacher model into a student, supporting full training, mixed on/off-policy, and LoRA. | +| [`trl/scripts/dpo.py`](https://github.com/huggingface/trl/blob/main/trl/scripts/dpo.py) | This script shows how to use the [`DPOTrainer`] to fine-tune a model. | +| [`examples/scripts/dpo_vlm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/dpo_vlm.py) | This script shows how to use the [`DPOTrainer`] to fine-tune a Vision Language Model to reduce hallucinations using the [openbmb/RLAIF-V-Dataset](https://huggingface.co/datasets/openbmb/RLAIF-V-Dataset) dataset. | +| [`examples/scripts/gkd.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/gkd.py) | This script shows how to use the [`experimental.gkd.GKDTrainer`] to fine-tune a model. | +| [`examples/scripts/gold.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/gold.py) | This script shows how to use the [`experimental.gold.GOLDTrainer`] to fine-tune a model with online distillation from a teacher model. | +| [`trl/scripts/grpo.py`](https://github.com/huggingface/trl/blob/main/trl/scripts/grpo.py) | This script shows how to use the [`GRPOTrainer`] to fine-tune a model. | +| [`trl/scripts/grpo_agent.py`](https://github.com/huggingface/trl/blob/main/trl/scripts/grpo_agent.py) | This script shows how to use the [`GRPOTrainer`] to fine-tune a model to enable agentic usage. | +| [`examples/scripts/grpo_vlm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/grpo_vlm.py) | This script shows how to use the [`GRPOTrainer`] to fine-tune a multimodal model for reasoning using the [lmms-lab/multimodal-open-r1-8k-verified](https://huggingface.co/datasets/lmms-lab/multimodal-open-r1-8k-verified) dataset. | +| [`examples/scripts/grpo_continuous_batching.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/grpo_continuous_batching.py) | This script shows how to use the [`GRPOTrainer`] with transformers' continuous batching engine for faster generation on large batches with variable completion lengths. | +| [`examples/scripts/gspo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/gspo.py) | This script shows how to use GSPO via the [`GRPOTrainer`] to fine-tune model for reasoning using the [AI-MO/NuminaMath-TIR](https://huggingface.co/datasets/AI-MO/NuminaMath-TIR) dataset. | +| [`examples/scripts/gspo_vlm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/gspo_vlm.py) | This script shows how to use GSPO via the [`GRPOTrainer`] to fine-tune a multimodal model for reasoning using the [lmms-lab/multimodal-open-r1-8k-verified](https://huggingface.co/datasets/lmms-lab/multimodal-open-r1-8k-verified) dataset. | +| [`examples/scripts/kto.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/kto.py) | This script shows how to use the [`experimental.kto.KTOTrainer`] to fine-tune a model. | +| [`examples/scripts/mpo_vlm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/mpo_vlm.py) | This script shows how to use MPO via the [`DPOTrainer`] to align a model based on preferences using the [HuggingFaceH4/rlaif-v_formatted](https://huggingface.co/datasets/HuggingFaceH4/rlaif-v_formatted) dataset and a set of loss weights with weights. | +| [`examples/scripts/nash_md.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/nash_md.py) | This script shows how to use the [`experimental.nash_md.NashMDTrainer`] to fine-tune a model. | +| [`examples/scripts/online_dpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/online_dpo.py) | This script shows how to use the [`experimental.online_dpo.OnlineDPOTrainer`] to fine-tune a model. | +| [`examples/scripts/online_dpo_vlm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/online_dpo_vlm.py) | This script shows how to use the [`experimental.online_dpo.OnlineDPOTrainer`] to fine-tune a Vision Language Model. | +| [`examples/scripts/orpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/orpo.py) | This script shows how to use the [`experimental.orpo.ORPOTrainer`] to fine-tune a model to increase helpfulness and harmlessness using the [Anthropic/hh-rlhf](https://huggingface.co/datasets/Anthropic/hh-rlhf) dataset. | +| [`examples/scripts/harbor/data_agent.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/harbor/data_agent.py) | This script shows how to use the [`GRPOTrainer`] to train a model against a Harbor task suite, with a pluggable base agent (`bash` / `jupyter` / `terminal_notes` harnesses under `examples/scripts/harbor/harnesses/`). See the [Harbor Integration](harbor) guide for setup and usage. | +| [`examples/scripts/openreward/seta.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/openreward/seta.py) | This script shows how to use the [`GRPOTrainer`] to train a model against the SETA ORS environment on the openreward.ai catalog. See the [OpenReward Integration](openreward) guide for setup and usage. | +| [`examples/scripts/ppo/ppo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/ppo/ppo.py) | This script shows how to use the [`experimental.ppo.PPOTrainer`] to fine-tune a model to improve its ability to continue text with positive sentiment or physically descriptive language. | +| [`examples/scripts/ppo/ppo_tldr.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/ppo/ppo_tldr.py) | This script shows how to use the [`experimental.ppo.PPOTrainer`] to fine-tune a model to improve its ability to generate TL;DR summaries. | +| [`examples/scripts/prm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/prm.py) | This script shows how to use the [`experimental.prm.PRMTrainer`] to fine-tune a Process-supervised Reward Model (PRM). | +| [`examples/scripts/reward_modeling.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/reward_modeling.py) | This script shows how to use the [`RewardTrainer`] to train an Outcome Reward Model (ORM) on your own dataset. | +| [`examples/scripts/rloo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/rloo.py) | This script shows how to use the [`RLOOTrainer`] to fine-tune a model to improve its ability to solve math questions. | +| [`examples/scripts/sdft.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/sdft.py) | This script shows how to use the [`experimental.sdft.SDFTTrainer`] for self-distillation fine-tuning (SDFT). | +| [`examples/scripts/sdpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/sdpo.py) | This script shows how to use the [`experimental.sdpo.SDPOTrainer`] to fine-tune a model with verifiable math rewards and optional environment feedback using the [openai/gsm8k](https://huggingface.co/datasets/openai/gsm8k) dataset. | +| [`trl/scripts/sft.py`](https://github.com/huggingface/trl/blob/main/trl/scripts/sft.py) | This script shows how to use the [`SFTTrainer`] to fine-tune a model. | +| [`examples/scripts/sft_gemma3.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/sft_gemma3.py) | This script shows how to use the [`SFTTrainer`] to fine-tune a Gemma 3 model. | +| [`examples/scripts/sft_nemotron_3.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/sft_nemotron_3.py) | This script shows how to use the [`SFTTrainer`] to fine-tune an NVIDIA Nemotron 3 model. | +| [`examples/scripts/sft_tiny_aya_tool_calling.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/sft_tiny_aya_tool_calling.py) | This script shows how to use the [`SFTTrainer`] to teach tool calling to a model without native tool-calling support using the [bebechien/SimpleToolCalling](https://huggingface.co/datasets/bebechien/SimpleToolCalling) dataset. | +| [`examples/scripts/sft_video_llm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/sft_video_llm.py) | This script shows how to use the [`SFTTrainer`] to fine-tune a Video Language Model. | +| [`examples/scripts/sft_vlm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/sft_vlm.py) | This script shows how to use the [`SFTTrainer`] to fine-tune a Vision Language Model in a chat setting. The script has only been tested with [LLaVA 1.5](https://huggingface.co/llava-hf/llava-1.5-7b-hf), [LLaVA 1.6](https://huggingface.co/llava-hf/llava-v1.6-mistral-7b-hf), and [Llama-3.2-11B-Vision-Instruct](https://huggingface.co/meta-llama/Llama-3.2-11B-Vision-Instruct) models, so users may see unexpected behaviour in other model architectures. | +| [`examples/scripts/sft_vlm_gemma3.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/sft_vlm_gemma3.py) | This script shows how to use the [`SFTTrainer`] to fine-tune a Gemma 3 model on vision to text tasks. | +| [`examples/scripts/sft_vlm_smol_vlm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/sft_vlm_smol_vlm.py) | This script shows how to use the [`SFTTrainer`] to fine-tune a SmolVLM model. | +| [`examples/scripts/ssd.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/ssd.py) | This script shows how to use the [`experimental.ssd.SSDTrainer`] for Simple Self-Distillation (SSD) on code generation. | +| [`examples/scripts/ssd_eval.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/ssd_eval.py) | This script evaluates SSD-trained checkpoints on LiveCodeBench with vLLM and the official `codegen_metrics` (pass@k). | +| [`examples/scripts/tpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/tpo.py) | This script shows how to use the [`experimental.tpo.TPOTrainer`] for Triple Preference Optimization (TPO) using the [tpo-alignment/triple-preference-ultrafeedback-40K](https://huggingface.co/datasets/tpo-alignment/triple-preference-ultrafeedback-40K) dataset. | +| [`examples/scripts/xpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/xpo.py) | This script shows how to use the [`experimental.xpo.XPOTrainer`] to fine-tune a model. | + +### OpenEnv Scripts + +These scripts demonstrate how to train models with [OpenEnv](openenv) environments using [`GRPOTrainer`]'s `environment_factory`. See the [OpenEnv Integration](openenv) guide for more details. + +| File | Description | +| --- | --- | +| [`examples/scripts/openenv/echo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/openenv/echo.py) | GRPO training with the Echo environment (minimal example). | +| [`examples/scripts/openenv/wordle.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/openenv/wordle.py) | GRPO training with the Wordle (TextArena) environment. | +| [`examples/scripts/openenv/catch.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/openenv/catch.py) | GRPO training with the Catch (OpenSpiel) environment. | +| [`examples/scripts/openenv/sudoku.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/openenv/sudoku.py) | GRPO training with the Sudoku environment. | +| [`examples/scripts/openenv/multi_env.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/openenv/multi_env.py) | Multi-environment GRPO training: Wordle + Catch in the same training run. | +| [`examples/scripts/openenv/browsergym.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/openenv/browsergym.py) | GRPO training with the BrowserGym environment for VLMs. | +| [`examples/scripts/openenv/browsergym_llm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/openenv/browsergym_llm.py) | GRPO training with the BrowserGym environment for LLMs. | +| [`examples/scripts/openenv/carla.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/openenv/carla.py) | GRPO training with the CARLA environment for autonomous driving. | +| [`examples/scripts/openenv/carla_vlm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/openenv/carla_vlm.py) | GRPO training with CARLA for VLMs with multimodal tool responses (camera images). | +| [`examples/scripts/openenv/carla_vlm_gemma.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/openenv/carla_vlm_gemma.py) | GRPO training with CARLA for Gemma 4 with multimodal tool responses (camera images). | + +## Distributed Training (for scripts) + +You can run scripts on multiple GPUs with 🤗 Accelerate: + +```shell +accelerate launch --config_file=examples/accelerate_configs/multi_gpu.yaml --num_processes {NUM_GPUS} path_to_script.py --all_arguments_of_the_script +``` + +For DeepSpeed ZeRO-{1,2,3}: + +```shell +accelerate launch --config_file=examples/accelerate_configs/deepspeed_zero{1,2,3}.yaml --num_processes {NUM_GPUS} path_to_script.py --all_arguments_of_the_script +``` + +Adjust `NUM_GPUS` and `--all_arguments_of_the_script` as needed. diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/experimental_overview.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/experimental_overview.md new file mode 100644 index 0000000000000000000000000000000000000000..af0bf3e3cf23e14f1042629ad54c875a57175344 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/experimental_overview.md @@ -0,0 +1,31 @@ +# Experimental + +This directory contains a minimal, clearly separated space for fast iteration on new ideas. + +> [!WARNING] +> **Stability contract:** Anything under `trl.experimental` may change or be removed in *any* release (including patch versions) without prior deprecation. Do not rely on these APIs for production workloads. + +## Promotion Path (Simple) + +1. **Prototype outside the main repo:** Start development in your own fork or a separate repository to iterate quickly. +2. **Experimental inclusion:** Once it’s ready for early users, move the idea into `trl.experimental.`. +3. **Improve:** Add tests, a short doc/example, and demonstrate the usage. +4. **Promote:** Once the API proves stable and there is clear interest or adoption from the community, move it into `trl.` (stable module). + +## FAQ + +**Why not just use branches?** +Because branches are not shipped to users; experimental code inside the package lets early adopters try things and give feedback. + +**Can these APIs change or vanish without warning?** +Yes. Anything inside `trl.experimental` can change or disappear in *any* release. + +**Should I use this in production?** +Only if you are fine with updating your code quickly when things change. + +**Will maintainers promptly fix issues in `trl.experimental`?** +Not necessarily. The experimental module is a playground for new ideas, and maintainers may not prioritize bug fixes or feature requests there. Issues may remain unresolved until (or unless) the feature graduates to the stable API. + +**How to silence the runtime notice?** + +Use: `export TRL_EXPERIMENTAL_SILENCE=1`. diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/gfpo.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/gfpo.md new file mode 100644 index 0000000000000000000000000000000000000000..fac77c9d1f092d6ef17af7262951d5d29799446b --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/gfpo.md @@ -0,0 +1,50 @@ +# GFPO + +This feature implements the GFPO algorithm to enforce concise reasoning in the model's output generation, as proposed in the paper [Sample More to Think Less: Group Filtered Policy Optimization for Concise Reasoning](https://huggingface.co/papers/2508.09726). + +## Usage + +To activate GFPO in [`GFPOTrainer`]: + +- set `num_remains_in_group` in [`GFPOConfig`] +- define a group filter function and set it to `group_filter_func` in [`GFPOTrainer`]. `group_filter_func` will score the `num_generations` completions and The GFPOTrainer filters groups according to their scores to get top `num_remains_in_group` completions as a new group. Model will be trained on the filtered group. + +```python +# train_gfpo.py +from trl.experimental.gfpo import GFPOConfig, GFPOTrainer + +# dummy group filter to scores the completions based on its indice in group +class GroupFilter: + def __call__(self, group_completions, group_rewards, **kwargs): + group_scores = [] + for completions, rewards in zip(group_completions, group_rewards): + scores = [float(i) for i in range(len(completions))] + group_scores.append(scores) + return group_scores + +training_args = GFPOConfig( + output_dir="Qwen3-0.6B-GFPO", + per_device_train_batch_size=4, + num_remains_in_group=2, + bf16=True, +) +trainer = GFPOTrainer( + model="Qwen/Qwen3-0.6B", + reward_funcs=..., + train_dataset=..., + args=training_args, + group_filter_func=GroupFilter(), +) +trainer.train() +``` + +## GFPOTrainer + +[[autodoc]] experimental.gfpo.GFPOTrainer + - train + - save_model + - push_to_hub + +## GFPOConfig + +[[autodoc]] experimental.gfpo.GFPOConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/gkd_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/gkd_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..b703a1712b900cb3ba1003bf3863261b3526523b --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/gkd_trainer.md @@ -0,0 +1,99 @@ +# Generalized Knowledge Distillation Trainer + +[![model badge](https://img.shields.io/badge/All_models-GKD-blue)](https://huggingface.co/models?other=gkd,trl) + +## Overview + +Generalized Knowledge Distillation (GKD) was proposed in [On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes](https://huggingface.co/papers/2306.13649) by Rishabh Agarwal, Nino Vieillard, Yongchao Zhou, Piotr Stanczyk, Sabela Ramos, Matthieu Geist, and Olivier Bachem. + +The abstract from the paper is the following: + +> Knowledge distillation (KD) is widely used for compressing a teacher model to reduce its inference cost and memory footprint, by training a smaller student model. However, current KD methods for auto-regressive sequence models suffer from distribution mismatch between output sequences seen during training and those generated by the student during inference. To address this issue, we introduce Generalized Knowledge Distillation (GKD). Instead of solely relying on a fixed set of output sequences, GKD trains the student on its self-generated output sequences by leveraging feedback from the teacher on such sequences. Unlike supervised KD approaches, GKD also offers the flexibility to employ alternative loss functions between the student and teacher, which can be useful when the student lacks the expressivity to mimic the teacher's distribution. Furthermore, GKD facilitates the seamless integration of distillation with RL fine-tuning (RLHF). We demonstrate the efficacy of GKD for distilling auto-regressive language models on summarization, translation, and arithmetic reasoning tasks, and task-agnostic distillation for instruction-tuning. + +The key aspects of GKD are: + +1. It addresses the train-inference distribution mismatch in auto-regressive sequence models by training the student model on its self-generated output sequences. +2. GKD allows flexibility in choosing different divergence measures between student and teacher models via the generalized Jensen-Shannon Divergence (JSD), which can be useful when the student lacks the capacity to fully mimic the teacher. + +This post-training method was contributed by [Kashif Rasul](https://huggingface.co/kashif) and [Lewis Tunstall](https://huggingface.co/lewtun). + +## Usage tips + +The [`experimental.gkd.GKDTrainer`] is a wrapper around the [`SFTTrainer`] class that takes in a teacher model argument. It needs three parameters to be set via the [`experimental.gkd.GKDConfig`] namely: + +* `lmbda`: controls the student data fraction, i.e., the proportion of on-policy student-generated outputs. When `lmbda=0.0`, the loss reduces to supervised JSD where the student is trained with the token-level probabilities of the teacher. When `lmbda=1.0`, the loss reduces to on-policy JSD, where the student generates output sequences and token-specific feedback on these sequences from the teacher. For values in between [0, 1] it is random between the two based on the `lmbda` value for each batch. +* `seq_kd`: controls whether to perform Sequence-Level KD (can be viewed as supervised FT on teacher-generated out). When `seq_kd=True` and `lmbda=0.0`, the loss reduces to supervised JSD, where the teacher generates output sequences and the student receives token-specific feedback on these sequences from the teacher. +* `beta`: controls the interpolation in the generalized Jensen-Shannon Divergence. When `beta=0.0` the loss approximates forward KL divergence, while for `beta=1.0` the loss approximates reverse KL divergence. For values in between [0, 1] it interpolates between the two. + +The authors find that on-policy data (high `lmbda`) performs better and the optimal `beta` varied depending on the task and evaluation method. + +> [!WARNING] +> Make sure that `attn_implementation="kernels-community/flash-attn2"` when training [Gemma models](https://huggingface.co/models?other=gemma2). Otherwise you will encounter NaNs in the logits due to the [soft capping technique](https://huggingface.co/blog/gemma2#soft-capping-and-attention-implementations) adopted by this architecture. + +The basic API is as follows: + +```python +from datasets import Dataset +from transformers import AutoModelForCausalLM, AutoTokenizer +from trl.experimental.gkd import GKDConfig, GKDTrainer + +NUM_DUMMY_SAMPLES = 100 + +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +# The model to optimise +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +# The teacher model to calculate the KL divergence against +teacher_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-1.5B-Instruct") + +train_dataset = Dataset.from_dict( + { + "messages": [ + [ + {"role": "user", "content": "Hi, how are you?"}, + {"role": "assistant", "content": "I'm great thanks"}, + ] + ] + * NUM_DUMMY_SAMPLES + } +) +eval_dataset = Dataset.from_dict( + { + "messages": [ + [ + {"role": "user", "content": "What colour is the sky?"}, + {"role": "assistant", "content": "The sky is blue"}, + ] + ] + * NUM_DUMMY_SAMPLES + } +) + +training_args = GKDConfig(output_dir="gkd-model", per_device_train_batch_size=1) +trainer = GKDTrainer( + model=model, + teacher_model=teacher_model, + args=training_args, + processing_class=tokenizer, + train_dataset=train_dataset, + eval_dataset=eval_dataset, +) +trainer.train() +``` + +### Expected dataset type + +The dataset should be formatted as a list of "messages" where each message is a list of dictionaries with the following keys: + +* `role`: either `system`, `assistant` or `user` +* `content`: the message content + +## GKDTrainer + +[[autodoc]] experimental.gkd.GKDTrainer + - train + - save_model + - push_to_hub + +## GKDConfig + +[[autodoc]] experimental.gkd.GKDConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/gmpo.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/gmpo.md new file mode 100644 index 0000000000000000000000000000000000000000..ede3363fe71b5ccf497e59aaf91ba8b832483880 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/gmpo.md @@ -0,0 +1,36 @@ +# GMPO + +In the paper [Geometric-Mean Policy Optimization](https://huggingface.co/papers/2507.20673), the authors propose a GRPO variant that maximizes the *geometric* mean of the token-level importance ratios instead of the arithmetic mean. Because the geometric mean is far less sensitive to outlier ratios, the policy update is more stable and tolerates a much wider clipping range. Clipping is applied per token, in log space, and one-sided per the advantage sign (the standard PPO trust region) — crucially, *before* the geometric mean is taken. + +To use GMPO, you can use the [`GMPOTrainer`] class in `trl.experimental.gmpo`. + +## Usage + +```python +from trl.experimental.gmpo import GMPOConfig, GMPOTrainer + +training_args = GMPOConfig( + epsilon=0.4, # log-space clip range -> ratios clipped to (exp(-0.4), exp(0.4)); paper, Sec. 4 + beta=0.0, +) +trainer = GMPOTrainer( + model="Qwen/Qwen3-0.6B", + reward_funcs=..., + train_dataset=..., + args=training_args, +) +trainer.train() +``` + +In GMPO, clipping is applied to the per-token *log*-importance ratios (i.e. in log space) before the geometric mean is taken, so `epsilon` and `epsilon_high` are expressed in log space: the effective ratio clipping range is `(exp(-epsilon), exp(epsilon_high))`. The paper recommends a markedly wider range than GRPO/DAPO, `(exp(-0.4), exp(0.4))`, to encourage exploration. + +## GMPOTrainer + +[[autodoc]] experimental.gmpo.GMPOTrainer + - train + - save_model + - push_to_hub + +## GMPOConfig + +[[autodoc]] experimental.gmpo.GMPOConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/gold_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/gold_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..ff50a558fc5c6c7272e85e3442f628233ef0e007 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/gold_trainer.md @@ -0,0 +1,190 @@ +# General Online Logit Distillation (GOLD) Trainer + +[![All_models-GOLD-blue](https://img.shields.io/badge/All_models-GOLD-blue)](https://huggingface.co/models?other=sft,gold) + +## Overview + +General Online Logit Distillation (GOLD) is an extension of Universal Logit Distillation (ULD) that supports +student/teacher pairs with different tokenizers. It aligns the textual spans produced by both tokenizers and merges the +associated logits so no completion tokens are dropped. This enables cross-tokenizer knowledge distillation, including +mixed model families (for example, LLaMA students with Qwen teachers). + +Key capabilities: + +1. **Cross-tokenizer alignment** – GOLD incrementally decodes the student and teacher tokens, groups passages with the same visible text, and merges probabilities inside each group. This guarantees loss terms are computed over the full completion even when token boundaries differ. +2. **Hybrid ULD loss** – when `uld_use_hybrid_loss` is enabled, GOLD compares exact vocabulary matches directly and falls back to the original sorted-probability ULD loss for unmatched tokens. This improves stability for students whose vocabularies only partially overlap with the teacher. +3. **Seamless integration with GKD** – GOLD inherits the on-policy vs. off-policy scheduling from the [`experimental.gkd.GKDTrainer`], so you can combine sequence-level KD, generalized JSD, and cross-tokenizer distillation in a single training run. + +> [!NOTE] +> GOLD is currently part of the `trl.experimental` namespace. APIs may change without notice while the feature is iterated on. + +## Usage tips + +The [`GOLDTrainer`] subclasses [`SFTTrainer`] and accepts the same datasets as other TRL trainers (lists of ChatML style +messages). Important configuration flags on [`GOLDConfig`] include: + +* `use_uld_loss` – toggles Universal Logit Distillation. Set this to `True` for cross-tokenizer setups. +* `teacher_tokenizer_name_or_path` – required when `use_uld_loss=True`; GOLD uses the teacher tokenizer to align tokens. +* `uld_use_hybrid_loss`, `uld_hybrid_matched_weight`, `uld_hybrid_unmatched_weight` – enables and weights the hybrid + matched/unmatched loss. +* `beta`, `lmbda`, `seq_kd` – inherited from [`experimental.gkd.GKDConfig`], controlling the generalized JSD interpolation and on-policy + sampling ratio. +* `num_generations`, `generation_batch_size` – control buffered rollout generation across gradient accumulation windows. + `generation_batch_size` is the number of unique prompts per worker per optimizer step. +* `model_revision` – controls which student model revision GOLD loads for training and generation. + +A minimal end-to-end example: + +```python +from datasets import load_dataset +from trl.experimental.gold import GOLDConfig, GOLDTrainer + +train_dataset = load_dataset( + "HuggingFaceTB/OpenR1-Math-220k-default-verified", + "all", + split="train[:1024]", +) + +trainer = GOLDTrainer( + model="meta-llama/Llama-3.2-1B-Instruct", + teacher_model="Qwen/Qwen2.5-0.5B-Instruct", + args=GOLDConfig(output_dir="gold-model", use_uld_loss=True, teacher_tokenizer_name_or_path="Qwen/Qwen2.5-0.5B-Instruct"), + train_dataset=train_dataset, +) +trainer.train() +``` + +For quick-start workflows you can rely on string identifiers as shown above—the trainer will load the model and tokenizer for you. Explicitly instantiating `AutoModelForCausalLM`, `AutoTokenizer`, or populating `GOLDConfig` is recommended only for advanced use cases where you need fine-grained control over initialization. + +A more explicit setup might look like this when you need to customise model loading, tokenizer settings, or training arguments: + +```python +from datasets import load_dataset +from trl.experimental.gold import GOLDConfig, GOLDTrainer +from transformers import AutoModelForCausalLM, AutoTokenizer + +student_name = "meta-llama/Llama-3.2-1B-Instruct" +teacher_name = "Qwen/Qwen2.5-0.5B-Instruct" + +tokenizer = AutoTokenizer.from_pretrained(student_name) +if tokenizer.pad_token is None: + tokenizer.pad_token = tokenizer.eos_token + +model = AutoModelForCausalLM.from_pretrained(student_name) +teacher_model = AutoModelForCausalLM.from_pretrained(teacher_name) + +train_dataset = load_dataset( + "HuggingFaceTB/Countdown-Task-GOLD", + "verified_Qwen2.5-0.5B-Instruct", + split="train", +) + +training_args = GOLDConfig( + output_dir="gold-model", + per_device_train_batch_size=1, + teacher_model_name_or_path=teacher_name, + teacher_tokenizer_name_or_path=teacher_name, + use_uld_loss=True, + uld_use_hybrid_loss=True, +) + +trainer = GOLDTrainer( + model=model, + teacher_model=teacher_model, + args=training_args, + processing_class=tokenizer, + train_dataset=train_dataset, +) +trainer.train() +``` + +> [!NOTE] +> GOLD buffers one full optimizer-window generation batch (`per_device_train_batch_size * gradient_accumulation_steps`) +> and reuses it across accumulation steps. If the final batch is undersized, GOLD warns and drops that last batch +> (`Dropping last batch due to unexpected batch size`). Set `dataloader_drop_last=True` to avoid this warning. + +### Expected dataset type + +GOLD requires a [conversational](dataset_formats#conversational) [language modeling](dataset_formats#language-modeling) dataset, e.g.: + +```python +{"messages": [{"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}]} +``` + +`GOLDTrainer` keeps the raw messages so the ChatML collator can construct prompts and completions with the correct +boundaries. + +## How Token Merging Works + +When student and teacher use different tokenizers, the same text may be split differently: + +- **Student**: `"Hugging Face"` → 1 token +- **Teacher**: `"Hugging"`, `" Face"` → 2 tokens + +GOLD aligns these sequences and merges the teacher's multi-token probabilities into a single distribution that can be compared with the student's single-token distribution. + +### Probability Merging + +For a teacher sequence of tokens `[token₀, token₁, ..., tokenₖ]` that maps to a single student token, GOLD computes: + +``` +P_merged(y) = P(y | context) × P(token₁ | token₀, context) × ... × P(tokenₖ | ..., context) +``` + +where: +- `P(y | context)` is the marginal probability distribution over all vocabulary tokens at the first position +- `P(tokenᵢ | ..., context)` are **scalar** conditional probabilities of the actual tokens that were generated + +**Key insight**: Only the conditional probabilities of the **actual continuation tokens** are extracted as scalars. The full marginal distribution at the first position is then scaled by multiplying these scalar probabilities. + +This ensures: +1. **Correct joint probability** for the actual generated sequence (by the chain rule) +2. **Reasonable approximation** for counterfactual tokens (scaled by the same continuation likelihood) +3. **Unnormalized distributions** that preserve the correct relative probabilities for ULD loss computation + +### Example + +Given: +``` +P(x₀): ["HF": 0.6, "is": 0.3, "cool": 0.1] +P(x₁ | "HF"): ["HF": 0.05, "is": 0.9, "cool": 0.05] +``` + +If tokens 0 and 1 are merged, and the actual sequence was `["HF", "is"]`: +``` +P_merged("HF") = 0.6 × 0.9 = 0.54 ✓ (correct joint probability) +P_merged("is") = 0.3 × 0.9 = 0.27 +P_merged("cool") = 0.1 × 0.9 = 0.09 +``` + +The merged distribution is unnormalized (sums to 0.81), but this is intentional and correct for ULD loss computation, which uses sorting and L1 distance. + +## Example script + +Use [`examples/scripts/gold.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/gold.py) to launch GOLD training from the command line. The script supports full training and LoRA via the standard `ModelConfig` flags. + +```bash +python examples/scripts/gold.py \ + --model_name_or_path meta-llama/Llama-3.2-1B-Instruct \ + --teacher_model_name_or_path Qwen/Qwen2-1.5B-Instruct \ + --dataset_name trl-lib/chatbot_arena_completions \ + --learning_rate 2e-5 \ + --per_device_train_batch_size 4 \ + --gradient_accumulation_steps 8 \ + --output_dir gold-model \ + --num_train_epochs 1 \ + --push_to_hub +``` + +## GOLDTrainer + +[[autodoc]] experimental.gold.GOLDTrainer + - train + - generate_on_policy_outputs + - save_model + - push_to_hub + +## GOLDConfig + +[[autodoc]] experimental.gold.GOLDConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/grpo_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/grpo_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..0621d5ee689e5c053829ee47be1de634489ccd2a --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/grpo_trainer.md @@ -0,0 +1,872 @@ +# GRPO Trainer + +[![model badge](https://img.shields.io/badge/All_models-GRPO-blue)](https://huggingface.co/models?other=grpo,trl) + +## Overview + +TRL supports the GRPO Trainer for training language models, as described in the paper [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models](https://huggingface.co/papers/2402.03300) by [Zhihong Shao](https://huggingface.co/syhia), [Peiyi Wang](https://huggingface.co/peiyiwang89), [Qihao Zhu](https://huggingface.co/zqh11), Runxin Xu, [Junxiao Song](https://huggingface.co/haha-point), Mingchuan Zhang, Y. K. Li, Y. Wu, [Daya Guo](https://huggingface.co/guoday). + +The abstract from the paper is the following: + +> Mathematical reasoning poses a significant challenge for language models due to its complex and structured nature. In this paper, we introduce DeepSeekMath 7B, which continues pre-training DeepSeek-Coder-Base-v1.5 7B with 120B math-related tokens sourced from Common Crawl, together with natural language and code data. DeepSeekMath 7B has achieved an impressive score of 51.7% on the competition-level MATH benchmark without relying on external toolkits and voting techniques, approaching the performance level of Gemini-Ultra and GPT-4. Self-consistency over 64 samples from DeepSeekMath 7B achieves 60.9% on MATH. The mathematical reasoning capability of DeepSeekMath is attributed to two key factors: First, we harness the significant potential of publicly available web data through a meticulously engineered data selection pipeline. Second, we introduce Group Relative Policy Optimization (GRPO), a variant of Proximal Policy Optimization (PPO), that enhances mathematical reasoning abilities while concurrently optimizing the memory usage of PPO. + +This post-training method was contributed by [Quentin Gallouédec](https://huggingface.co/qgallouedec). + +## Quick start + +This example demonstrates how to train a model using the GRPO method. We train a [Qwen2.5 0.5B Instruct model](https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct) with the prompts from the [DeepMath-103K dataset](https://huggingface.co/datasets/trl-lib/DeepMath-103K). You can view the data in the dataset here: + + + +Below is the script to train the model. + +```python +# train_grpo.py +from datasets import load_dataset +from trl import GRPOTrainer +from trl.rewards import accuracy_reward + +dataset = load_dataset("trl-lib/DeepMath-103K", split="train") + +trainer = GRPOTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", + reward_funcs=accuracy_reward, + train_dataset=dataset, +) +trainer.train() +``` + +Execute the script using the following command: + +```bash +accelerate launch train_grpo.py +``` + +Distributed across 8 GPUs, the training takes approximately 1 day. + +![GRPO curves](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/grpo_curves.png) + +> **Note:** The reward curves above were generated with `Qwen/Qwen2-0.5B-Instruct`. Results with `Qwen/Qwen2.5-0.5B-Instruct` will be qualitatively similar. + +## Looking deeper into the GRPO method + +GRPO is an online learning algorithm, meaning it improves iteratively by using the data generated by the trained model itself during training. The intuition behind GRPO objective is to maximize the advantage of the generated completions, while ensuring that the model remains close to the reference policy. To understand how GRPO works, it can be broken down into four main steps: **Generating completions**, **computing the advantage**, **estimating the KL divergence**, and **computing the loss**. + +![GRPO visual](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/grpo_visual.png) + +### Generating completions + +At each training step, we sample a batch of prompts and generate a set of \\( G \\) completions for each prompt (denoted as \\( o_i \\)). + +### Computing the advantage + +For each of the \\( G \\) sequences, we compute the reward using a reward model or reward function. To align with the comparative nature of reward models—typically trained on datasets of comparisons between outputs for the same question—the advantage is calculated to reflect these relative comparisons. It is normalized as follows: + +$$\hat{A}_{i,t} = \frac{r_i - \text{mean}(\mathbf{r})}{\text{std}(\mathbf{r})}$$ + +This approach gives the method its name: **Group Relative Policy Optimization (GRPO)**. + +> [!TIP] +> It was shown in the paper [Understanding R1-Zero-Like Training: A Critical Perspective](https://huggingface.co/papers/2503.20783) that scaling by \\( \text{std}(\mathbf{r}) \\) may cause a question-level difficulty bias. You can disable this scaling by setting `scale_rewards=False` in [`GRPOConfig`]. +> Note that turning off std-based scaling also removes variance normalization, so update magnitudes depend directly on the raw reward scale and batch composition. + +> [!TIP] +> As shown in [Part I: Tricks or Traps? A Deep Dive into RL for LLM Reasoning (Lite PPO)](https://huggingface.co/papers/2508.08221), calculating the mean at the local (group) level and the standard deviation at the global (batch) level enables more robust reward shaping. You can use this scaling strategy by setting `scale_rewards="batch"` in [`GRPOConfig`]. + +### Estimating the KL divergence + +KL divergence is estimated using the approximator introduced by [Schulman et al. (2020)](http://joschu.net/blog/kl-approx.html). The approximator is defined as follows: + +$$\mathbb{D}_{\text{KL}}\left[\pi_\theta \|\pi_{\text{ref}}\right] = \frac{\pi_{\text{ref}}(o_{i,t} \mid q, o_{i, [!TIP] +> Note that compared to the original formulation in [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models](https://huggingface.co/papers/2402.03300), we don't scale by \\( \frac{1}{|o_i|} \\) because it was shown in the paper [Understanding R1-Zero-Like Training: A Critical Perspective](https://huggingface.co/papers/2503.20783) that this introduces a response-level length bias. More details in [loss types](#loss-types). + +> [!TIP] +> Note that compared to the original formulation in [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models](https://huggingface.co/papers/2402.03300), we use \\( \beta = 0.0 \\) by default, meaning that the KL divergence term is not used. This choice is motivated by several recent studies (e.g., [Open-Reasoner-Zero: An Open Source Approach to Scaling Up Reinforcement Learning on the Base Model](https://huggingface.co/papers/2503.24290)) which have shown that the KL divergence term is not essential for training with GRPO. As a result, it has become common practice to exclude it (e.g. [Understanding R1-Zero-Like Training: A Critical Perspective](https://huggingface.co/papers/2503.20783), [DAPO: An Open-Source LLM Reinforcement Learning System at Scale](https://huggingface.co/papers/2503.14476)). If you wish to include the KL divergence term, you can set `beta` in [`GRPOConfig`] to a non-zero value. + +In the original paper, this formulation is generalized to account for multiple updates after each generation (denoted \\( \mu \\), can be set with `num_iterations` in [`GRPOConfig`]) by leveraging the **clipped surrogate objective**: + +$$ +\mathcal{L}_{\text{GRPO}}(\theta) = - \frac{1}{\sum_{i=1}^G |o_i|} \sum_{i=1}^G \sum_{t=1}^{|o_i|} \left[ \min \left( \frac{\pi_\theta(o_{i,t} \mid q, o_{i,< t})}{\pi_{\theta_{\text{old}}}(o_{i,t} \mid q, o_{i,< t})} \hat{A}_{i,t}, \, \text{clip}\left( \frac{\pi_\theta(o_{i,t} \mid q, o_{i,< t})}{\pi_{\theta_{\text{old}}}(o_{i,t} \mid q, o_{i,< t})}, 1 - \epsilon, 1 + \epsilon \right) \hat{A}_{i,t} \right) - \beta \mathbb{D}_{\text{KL}}\left[\pi_\theta \| \pi_{\text{ref}}\right] \right], +$$ + +where \\(\text{clip}(\cdot, 1 - \epsilon, 1 + \epsilon) \\) ensures that updates do not deviate excessively from the reference policy by bounding the policy ratio between \\( 1 - \epsilon \\) and \\( 1 + \epsilon \\). +When \\( \mu = 1 \\) (default in TRL), the clipped surrogate objective simplifies to the original objective. + +#### Loss Types + +Several formulations of the objective have been proposed in the literature. Initially, the objective of GRPO was defined as follows: + +$$ +\mathcal{L}_{\text{GRPO}}(\theta) = - \frac{1}{G} \sum_{i=1}^G \frac{1}{|o_i|} \sum_{t=1}^{|o_i|} l_{i,t}, +$$ + +where + +$$ +l_{i,t} = \frac{\pi_\theta(o_{i,t} \mid q, o_{i,< t})}{\left[\pi_\theta(o_{i,t} \mid q, o_{i,< t})\right]_{\text{no grad}}} \hat{A}_{i,t} - \beta \mathbb{D}_{\text{KL}}\left[\pi_\theta \| \pi_{\text{ref}}\right]. +$$ + +The [DAPO paper](https://huggingface.co/papers/2503.14476) highlights the limitations of the GRPO algorithm’s sample-level loss in long-CoT scenarios, where longer responses are under-penalized, leading to poorer quality outputs. The proposed solution is a token-level normalization, which better handles longer sequences by assigning more balanced rewards to individual tokens, regardless of response length: + +$$ +\mathcal{L}_{\text{DAPO}}(\theta) = - \frac{1}{\sum_{i=1}^G |o_i|} \sum_{i=1}^G \sum_{t=1}^{|o_i|} l_{i,t}, +$$ + +To use this formulation, set `loss_type="dapo"` in [`GRPOConfig`]. + +Furthermore, it was demonstrated in the paper [Understanding R1-Zero-Like Training: A Critical Perspective](https://huggingface.co/papers/2503.20783) that the initial GRPO formulation introduces a response length bias. They show that while the DAPO formulation reduces this bias, it does not eliminate it completely. To fully remove this bias, they propose dividing by a constant instead of the sequence length, resulting in the following formulation: + +$$ +\mathcal{L}_{\text{Dr. GRPO}}(\theta) = - \frac{1}{LG} \sum_{i=1}^G \sum_{t=1}^{|o_i|} l_{i,t}, +$$ + +This constant is recommended to be the maximum completion length. To use this formulation, set `loss_type="dr_grpo"` in the [`GRPOConfig`]. + +Alternatively, in the [SAPO paper](https://huggingface.co/papers/2511.20347), the Qwen team proposes replacing the "hard" clipping mechanism of GRPO with a smooth, temperature-controlled soft gating mechanism. While GRPO zeroes out gradients when the policy deviates too far from the reference, SAPO uses a soft trust region that smoothly decays the gradient weight. This allows the model to retain useful learning signals from "near-on-policy" tokens while suppressing noise from extreme deviations. + +The loss function is defined as: + +$$ +\mathcal{L}_{\text{SAPO}}(\theta) = - \frac{1}{G} \sum_{i=1}^G \frac{1}{|o_i|} \sum_{t=1}^{|o_i|} f_{i,t} \left( \frac{\pi_\theta(o_{i,t} | q, o_{i, 0 \\ +\tau_{\text{neg}}, & \text{otherwise} +\end{cases} +$$ + +They recommend using asymmetric temperatures, \\( \tau_{\text{neg}} > \tau_{\text{pos}} \\) (defaults are \\( \tau_{\text{pos}}=1.0, \tau_{\text{neg}}=1.05 \\) ). This ensures that the model is penalized more strictly for "bad" actions to prevent instability, while being more permissive with "good" actions. + +To use this formulation, set `loss_type="sapo"` in the [`GRPOConfig`]. + +## Logged metrics + +While training and evaluating, we record the following reward metrics: + +- `num_tokens`: The total number of tokens processed so far, including both prompts and completions. When using tools, only non-tool tokens are counted. +- `step_time`: The average time (in seconds) taken per training step (including generation). +- `completions/mean_length`: The average length of generated completions. When using tools, only non-tool tokens are counted. +- `completions/min_length`: The minimum length of generated completions. When using tools, only non-tool tokens are counted. +- `completions/max_length`: The maximum length of generated completions. When using tools, only non-tool tokens are counted. +- `completions/mean_terminated_length`: The average length of generated completions that terminate with EOS. When using tools, only non-tool tokens are counted. +- `completions/min_terminated_length`: The minimum length of generated completions that terminate with EOS. When using tools, only non-tool tokens are counted. +- `completions/max_terminated_length`: The maximum length of generated completions that terminate with EOS. When using tools, only non-tool tokens are counted. +- `completions/clipped_ratio`: The ratio of truncated (clipped) completions. +- `reward/{reward_func_name}/mean`: The average reward from a specific reward function. +- `reward/{reward_func_name}/std`: The standard deviation of the reward from a specific reward function. +- `reward`: The overall average reward after summing rewards across functions (weighted by `reward_weights`). +- `reward_std`: The standard deviation of summed rewards across functions (weighted by `reward_weights`), computed over the full batch. +- `frac_reward_zero_std`: The fraction of samples in the generation batch with a reward std of zero, implying there is little diversity for that prompt (all answers are correct or incorrect). +- `entropy`: Average entropy of token predictions across generated completions. (If `mask_truncated_completions=True`, masked sequences tokens are excluded.) +- `kl`: The average KL divergence between the model and the reference model, calculated over generated completions. Logged only if `beta` is nonzero. +- `clip_ratio/region_mean`: The ratio of token (or sequence, if `importance_sampling_level="sequence"`) probabilities where the GRPO objective is clipped to stay within the trust region: \\( \text{clip}\left( r_{i,t}(\theta), 1 - \epsilon_\mathrm{low}, 1 + \epsilon_\mathrm{high} \right)\,, \quad r_{i,t}(\theta) = \frac{\pi_\theta(o_{i,t} \mid q, o_{i,< t})}{\pi_{\theta_{\text{old}}}(o_{i,t} \mid q, o_{i,< t})} \\). A higher value means more tokens are clipped, which constrains how much the policy $\pi_\theta$ can change. +- `clip_ratio/low_mean`: The average ratio of token (or sequence, if `importance_sampling_level="sequence"`) probabilities that were clipped on the lower bound of the trust region: \\(r_{i,t}(\theta) < 1 - \epsilon_\mathrm{low}\\). +- `clip_ratio/low_min`: The minimum ratio of token (or sequence, if `importance_sampling_level="sequence"`) probabilities that were clipped on the lower bound of the trust region: \\(r_{i,t}(\theta) < 1 - \epsilon_\mathrm{low}\\). +- `clip_ratio/high_mean`: The average ratio of token (or sequence, if `importance_sampling_level="sequence"`) probabilities that were clipped on the upper bound of the trust region: \\(r_{i,t}(\theta) > 1 + \epsilon_\mathrm{high}\\). +- `clip_ratio/high_max`: The maximum ratio of token (or sequence, if `importance_sampling_level="sequence"`) probabilities that were clipped on the upper bound of the trust region: \\(r_{i,t}(\theta) > 1 + \epsilon_\mathrm{high}\\). + +## Customization + +### Speed up training with vLLM-powered generation + +Generation is often the main bottleneck when training with online methods. To accelerate generation, you can use [vLLM](https://github.com/vllm-project/vllm), a high-throughput, low-latency inference engine for LLMs. To enable it, first install the package with + +```shell +pip install trl[vllm] +``` + +We support two ways of using vLLM during training: **server mode** and **colocate mode**. + +> [!TIP] +> By default, Truncated Importance Sampling is activated for vLLM generation to address the generation-training mismatch that occurs when using different frameworks. This can be turned off by setting `vllm_importance_sampling_correction=False`. For more information, see [Truncated Importance Sampling](paper_index#truncated-importance-sampling) + +#### Option 1: Colocate mode + +In this mode, vLLM runs inside the trainer process and shares GPU memory with the training model. This avoids launching a separate server and can improve GPU utilization, but may lead to memory contention on the training GPUs. This is the default mode. + +```python +from trl import GRPOConfig + +training_args = GRPOConfig( + ..., + use_vllm=True, # vllm_mode="colocate" by default +) +``` + +#### Option 2: Server mode + +In this mode, vLLM runs in a separate process (and using separate GPUs) and communicates with the trainer via HTTP. This is ideal if you have dedicated GPUs for inference. + +1. **Start the vLLM server**: + + ```bash + trl vllm-serve --model + ``` + +2. **Enable server mode in your training script**: + + ```python + from trl import GRPOConfig + + training_args = GRPOConfig( + ..., + use_vllm=True, + vllm_mode="server", + ) + ``` + +> [!WARNING] +> Make sure that the server is using different GPUs than the trainer, otherwise you may run into NCCL errors. You can specify the GPUs to use with the `CUDA_VISIBLE_DEVICES` environment variable. + +> [!TIP] +> Depending on the model size and the overall GPU memory requirements for training, you may need to adjust the `vllm_gpu_memory_utilization` parameter in [`GRPOConfig`] to avoid underutilization or out-of-memory errors. +> +> We provide a [HF Space](https://huggingface.co/spaces/trl-lib/recommend-vllm-memory) to help estimate the recommended GPU memory utilization based on your model configuration and experiment settings. Simply use it as follows to get `vllm_gpu_memory_utilization` recommendation: +> +> +> +> If the recommended value does not work in your environment, we suggest adding a small buffer (e.g., +0.05 or +0.1) to the recommended value to ensure stability. +> +> If you still find you are getting out-of-memory errors set `vllm_enable_sleep_mode` to True and the vllm parameters and cache will be offloaded during the optimization step. For more information, see [Reducing Memory Usage with vLLM Sleep Mode](reducing_memory_usage#vllm-sleep-mode). + +> [!TIP] +> By default, GRPO uses `MASTER_ADDR=localhost` and `MASTER_PORT=12345` for vLLM, but you can override these values by setting the environment variables accordingly. + +For more information, see [Speeding up training with vLLM](speeding_up_training#vllm-for-fast-generation-in-online-methods). + + +#### Dealing with the Training-Inference Mismatch +While vLLM greatly accelerates inference, it also decouples the inference engine from the training engine. In theory these engines are mathematically identical, in practice however they can produce different outputs due to precision effects and hardware specific optimizations. This divergence reflects the different optimization objectives of the two systems. Inference engines aim to maximize sampling throughput, typically measured in tokens per second, while maintaining acceptable sampling fidelity. Training frameworks instead focus on numerical stability and precision for gradient computation, often using higher precision formats like FP32 for master weights and optimizer states. These differing priorities and constraints introduce an inevitable, albeit subtle, mismatch between training and inference. + +This mismatch leads to a biased gradient update which has been observed to destabilize training ([[1]](https://fengyao.notion.site/off-policy-rl)[[2]](https://yingru.notion.site/When-Speed-Kills-Stability-Demystifying-RL-Collapse-from-the-Training-Inference-Mismatch-271211a558b7808d8b12d403fd15edda)[[3]](https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/#true-on-policy-rl)[[4]](https://huggingface.co/papers/2510.26788)[[5]](https://huggingface.co/papers/2510.18855)). For simplicity, consider the REINFORCE policy gradient: + +$$ +\nabla_\theta \mathcal{J}(x,\theta) += \mathbb{E}_{y \sim \pi^\text{train}(\cdot \mid x,\theta)} +\left[ \nabla_\theta \log \pi^\text{train}(y \mid x,\theta) \cdot R(x,y) \right] +$$ + +Here \\( x \\) denotes prompts sampled from some data distribution, and \\( \pi^\text{train} \\) is the policy implemented by the training engine. With vLLM in the loop we obtain a separate inference policy \\( \pi^\text{inference} \\), so the effective policy gradient becomes + +$$ +\nabla_\theta \mathcal{J}_{\text{biased}}(x,\theta) += \mathbb{E}_{y \sim \pi^\text{inference}(\cdot \mid x,\theta)} +\left[ \nabla_\theta \log \pi^\text{train}(y \mid x,\theta) \cdot R(x,y) \right]. +$$ + +This turns an otherwise on policy RL problem into an off policy one. + +The standard way to correct for this distribution shift is **importance sampling (IS)**. We provide two IS variants: [Truncated Importance Sampling (TIS)](paper_index#truncated-importance-sampling) and [Masked Importance Sampling (MIS)](paper_index#masked-importance-sampling). Both variants can be applied either at the token level or at the sequence level. Let \\( \rho \\) denote the importance weight, for example \\( \rho_t \\) per token or \\( \rho_{\text{seq}} \\) per sequence. Under TIS, ratios outside of the range `[vllm_importance_sampling_clip_min, vllm_importance_sampling_clip_max]` are clipped, + +$$ +\rho \leftarrow \text{clip}(\rho, C_{\min}, C_{\max}). +$$ + +The original [TIS paper](https://huggingface.co/papers/1606.02647) proposed a single upper-bound clipping mechanism, i.e., \\( \min(\rho, C_{\max}) \\). The implementation in TRL generalized this by also introducing a lower bound, yielding the two-sided formulation shown above, inspired by the [IcePop](paper_index#masked-importance-sampling) method. +Note that in IcePop, the bounds are labelled as \\( \alpha \\) and \\( \beta \\) while in TRL we use \\( C_{\min} \\) and \\( C_{\max} \\). + +Under MIS, ratios outside of this range are set to zero, so those samples do not contribute to the gradient. In other words, outlier samples are downweighted under TIS and discarded under MIS. The configuration flag `vllm_importance_sampling_mode` chooses both the IS variant (masking or truncation) and the granularity (token level or sequence level). + +Importance sampling is the principled algorithmic response to the training–inference mismatch. However, there are also more direct approaches that attempt to reduce the mismatch between the two engines themselves. Most of these are engineering solutions. For example, [MiniMax M1 uses an FP32 language model head](https://huggingface.co/papers/2506.13585) in the inference engine. Thinking Machines has explored [deterministic inference kernels](https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/), although this comes with a significant efficiency cost. vLLM has shown [bitwise consistent policies](https://blog.vllm.ai/2025/11/10/bitwise-consistent-train-inference.html) by building on the batch invariant deterministic kernels from Thinking Machines, but as of November 2025 there remains a substantial throughput penalty relative to standard vLLM inference. + +### Speed up training with transformers continuous batching + +As an alternative to vLLM, you can use transformers' built-in continuous batching engine for faster generation. Continuous batching removes finished sequences from the batch immediately rather than waiting for the slowest one to finish. For tasks with variable completion lengths (e.g., math reasoning), this yields faster generation and lower VRAM usage than the default `generate()` at large batch sizes (N≥32). + +> [!TIP] +> Continuous batching is a drop-in upgrade with no server setup or weight synchronization. It runs in-process and is well-suited for single-GPU training or memory-constrained environments. For maximum generation throughput at scale, use vLLM instead. + +```python +from trl import GRPOConfig + +training_args = GRPOConfig( + ..., + use_transformers_continuous_batching=True, + transformers_continuous_batching_config={ + "use_cuda_graph": False, + "max_memory_percent": 0.4, # lower values leave more VRAM for the training backward pass + }, +) +``` + +> [!TIP] +> TRL defaults `max_memory_percent` to `0.5` (instead of transformers' `0.9`) to leave enough VRAM for the training backward pass. Tune it down to `0.3`–`0.4` for large generation batches (N≥32) or if you see out-of-memory errors. + +For a full training example, see [`examples/scripts/grpo_continuous_batching.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/grpo_continuous_batching.py). + +### GRPO at scale: train a 70B+ Model on multiple nodes + +When training large models like **Qwen2.5-72B**, you need several key optimizations to make the training efficient and scalable across multiple GPUs and nodes. These include: + +- **DeepSpeed ZeRO Stage 3**: ZeRO leverages data parallelism to distribute model states (weights, gradients, optimizer states) across multiple GPUs and CPUs, reducing memory and compute requirements on each device. Since large models cannot fit on a single GPU, using ZeRO Stage 3 is required for training such models. For more details, see [DeepSpeed Integration](deepspeed_integration). +- **Accelerate**: Accelerate is a library that simplifies distributed training across multiple GPUs and nodes. It provides a simple API to launch distributed training and handles the complexities of distributed training, such as data parallelism, gradient accumulation, and distributed data loading. For more details, see [Distributing Training](distributing_training). +- **vLLM**: See the previous section on how to use vLLM to speed up generation. + +Below is an example SLURM script to train a 70B model with GRPO on multiple nodes. This script trains a model on 4 nodes and uses the 5th node for vLLM-powered generation. + +```sh +#!/bin/bash +#SBATCH --nodes=5 +#SBATCH --gres=gpu:8 + +# Get the list of allocated nodes +NODELIST=($(scontrol show hostnames $SLURM_JOB_NODELIST)) + +# Assign the first 4 nodes for training and the 5th node for vLLM +TRAIN_NODES="${NODELIST[@]:0:4}" # Nodes 0, 1, 2, 3 for training +VLLM_NODE="${NODELIST[4]}" # Node 4 for vLLM + +# Run training on the first 4 nodes (Group 1) +srun --nodes=4 --ntasks=4 --nodelist="${NODELIST[@]:0:4}" accelerate launch \ + --config_file examples/accelerate_configs/deepspeed_zero3.yaml \ + --num_processes 32 \ + --num_machines 4 \ + --main_process_ip ${NODELIST[0]} \ + --machine_rank $SLURM_PROCID \ + --rdzv_backend c10d \ + train_grpo.py \ + --server_ip $VLLM_NODE & + +# Run vLLM server on the 5th node (Group 2) +srun --nodes=1 --ntasks=1 --nodelist="${NODELIST[4]}" trl vllm-serve --model Qwen/Qwen2.5-72B --tensor_parallel_size 8 & + +wait +``` + +```python +import argparse + +from datasets import load_dataset +from trl import GRPOTrainer, GRPOConfig +from trl.rewards import accuracy_reward + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--vllm_server_host", type=str, default="", help="The server IP") + args = parser.parse_args() + + dataset = load_dataset("trl-lib/DeepMath-103K", split="train") + + training_args = GRPOConfig( + per_device_train_batch_size=4, + use_vllm=True, + vllm_mode="server", + vllm_server_host=args.vllm_server_host.replace("ip-", "").replace("-", "."), # from ip-X-X-X-X to X.X.X.X + ) + + trainer = GRPOTrainer( + model="Qwen/Qwen2.5-72B", + args=training_args, + reward_funcs=accuracy_reward, + train_dataset=dataset + ) + trainer.train() + +if __name__=="__main__": + main() +``` + +### Using a custom reward function + +The [`GRPOTrainer`] supports using custom reward functions instead of dense reward models. To ensure compatibility, your reward function must satisfy the following requirements: + +Reward functions can be either synchronous Python callables or asynchronous `async def` coroutines. When you provide multiple asynchronous reward functions, they are awaited concurrently (run in parallel via `asyncio.gather`) so their latency overlaps. + +1. **Input arguments**: + - The function must accept the following as keyword arguments: + - `prompts` (contains the prompts), + - `completions` (contains the generated completions), + - `completion_ids` (contains the tokenized completions), + - `trainer_state` ([`~transformers.TrainerState`]): The current state of the trainer. This can be used to implement dynamic reward functions, such as curriculum learning, where the reward is adjusted based on the training progress. + - `log_extra`: a callable `log_extra(column: str, values: list)` to add extra columns to the completions table. See Example 6. In distributed training, it's important that all processes log the same set of keys. + - `log_metric`: a callable `log_metric(name: str, value: float)` to log scalar metrics as plots alongside `kl`, `entropy`, etc. See Example 6. In distributed training, it's important that all processes log the same set of keys. + - `environments`: a list of environment instances, one per completion. Only present when `environment_factory` is provided. Use this to read state accumulated during the episode (e.g., `env.reward`). + - All column names (but `prompt`) that the dataset may have. For example, if the dataset contains a column named `ground_truth`, the function will be called with `ground_truth` as a keyword argument. + + The easiest way to comply with this requirement is to use `**kwargs` in the function signature. + - Depending on the dataset format, the input will vary: + - For [standard format](dataset_formats#standard), `prompts` and `completions` will be lists of strings. + - For [conversational format](dataset_formats#conversational), `prompts` and `completions` will be lists of message dictionaries. + +2. **Return value**: The function must return a list of floats. Each float represents the reward corresponding to a single completion. + +#### Example 1: Reward longer completions + +Below is an example of a reward function for a standard format that rewards longer completions: + +```python +def reward_func(completion_ids, **kwargs): + """Reward function that assigns higher scores to longer completions (in terms of token count).""" + return [float(len(ids)) for ids in completion_ids] +``` + +You can test it as follows: + +```python +>>> prompts = ["The sky is", "The sun is"] # not used in the reward function, but the trainer will pass it +>>> completions = [" blue.", " in the sky."] # not used in the reward function, but the trainer will pass it +>>> completion_ids = [[6303, 13], [304, 279, 12884, 13]] +>>> reward_func(prompts=prompts, completions=completions, completion_ids=completion_ids) +[2.0, 4.0] +``` + +#### Example 1.1: Reward longer completions (based on the number of characters) + +Same as the previous example, but this time the reward function is based on the number of characters instead of tokens. + +```python +def reward_func(completions, **kwargs): + """Reward function that assigns higher scores to longer completions (in terms of character count).""" + return [float(len(completion)) for completion in completions] +``` + +You can test it as follows: + +```python +>>> prompts = ["The sky is", "The sun is"] +>>> completions = [" blue.", " in the sky."] +>>> completion_ids = [[6303, 13], [304, 279, 12884, 13]] # not used in the reward function, but the trainer will pass it +>>> reward_func(prompts=prompts, completions=completions, completion_ids=completion_ids) +[6.0, 12.0] +``` + +#### Example 2: Reward completions with a specific format + +Below is an example of a reward function that checks if the completion has a specific format. This example is inspired by the _format reward_ function used in the paper [DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning](https://huggingface.co/papers/2501.12948). +It is designed for a conversational format, where prompts and completions consist of structured messages. + +```python +import re + +def format_reward_func(completions, **kwargs): + """Reward function that checks if the completion has a specific format.""" + pattern = r"^.*?.*?$" + completion_contents = [completion[0]["content"] for completion in completions] + matches = [re.match(pattern, content) for content in completion_contents] + return [1.0 if match else 0.0 for match in matches] +``` + +You can test this function as follows: + +```python +>>> prompts = [ +... [{"role": "assistant", "content": "What is the result of (1 + 2) * 4?"}], +... [{"role": "assistant", "content": "What is the result of (3 + 1) * 2?"}], +... ] +>>> completions = [ +... [{"role": "assistant", "content": "The sum of 1 and 2 is 3, which we multiply by 4 to get 12.(1 + 2) * 4 = 12"}], +... [{"role": "assistant", "content": "The sum of 3 and 1 is 4, which we multiply by 2 to get 8. So (3 + 1) * 2 = 8."}], +... ] +>>> format_reward_func(prompts=prompts, completions=completions) +[1.0, 0.0] +``` + +#### Example 3: Reward completions based on a reference + +Below is an example of a reward function that checks if the completion is correct. This example is inspired by the _accuracy reward_ function used in the paper [DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning](https://huggingface.co/papers/2501.12948). +This example is designed for [standard format](dataset_formats#standard), where the dataset contains a column named `ground_truth`. + +```python +import re + +def reward_func(completions, ground_truth, **kwargs): + # Regular expression to capture content inside \boxed{} + matches = [re.search(r"\\boxed\{(.*?)\}", completion) for completion in completions] + contents = [match.group(1) if match else "" for match in matches] + # Reward 1 if the content is the same as the ground truth, 0 otherwise + return [1.0 if c == gt else 0.0 for c, gt in zip(contents, ground_truth)] +``` + +You can test this function as follows: + +```python +>>> prompts = ["Problem: Solve the equation $2x + 3 = 7$. Solution:", "Problem: Solve the equation $3x - 5 = 10$."] +>>> completions = [r" The solution is \boxed{2}.", r" The solution is \boxed{6}."] +>>> ground_truth = ["2", "5"] +>>> reward_func(prompts=prompts, completions=completions, ground_truth=ground_truth) +[1.0, 0.0] +``` + +#### Example 4: Multi-task reward functions + +Below is an example of using multiple reward functions in the [`GRPOTrainer`]. In this example, we define two task-specific reward functions: `math_reward_func` and `coding_reward_func`. The `math_reward_func` rewards math problems based on their correctness, while the `coding_reward_func` rewards coding problems based on whether the solution works. + +```python +from datasets import Dataset +from trl import GRPOTrainer + +# Define a dataset that contains both math and coding problems +dataset = Dataset.from_list( + [ + {"prompt": "What is 2+2?", "task": "math"}, + {"prompt": "Write a function that returns the sum of two numbers.", "task": "code"}, + {"prompt": "What is 3*4?", "task": "math"}, + {"prompt": "Write a function that returns the product of two numbers.", "task": "code"}, + ] +) + +# Math-specific reward function +def math_reward_func(prompts, completions, task, **kwargs): + rewards = [] + for prompt, completion, t in zip(prompts, completions, task): + if t == "math": + # Calculate math-specific reward + correct = check_math_solution(prompt, completion) + reward = 1.0 if correct else -1.0 + rewards.append(reward) + else: + # Return None for non-math tasks + rewards.append(None) + return rewards + +# Coding-specific reward function +def coding_reward_func(prompts, completions, task, **kwargs): + rewards = [] + for prompt, completion, t in zip(prompts, completions, task): + if t == "coding": + # Calculate coding-specific reward + works = test_code_solution(prompt, completion) + reward = 1.0 if works else -1.0 + rewards.append(reward) + else: + # Return None for non-coding tasks + rewards.append(None) + return rewards + +# Use both task-specific reward functions +trainer = GRPOTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", + reward_funcs=[math_reward_func, coding_reward_func], + train_dataset=dataset, +) + +trainer.train() +``` + +In this example, the `math_reward_func` and `coding_reward_func` are designed to work with a mixed dataset that contains both math and coding problems. The `task` column in the dataset is used to determine which reward function to apply to each problem. If there is no relevant reward function for a sample in the dataset, the reward function will return `None`, and the [`GRPOTrainer`] will continue with the valid functions and tasks. This allows the [`GRPOTrainer`] to handle multiple reward functions with different applicability. + +Note that the [`GRPOTrainer`] will ignore the `None` rewards returned by the reward functions and only consider the rewards returned by the relevant functions. This ensures that the model is trained on the relevant tasks and ignores the tasks for which there is no relevant reward function. + +#### Example 5: Asynchronous reward functions + +Custom reward functions can also be defined as `async def` coroutines. This is useful if your reward depends on slow I/O (for example, calling a remote service). When you pass multiple async reward functions, [`GRPOTrainer`] executes them concurrently so their latency overlaps. + +Below is a minimal example of an async reward function that simulates an I/O-bound operation: + +```python +import asyncio + +async def async_reward_func(prompts, completions, **kwargs): + # Simulate an I/O-bound call (e.g., HTTP request, database lookup) + await asyncio.sleep(0.01) + # Simple toy reward: 1.0 if the completion is non-empty, else 0.0 + return [1.0 if completion else 0.0 for completion in completions] +``` + +#### Example 6: Logging extra columns and metrics + +Below is an example of a reward function that logs extra columns to the completions table and scalar metrics as plots. + +```python +import re + +def reward_func(completions, ground_truth, log_extra=None, log_metric=None, **kwargs): + extracted = [re.search(r"\\boxed\{(.*?)\}", c) for c in completions] + extracted = [m.group(1) if m else None for m in extracted] + rewards = [1.0 if e == gt else 0.0 for e, gt in zip(extracted, ground_truth)] + + if log_extra: + log_extra("golden_answer", list(ground_truth)) + log_extra("extracted_answer", [e or "[none]" for e in extracted]) + + if log_metric: + log_metric("accuracy", sum(rewards) / len(rewards)) + + return rewards +``` + +#### Passing the reward function to the trainer + +To use your custom reward function, pass it to the [`GRPOTrainer`] as follows: + +```python +from trl import GRPOTrainer + +trainer = GRPOTrainer( + reward_funcs=reward_func, + ..., +) +``` + +You can pass several reward functions as a list; this list may include both synchronous and asynchronous functions: + +```python +from trl import GRPOTrainer + +trainer = GRPOTrainer( + reward_funcs=[reward_func, async_reward_func1, async_reward_func2], + ..., +) +``` + +and the reward will be computed as the sum of the rewards from each function, or the weighted sum if `reward_weights` is provided in the config. + +Note that [`GRPOTrainer`] supports multiple reward functions of different types. See the parameters documentation for more details. + +### Rapid Experimentation for GRPO + +RapidFire AI is an open-source experimentation engine that sits on top of TRL and lets you launch multiple GRPO configurations at once, even on a single GPU. Instead of trying configurations sequentially, RapidFire lets you **see all their learning curves earlier, stop underperforming runs, and clone promising ones with new settings in flight** without restarting. For more information, see [RapidFire AI Integration](rapidfire_integration). + +## Agent Training + +GRPO supports **agent training** through the `tools` argument in [`GRPOTrainer`]. +This parameter expects a list of Python functions (sync or async) that define the tools available to the agent: + +```python +from trl import GRPOTrainer + +trainer = GRPOTrainer( + tools=[tool1, tool2], + ..., +) +``` + +Each tool must be a standard Python function with **type-hinted arguments and return types**, along with a **Google-style docstring** describing its purpose, arguments, and return value. +For more details, see the [Passing tools guide](https://huggingface.co/docs/transformers/en/chat_extras#passing-tools). + +> [!TIP] +> The GRPO tool call loop requires the chat template to be *prefix-preserving* (appending a tool message must not change how earlier messages are rendered). For known model families (e.g. Qwen3, DeepSeek-V3), TRL automatically swaps in a patched training template when tools are enabled. See [Chat Templates](chat_templates#training-templates) for the full list. + +Example: + +```python +from trl import GRPOTrainer + +def multiply(a: int, b: int) -> int: + """ + Multiplies two integers. + + Args: + a: The first integer. + b: The second integer. + + Returns: + The product of the two integers. + """ + return a * b + +async def async_add(a: int, b: int) -> int: + """ + Asynchronously adds two integers. + + Args: + a: The first integer. + b: The second integer. + + Returns: + The sum of the two integers. + """ + return a + b + +trainer = GRPOTrainer( + tools=[multiply, async_add], + ..., +) +``` + +You can also provide tools through `environment_factory`. In this mode, [`GRPOTrainer`] creates one environment instance per rollout and exposes the environment's public methods as tools. See the [OpenEnv guide](openenv) for the `environment_factory` contract. + +All environments plug into the same `environment_factory` slot, so they are interchangeable at the TRL level — pick the one whose ecosystem fits your task: + +| Integration | What it is | Use it when | +|---|---|---| +| [OpenEnv](openenv) | The open environment standard (Gymnasium-style API, served over WebSocket or containerised execution), backed by Hugging Face and the community. | You're using a ready-made OpenEnv environment from the Hub, or defining your own against the open standard (e.g. Wordle, Sudoku, Catch). | +| [OpenReward](openreward) | An integration with ORS-speaking environments (the [openreward.ai](https://openreward.ai) catalog or your own ORS server); tasks **and** rewards are served over HTTP. | You want to train against an ORS environment: the catalog (e.g. `Eigent/SETA`), one you self-host on your own infra, or a local server you're developing. | +| [Harbor](harbor) | An integration with Harbor task suites: each task is an instruction, a real sandbox image (`docker`, `e2b`, ...), and an in-sandbox verifier. | You want to train against a Harbor task suite: a tree of tasks, each a self-contained sandbox plus verifier (e.g. a data-analysis agent that explores files in a sandbox and writes an answer a grader checks). | + +> [!IMPORTANT] +> `environment_factory` requires `transformers>=5.2.0`. + +The following is a minimal example of using `environment_factory` to define a simple environment with an `increment` method, which is exposed as a tool to the agent: + +```python +from datasets import Dataset +from trl import GRPOConfig, GRPOTrainer + +instructions = [f"Increment the counter by {i}." for i in range(1, 7)] +dataset = Dataset.from_dict({"prompt": [[{"role": "user", "content": instruction}] for instruction in instructions]}) + +def reward_func(environments, **kwargs): # dummy reward: the reward is the current value of the counter + return [environment.counter for environment in environments] + +class IncrementEnv: + def reset(self, **kwargs) -> str | None: # required; receives sampled row fields as kwargs (e.g., `prompt`) + self.counter = 0 + return "Counter reset to 0.\n" + + def increment(self, step: int) -> int: # the other public methods of the environment are exposed as tools + """ + Increment the internal counter. + + Args: + step: Value to add to the counter. + + Returns: + The updated counter value. + """ + self.counter += step + return self.counter + +trainer = GRPOTrainer( + model="Qwen/Qwen3-0.6B", + args=GRPOConfig(chat_template_kwargs={"enable_thinking": False}), + train_dataset=dataset, + reward_funcs=reward_func, + environment_factory=IncrementEnv, +) +trainer.train() +``` + +`reset` can return either `None` or a string. In GRPO, when it returns a string, that string is appended to the last user message before generation. + +### Multimodal Tool Responses + +Tools can return images alongside text by returning a list of content blocks. This is useful for VLM agent training where the tool provides visual feedback (e.g., screenshots, plots, camera captures). + +```python +from PIL import Image + +def take_screenshot() -> list: + """ + Takes a screenshot of the current screen. + + Returns: + The screenshot image with a description. + """ + img = Image.open("screenshot.png") + return [{"type": "image", "image": img}, {"type": "text", "text": "Here is the screenshot."}] +``` + +The returned images are automatically injected into the conversation and passed to the VLM for subsequent generation turns. + +### Supported Models + +Tested with: + +- [**Gemma4**](https://huggingface.co/collections/google/gemma-4) — e.g., `google/gemma-4-E2B-it` +- **GLM-4-MoE** ([4.5](https://huggingface.co/collections/zai-org/glm-45), [4.6](https://huggingface.co/collections/zai-org/glm-46) or [4.7](https://huggingface.co/collections/zai-org/glm-47)) — e.g., `zai-org/GLM-4.7` +- [**GPT-OSS**](https://huggingface.co/collections/openai/gpt-oss) — e.g., `openai/gpt-oss-20b` +- [**Llama 3.1**](https://huggingface.co/collections/meta-llama/llama-31) — e.g., `meta-llama/Llama-3.1-8B-Instruct` +- [**Llama 3.2**](https://huggingface.co/collections/meta-llama/llama-32) — e.g., `meta-llama/Llama-3.2-3B-Instruct` +- [**Qwen2.5**](https://huggingface.co/collections/Qwen/qwen25) — e.g., `Qwen/Qwen2.5-0.5B-Instruct` +- [**Qwen3**](https://huggingface.co/collections/Qwen/qwen3) — e.g., `Qwen/Qwen3-0.6B` +- [**Qwen3-VL**](https://huggingface.co/collections/Qwen/qwen3-vl) — e.g., `Qwen/Qwen3-VL-2B-Instruct` +- [**Qwen3.5**](https://huggingface.co/collections/Qwen/qwen35) — e.g., `Qwen/Qwen3.5-2B` +- [**Qwen3.6**](https://huggingface.co/collections/Qwen/qwen36) — e.g., `Qwen/Qwen3.6-35B-A3B` + +> [!TIP] +> Compatibility with all LLMs is not guaranteed. If you believe a model should be supported, feel free to open an issue on GitHub — or better yet, submit a pull request with the required changes. + +### Quick Start + +Use [grpo\_agent.py](https://github.com/huggingface/trl/blob/main/examples/scripts/grpo_agent.py) to fine-tune a LLM for agentic workflows. + +```bash +accelerate launch \ + --config_file=examples/accelerate_configs/deepspeed_zero3.yaml \ + examples/scripts/grpo_agent.py \ + --model_name_or_path Qwen/Qwen3-0.6B + ... +``` + +## Vision-Language Model (VLM) Training + +GRPO supports training Vision-Language Models (VLMs) on multimodal datasets containing both text and images. + +### Supported Models + +Tested with: + +- **Gemma3** — e.g., `google/gemma-3-4b-it` +- **LLaVA-NeXT** — e.g., `llava-hf/llava-v1.6-mistral-7b-hf` +- **Qwen2-VL** — e.g., `Qwen/Qwen2-VL-2B-Instruct` +- **Qwen2.5-VL** — e.g., `Qwen/Qwen2.5-VL-3B-Instruct` +- **SmolVLM2** — e.g., `HuggingFaceTB/SmolVLM2-2.2B-Instruct` + +> [!TIP] +> Compatibility with all VLMs is not guaranteed. If you believe a model should be supported, feel free to open an issue on GitHub — or better yet, submit a pull request with the required changes. + +### Quick Start + +Use [grpo\_vlm.py](https://github.com/huggingface/trl/blob/main/examples/scripts/grpo_vlm.py) to fine-tune a VLM. Example command for training on [`lmms-lab/multimodal-open-r1-8k-verified`](https://huggingface.co/datasets/lmms-lab/multimodal-open-r1-8k-verified): + +```bash +accelerate launch \ + --config_file=examples/accelerate_configs/deepspeed_zero3.yaml \ + examples/scripts/grpo_vlm.py \ + --model_name_or_path Qwen/Qwen2.5-VL-3B-Instruct \ + --output_dir grpo-Qwen2.5-VL-3B-Instruct \ + --learning_rate 1e-5 \ + --dtype bfloat16 \ + --max_completion_length 1024 \ + --use_vllm \ + --vllm_mode colocate \ + --use_peft \ + --lora_target_modules "q_proj", "v_proj" \ + --log_completions +``` + +### Configuration Tips + +- Use LoRA on vision-language projection layers +- Enable 4-bit quantization to reduce memory usage +- VLMs are memory-intensive — start with smaller batch sizes +- Most models are compatible with vLLM (`server` and `colocate` modes) + +### Dataset Format + +Each training sample should include: + +- `prompt`: Text formatted via the processor's chat template +- `image`/`images`: PIL Image or list of PIL Images + +The trainer automatically handles image-to-tensor conversion via the model’s image processor. + +## GRPOTrainer + +[[autodoc]] GRPOTrainer + - train + - save_model + - push_to_hub + +## GRPOConfig + +[[autodoc]] GRPOConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/grpo_with_replay_buffer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/grpo_with_replay_buffer.md new file mode 100644 index 0000000000000000000000000000000000000000..e68cce94458f7b1769630847b1a201f8fb99024a --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/grpo_with_replay_buffer.md @@ -0,0 +1,56 @@ +# GRPO With Replay Buffer + +This experimental trainer, trains a model with GRPO but replaces groups (and corresponding completions) that have 0 standard deviation with groups with high rewards and standard deviation that've been used to train a model in prior batches. + +## Usage + +```python +import torch +from trl.experimental.grpo_with_replay_buffer import GRPOWithReplayBufferConfig, GRPOWithReplayBufferTrainer +from datasets import load_dataset + +dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + +# Guarantee that some rewards have 0 std +def custom_reward_func(completions, **kwargs): + if torch.rand(1).item() < 0.25: + return [0] * len(completions) # simulate some None rewards + else: + return torch.rand(len(completions)).tolist() + +training_args = GRPOWithReplayBufferConfig( + output_dir="./tmp", + learning_rate=1e-4, + per_device_train_batch_size=4, + num_generations=4, + max_completion_length=8, + replay_buffer_size=8, + report_to="none", +) + +trainer = GRPOWithReplayBufferTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=[custom_reward_func], + args=training_args, + train_dataset=dataset, +) + +previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + +trainer.train() +``` + +## GRPOWithReplayBufferTrainer + +[[autodoc]] experimental.grpo_with_replay_buffer.GRPOWithReplayBufferTrainer + - train + - save_model + - push_to_hub + +## GRPOWithReplayBufferConfig + +[[autodoc]] experimental.grpo_with_replay_buffer.GRPOWithReplayBufferConfig + +## ReplayBuffer + +[[autodoc]] experimental.grpo_with_replay_buffer.ReplayBuffer diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/gspo_token.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/gspo_token.md new file mode 100644 index 0000000000000000000000000000000000000000..394fb555f87f4e5e1aeb25ed963a0a3643e3dc47 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/gspo_token.md @@ -0,0 +1,25 @@ +# GSPO-token + +In the paper [Group Sequence Policy Optimization](https://huggingface.co/papers/2507.18071), the authors propose a token-level objective variant to GSPO, called GSPO-token. To use GSPO-token, you can use the `GRPOTrainer` class in `trl.experimental.gspo_token`. + +## Usage + +```python +from trl.experimental.gspo_token import GRPOTrainer +from trl import GRPOConfig + +training_args = GRPOConfig( + importance_sampling_level="sequence_token", + ... +) +``` + +> [!WARNING] +> To leverage GSPO-token, the user will need to provide the per-token advantage \\( \hat{A_{i,t}} \\) for each token \\( t \\) in the sequence \\( i \\) (i.e., make \\( \hat{A_{i,t}} \\) varies with \\( t \\)—which isn't the case here, \\( \hat{A_{i,t}}=\hat{A_{i}} \\)). Otherwise, GSPO-Token gradient is just equivalent to the original GSPO implementation. + +## GRPOTrainer + +[[autodoc]] experimental.gspo_token.GRPOTrainer + - train + - save_model + - push_to_hub diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/harbor.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/harbor.md new file mode 100644 index 0000000000000000000000000000000000000000..e5deaaa73632b4e90175a3c9f1ddd8904cbca5b1 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/harbor.md @@ -0,0 +1,171 @@ +# Harbor Integration for Training LLMs with Environments + +[Harbor](https://www.harborframework.com) is a framework for running agentic tasks in sandboxes. It decouples a **task** (instruction + sandbox image + verifier), a **harness/agent** (the tool surface + loop), and a **sandbox** (`docker`, `e2b`, `daytona`, `gke`, …) so they can be mixed freely. This makes it a natural fit for RL: the same task suite can be trained with different tool surfaces, on whichever sandbox backend you prefer. + +This guide covers **how to integrate Harbor with TRL**. For Harbor itself, see the [Harbor docs](https://www.harborframework.com/docs). + +> [!NOTE] +> The integration lives at `trl.experimental.harbor` and is gated behind the `trl[harbor]` extra (lazy-imported — non-users pay nothing). + +## When to use Harbor environments + +[`GRPOTrainer`] supports environment-based training via the `environment_factory` slot — see [OpenEnv](openenv) for the general contract. Use Harbor when you want to train against a **Harbor task suite**: a directory tree of tasks, each a self-contained sandbox + verifier (for example, a data-analysis agent suite where the model explores files in a sandbox and writes an answer that a grader checks). + +## Installation + +```bash +pip install trl[harbor] +``` + +> [!IMPORTANT] +> Harbor drives generation through vLLM and uses `environment_factory`, which requires `vllm>=0.22.0` and `transformers>=5.2.0`. +> +> ```bash +> pip install 'vllm>=0.22.0' +> ``` + +This installs the `harbor` framework (Python >= 3.12). The integration imports `harbor` lazily and runs it **in-process**, so users who don't touch `trl.experimental.harbor` aren't affected. + +A sandbox backend must also be installed and reachable at train time. Harbor keeps cloud backends behind its own extras, so install the one you intend to use and provide its credentials: + +```bash +pip install "harbor[e2b]" # E2B cloud sandbox -> environment_type="e2b", needs E2B_API_KEY +# docker backend (environment_type="docker", Harbor's default) just needs a reachable Docker daemon +``` + +## Quick start + +`HarborSpec` wires a single Harbor task suite into the three TRL trainer slots — `train_dataset`, `environment_factory`, `reward_funcs` — by exposing properties that map 1:1 to those kwarg names: + +```python +from trl import GRPOConfig, GRPOTrainer +from trl.experimental.harbor import HarborSpec + +spec = HarborSpec("AdithyaSK/data_agent_rl_environment_train", agent="bash", num_tasks=64) + +trainer = GRPOTrainer( + model="Qwen/Qwen3-4B", + args=GRPOConfig( + num_generations=8, + max_steps=50, + max_tool_calling_iterations=25, + log_completions=True, + ), + train_dataset=spec.train_dataset, + environment_factory=spec.environment_factory, + reward_funcs=spec.reward_funcs, +) +trainer.train() +``` + +Under the hood `HarborSpec` does three things, lazily on first access: + +1. **`spec.train_dataset`**: resolves the task suite to local task directories (downloading the HF dataset if needed) and builds a `datasets.Dataset` with `prompt` (empty — the env's instruction is appended at `reset`), `task_dir`, `task_index`, plus per-task `task.toml` metadata columns. +2. **`spec.environment_factory`**: returns a zero-arg callable producing a fresh per-rollout [`~trl.experimental.harbor.HarborEnv`]. On `reset(task_dir)` it starts the task's Harbor sandbox and returns its instruction; tool methods exec into the sandbox; `env.reward` runs the verifier once after the rollout. +3. **`spec.reward_funcs`**: an outcome reward that reads the Harbor verifier's scalar per rollout. + +## The dataset + +`dataset` is either a Hugging Face dataset repo id holding a Harbor task tree, or a local path containing a `tasks/` subtree. Each task is a directory: + +``` +tasks// +├── instruction.md # the task prompt (returned by reset) +├── task.toml # config + metadata (gold answer, difficulty, ...) +├── environment/ # Dockerfile (+ any pre-agent data hooks) +└── tests/ # test.sh / grader → writes the reward +``` + +Select a subset with `num_tasks` or `indices` (mutually exclusive): + +```python +spec = HarborSpec("AdithyaSK/data_agent_rl_environment_train", num_tasks=10) # first 10 +spec = HarborSpec("AdithyaSK/data_agent_rl_environment_train", indices=[0, 5, 13]) # specific +``` + +## Agents: external vs installed + +Harbor supports two ways an agent drives a task, and the distinction determines what can be trained with RL: + +- [**External agents**](https://www.harborframework.com/docs/agents#external-agents) run *outside* the sandbox and drive the loop themselves, issuing commands into the container through Harbor's environment interface ("typically by executing bash commands via the `exec` method"). The agent decides each action and interprets each result; the sandbox only executes. +- [**Installed agents**](https://www.harborframework.com/docs/agents#installed-agents) are installed *into the container image* and run there as a headless subprocess (extending `BaseInstalledAgent`). Harbor launches the agent inside the sandbox and parses its trajectory file afterward (`populate_context_post_run`); the agent runs autonomously with its own inference. + +**TRL's integration is the external-agent pattern, and only that pattern is supported for now.** RL training requires the trainer to drive the rollout turn by turn: the *policy model being trained* generates each turn, and TRL captures its tokens and log-probs and applies the environment mask — exactly what `environment_factory` provides over a black-box `rollout_func`. An installed agent is opaque to this: it runs inside the container with its *own* model and only emits a trajectory after the fact, so there are no policy tokens or log-probs for the trainer to optimize, and the model under training is never invoked. A [`~trl.experimental.harbor.HarborEnv`] is therefore an external agent — its tool methods `exec` into the sandbox, but the loop, and the model under training, stay in TRL. + +## Selecting the base agent (harness) + +The **base agent** is the harness — which tool methods the env exposes and how it submits. Select it with `agent=`: + +```python +HarborSpec(dataset, agent="bash") # built-in single-bash-tool harness +HarborSpec(dataset, agent="my_pkg.harnesses:JupyterEnv") # import path to your HarborEnv subclass +HarborSpec(dataset, agent="path/to/harness.py:JupyterEnv") # file path to your HarborEnv subclass +HarborSpec(dataset, agent=MyHarborEnv) # a HarborEnv subclass directly +``` + +The built-in `"bash"` harness ([`~trl.experimental.harbor.HarborBashEnv`]) exposes one `bash` tool and submits by writing `/workdir/answer.txt`. Two richer harnesses ship as examples — each in its own folder with a README listing its tools — under [`examples/scripts/harbor/harnesses/`](https://github.com/huggingface/trl/tree/main/examples/scripts/harbor/harnesses): + +- [`jupyter/`](https://github.com/huggingface/trl/tree/main/examples/scripts/harbor/harnesses/jupyter) (`JupyterEnv`) — a stateful Python kernel (variables persist across cells) + a shell tool. +- [`terminal_notes/`](https://github.com/huggingface/trl/tree/main/examples/scripts/harbor/harnesses/terminal_notes) (`TerminalNotesEnv`) — 6 shell tools (incl. background processes) + a 4-tool persistent note toolkit. + +```python +HarborSpec(dataset, agent="examples/scripts/harbor/harnesses/jupyter/env.py:JupyterEnv") +HarborSpec(dataset, agent="examples/scripts/harbor/harnesses/terminal_notes/env.py:TerminalNotesEnv") +``` + +To write your own harness, subclass [`~trl.experimental.harbor.HarborEnv`] and add tool methods — every public method becomes a tool (TRL discovers them with `inspect.getmembers`), so give each a typed signature and a docstring (used to build the tool schema). Keep helpers underscore-prefixed. Use `self._exec(cmd)` to run shell commands in the sandbox, and set `PROMPT_SUFFIX` to append harness guidance to the task instruction: + +```python +from trl.experimental.harbor import HarborEnv + +class GrepEnv(HarborEnv): + PROMPT_SUFFIX = "\n\nUse `grep` and `read_file`. Submit by writing /workdir/answer.txt." + + def grep(self, pattern: str, path: str) -> str: + """Search for `pattern` under `path`. + + Args: + pattern: The regex to search for. + path: The file or directory to search. + """ + return self._exec(f"grep -rn {pattern!r} {path!r}") +``` + +## The sandbox backend + +`environment_type` is passed straight through to Harbor (not validated by TRL): + +```python +HarborSpec(dataset, environment_type="e2b") # cloud sandbox (offloads provisioning), needs E2B_API_KEY +HarborSpec(dataset, environment_type="docker") # default; needs a local Docker daemon +``` + +`e2b` is recommended for cluster training: only `environment.exec` crosses into the cloud sandbox, so the GPUs stay dedicated to the policy and you can run many rollouts concurrently. + +## Reward functions + +`spec.reward_funcs` defaults to an outcome reward — per rollout it reads the Harbor verifier's scalar (`env.reward`), computed once after the rollout by running the task's `tests/` verifier in the sandbox. For a custom reward, write a regular TRL reward function: + +```python +def my_reward(environments, **kwargs) -> list[float]: + return [env.reward for env in environments] +``` + +## API + +[[autodoc]] trl.experimental.harbor.HarborSpec + +[[autodoc]] trl.experimental.harbor.HarborEnv + +[[autodoc]] trl.experimental.harbor.HarborBashEnv + +## Limitations + +- The integration is in `trl.experimental` — APIs may change. Set `TRL_EXPERIMENTAL_SILENCE=1` to silence the warning in CI logs. +- Harbor's async sandbox client is bound to one event loop, so each env drives start/exec/verify synchronously on its own loop; sandbox provisioning is therefore sequential across the generation batch (cloud backends like `e2b` mitigate the per-sandbox cost). +- A single `HarborSpec` covers one task suite + one harness; multi-suite training is not supported yet. + +## Reference + +- [Harbor framework](https://www.harborframework.com) +- [Harbor RL training docs](https://www.harborframework.com/docs/training-workflows/rl) diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/index.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/index.md new file mode 100644 index 0000000000000000000000000000000000000000..8f01a7f41fa799e4431da7037a3ab630d0963bb5 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/index.md @@ -0,0 +1,159 @@ +
+ + + + +
+ +# TRL - Transformers Reinforcement Learning + +TRL is a full stack library where we provide a set of tools to train transformer language models with methods like Supervised Fine-Tuning (SFT), Group Relative Policy Optimization (GRPO), Direct Preference Optimization (DPO), Reward Modeling, and more. +The library is integrated with 🤗 [transformers](https://github.com/huggingface/transformers). + +## 🎉 What's New + +**TRL v1:** We released TRL v1 — a major milestone that marks a real shift in what TRL is. Read the [blog post](https://huggingface.co/blog/trl-v1) to learn more. + +**🚢 Harbor:** We now support [Harbor](harbor) — train agents against sandboxed task suites (instruction + sandbox image + in-sandbox verifier) via [`GRPOTrainer`]'s `environment_factory`. + +## Taxonomy + +Below is the current list of TRL trainers, organized by method type (⚡️ = vLLM support; 🧪 = experimental). + +
+
+ +### Online methods + +- [`GRPOTrainer`](grpo_trainer) ⚡️ +- [`RLOOTrainer`](rloo_trainer) ⚡️ +- [`OnlineDPOTrainer`](online_dpo_trainer) 🧪 ⚡️ +- [`NashMDTrainer`](nash_md_trainer) 🧪 ⚡️ +- [`PPOTrainer`](ppo_trainer) 🧪 +- [`XPOTrainer`](xpo_trainer) 🧪 ⚡️ + +### Reward modeling + +- [`RewardTrainer`](reward_trainer) +- [`PRMTrainer`](prm_trainer) 🧪 + +
+
+ +### Offline methods + +- [`SFTTrainer`](sft_trainer) +- [`DPOTrainer`](dpo_trainer) +- [`BCOTrainer`](bco_trainer) 🧪 +- [`CPOTrainer`](cpo_trainer) 🧪 +- [`KTOTrainer`](kto_trainer) 🧪 +- [`ORPOTrainer`](orpo_trainer) 🧪 + +### Knowledge distillation + +- [`GKDTrainer`](gkd_trainer) 🧪 +- [`MiniLLMTrainer`](minillm_trainer) 🧪 + +
+
+ +You can also explore TRL-related models, datasets, and demos in the [TRL Hugging Face organization](https://huggingface.co/trl-lib). + +## Learn + +Learn post-training with TRL and other libraries in 🤗 [smol course](https://github.com/huggingface/smol-course). + +## Contents + +The documentation is organized into the following sections: + +- **Getting Started**: installation and quickstart guide. +- **Conceptual Guides**: dataset formats, training FAQ, and understanding logs. +- **How-to Guides**: reducing memory usage, speeding up training, distributing training, etc. +- **Integrations**: DeepSpeed, Liger Kernel, PEFT, etc. +- **Examples**: example overview, community tutorials, etc. +- **API**: trainers, utils, etc. + +## Blog posts + + + +## Talks + + diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/installation.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/installation.md new file mode 100644 index 0000000000000000000000000000000000000000..6a4a9117d5168d8869b4cc3647c4a1da18fe93f3 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/installation.md @@ -0,0 +1,42 @@ +# Installation + +You can install TRL either from PyPI or from source: + +## PyPI + +Install the library with pip or [uv](https://docs.astral.sh/uv/): + + + + +uv is a fast Rust-based Python package and project manager. Refer to [Installation](https://docs.astral.sh/uv/getting-started/installation/) for installation instructions. + +```bash +uv pip install trl +``` + + + + +```bash +pip install trl +``` + + + + +## Source + +You can also install the latest version from source. First clone the repo and then run the installation with `pip`: + +```bash +git clone https://github.com/huggingface/trl.git +cd trl/ +pip install -e . +``` + +If you want the development install you can replace the pip install with the following: + +```bash +pip install -e ".[dev]" +``` diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/jobs_training.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/jobs_training.md new file mode 100644 index 0000000000000000000000000000000000000000..a1b0c66cfb1b9e830d78007bebd43c0c736b5b3b --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/jobs_training.md @@ -0,0 +1,275 @@ +# Training with Jobs + +[![model badge](https://img.shields.io/badge/All_models-HF_Jobs-blue)](https://huggingface.co/models?other=hf_jobs,trl) + +[Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs) lets you run training scripts on fully managed infrastructure—no need to manage GPUs or local environment setup. + +In this guide, you'll learn how to: + +* Use [TRL Jobs](https://github.com/huggingface/trl-jobs) to easily run pre-optimized TRL training +* Run any TRL training script with uv scripts + +For general details about Hugging Face Jobs (hardware selection, job monitoring, etc.), see the [Jobs documentation](https://huggingface.co/docs/huggingface_hub/guides/jobs). + +## Requirements + +* A [Pro](https://hf.co/pro), [Team](https://hf.co/enterprise), or [Enterprise](https://hf.co/enterprise) plan +* Logged in to the Hugging Face Hub (`hf auth login`) + +## Using TRL Jobs + +[TRL Jobs](https://github.com/huggingface/trl-jobs) is a high-level wrapper around Hugging Face Jobs and TRL that streamlines training. It provides optimized default configurations so you can start quickly without manually tuning parameters. + +Example: + +```bash +pip install trl-jobs +trl-jobs sft --model_name Qwen/Qwen3-0.6B --dataset_name trl-lib/Capybara +``` + +TRL Jobs supports everything covered in this guide, with additional optimizations to simplify workflows. + +## Using uv Scripts + +For more control, you can run Hugging Face Jobs directly with your own scripts, using [uv scripts](https://docs.astral.sh/uv/guides/scripts/). + +Create a Python script (e.g., `train.py`) containing your training code: + +```python +from datasets import load_dataset +from trl import SFTTrainer + +dataset = load_dataset("trl-lib/Capybara", split="train") +trainer = SFTTrainer( + model="Qwen/Qwen2.5-0.5B", + train_dataset=dataset, +) +trainer.train() +trainer.push_to_hub("Qwen2.5-0.5B-SFT") +``` + +Launch the job using either the [`hf jobs` CLI](https://huggingface.co/docs/huggingface_hub/guides/cli#hf-jobs) or the Python API: + + + + +```bash +hf jobs uv run \ + --flavor a100-large \ + --with trl \ + --secrets HF_TOKEN \ + train.py +``` + + + + +```python +from huggingface_hub import run_uv_job + +run_uv_job( + "train.py", + dependencies=["trl"], + flavor="a100-large", + secrets={"HF_TOKEN": "hf_..."}, +) +``` + + + + +To run successfully, the script needs: + +* **TRL installed**: Use the `--with trl` flag or the `dependencies` argument. uv installs these dependencies automatically before running the script. +* **An authentication token**: Required to push the trained model (or perform other authenticated operations). Provide it with the `--secrets HF_TOKEN` flag or the `secrets` argument. + +> [!WARNING] +> When training with Jobs, be sure to: +> +> * **Set a sufficient timeout**. Jobs time out after 30 minutes by default. If your job exceeds the timeout, it will fail and all progress will be lost. See [Setting a custom timeout](https://huggingface.co/docs/huggingface_hub/guides/jobs#setting-a-custom-timeout). +> * **Push the model to the Hub**. The Jobs environment is ephemeral—files are deleted when the job ends. If you don’t push the model, it will be lost. + +You can also run a script directly from a URL: + + + + +```bash +hf jobs uv run \ + --flavor a100-large \ + --with trl \ + --secrets HF_TOKEN \ + "https://gist.githubusercontent.com/qgallouedec/eb6a7d20bd7d56f9c440c3c8c56d2307/raw/69fd78a179e19af115e4a54a1cdedd2a6c237f2f/train.py" +``` + + + + +```python +from huggingface_hub import run_uv_job + +run_uv_job( + "https://gist.githubusercontent.com/qgallouedec/eb6a7d20bd7d56f9c440c3c8c56d2307/raw/69fd78a179e19af115e4a54a1cdedd2a6c237f2f/train.py", + flavor="a100-large", + dependencies=["trl"], + secrets={"HF_TOKEN": "hf_..."}, +) +``` + + + + +To make a script self-contained, declare dependencies at the top: + +```python +# /// script +# dependencies = [ +# "trl", +# "peft", +# ] +# /// + +from datasets import load_dataset +from peft import LoraConfig +from trl import SFTTrainer + +dataset = load_dataset("trl-lib/Capybara", split="train") + +trainer = SFTTrainer( + model="Qwen/Qwen2.5-0.5B", + train_dataset=dataset, + peft_config=LoraConfig(), +) +trainer.train() +trainer.push_to_hub("Qwen2.5-0.5B-SFT") +``` + +You can then run the script without specifying dependencies: + + + + +```bash +hf jobs uv run \ + --flavor a100-large \ + --secrets HF_TOKEN \ + train.py +``` + + + + +```python +from huggingface_hub import run_uv_job + +run_uv_job( + "train.py", + flavor="a100-large", + secrets={"HF_TOKEN": "hf_..."}, +) +``` + + + + +TRL example scripts are fully uv-compatible, so you can run a complete training workflow directly on Jobs. You can customize training with standard script arguments plus hardware and secrets: + + + + +```bash +hf jobs uv run \ + --flavor a100-large \ + --secrets HF_TOKEN \ + https://raw.githubusercontent.com/huggingface/trl/refs/heads/main/examples/scripts/prm.py \ + --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ + --dataset_name trl-lib/prm800k \ + --output_dir Qwen2-0.5B-Reward \ + --push_to_hub +``` + + + + +```python +from huggingface_hub import run_uv_job +run_uv_job( + "https://raw.githubusercontent.com/huggingface/trl/refs/heads/main/examples/scripts/prm.py", + flavor="a100-large", + secrets={"HF_TOKEN": "hf_..."}, + script_args=[ + "--model_name_or_path", "Qwen/Qwen2-0.5B-Instruct", + "--dataset_name", "trl-lib/prm800k", + "--output_dir", "Qwen2-0.5B-Reward", + "--push_to_hub" + ] +) +``` + + + + +See the full list of examples in [Example Scripts](example_overview#scripts). + +### Docker Images + +An up-to-date Docker image with all TRL dependencies is available at [huggingface/trl](https://hub.docker.com/r/huggingface/trl) and can be used directly with Hugging Face Jobs: + + + + +```bash +hf jobs uv run \ + --flavor a100-large \ + --secrets HF_TOKEN \ + --image huggingface/trl \ + train.py +``` + + + + +```python +from huggingface_hub import run_uv_job + +run_uv_job( + "train.py", + flavor="a100-large", + secrets={"HF_TOKEN": "hf_..."}, + image="huggingface/trl", +) +``` + + + + +Jobs runs on a Docker image from Hugging Face Spaces or Docker Hub, so you can also specify any custom image: + + + + +```bash +hf jobs uv run \ + --flavor a100-large \ + --secrets HF_TOKEN \ + --image \ + --secrets HF_TOKEN \ + train.py +``` + + + + +```python +from huggingface_hub import run_uv_job + +run_uv_job( + "train.py", + flavor="a100-large", + secrets={"HF_TOKEN": "hf_..."}, + image="", +) +``` + + + diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/kernels_hub.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/kernels_hub.md new file mode 100644 index 0000000000000000000000000000000000000000..f3d7ee124ba58be7f9bfd503dded52d4dc90a2b5 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/kernels_hub.md @@ -0,0 +1,96 @@ +# Kernels Hub Integration and Usage + +kernel-builder logo + +The [`kernels`](https://huggingface.co/blog/hello-hf-kernels#get-started-and-next-steps) library allows optimized compute kernels to be loaded directly from the Hub. +You can find `kernels` in [dedicated orgs](https://huggingface.co/kernels-community) or by searching for the [`kernel` tag](https://huggingface.co/models?other=kernel) within the Hub. + +Kernels are **optimized code pieces** that help in model development, training, and inference. Here, we’ll focus on their **integration with TRL**, but check out the above resources to learn more about them. + +## Installation + +To use kernels with TRL, you'd need to install the library in your Python environment: + +```bash +pip install kernels +``` + +## Using Kernels from the Hub in TRL + +Kernels can directly replace attention implementations, removing the need to manually compile attention backends like Flash Attention and boosting training speed just by pulling the respective attention kernel from the Hub. + +You can specify a kernel when loading a model: + + +```python +from transformers import AutoModelForCausalLM + +model = AutoModelForCausalLM.from_pretrained( + "your-model-name", + attn_implementation="kernels-community/flash-attn2" # other options: kernels-community/vllm-flash-attn3, kernels-community/paged-attention +) +``` + +Or when running a TRL training script: + +```bash +python sft.py ... --attn_implementation kernels-community/flash-attn2 +``` + +Or using the TRL CLI: + +```bash +trl sft ... --attn_implementation kernels-community/flash-attn2 +``` + +> [!TIP] +> Now you can leverage faster attention backends with a pre-optimized kernel for your hardware configuration from the Hub, speeding up both development and training. + +## Comparing Attention Implementations + +We evaluated various attention implementations available in transformers, along with different kernel backends, using **TRL** and **SFT**. +The experiments were run on a single **H100 GPU** with **CUDA 12.9**, leveraging **Qwen3-8B** with a **batch size of 8**, **gradient accumulation of 1**, and **bfloat16** precision. +Keep in mind that the results shown here are specific to this setup and may vary with different training configurations. + +The following figure illustrates both **latency** (time per training step) and **peak allocated memory** for the different attention implementations and kernel backends. +Kernel-based implementations perform on par with custom-installed attention, and increasing the model’s `max_length` further enhances performance. Memory consumption is similar across all implementations, showing no significant differences. We get the same performance but with less friction, as described in [the following section](#flash-attention-vs-hub-kernels). + +
+ Latency and Memory Usage + Latency and Memory Usage +
+ +## Flash Attention vs. Hub Kernels + +Building Flash Attention from source can be time-consuming, often taking anywhere from several minutes to hours, depending on your hardware, CUDA/PyTorch configuration, and whether precompiled wheels are available. + +In contrast, **Hugging Face Kernels** provide a much faster and more reliable workflow. Developers don’t need to worry about complex setups—everything is handled automatically. In our benchmarks, kernels were ready to use in about **2.5 seconds**, with no compilation required. This allows you to start training almost instantly, significantly accelerating development. Simply specify the desired version, and `kernels` takes care of the rest. + +## Combining FlashAttention Kernels with Liger Kernels + +You can combine **FlashAttention kernels** with **Liger kernels** for additional TRL performance improvements. + +First, install the Liger kernel dependency: + +```bash +pip install liger-kernel +``` + +Then, combine both in your code: + +```python +from transformers import AutoModelForCausalLM +from trl import SFTConfig + +model = AutoModelForCausalLM.from_pretrained( + "your-model-name", + attn_implementation="kernels-community/flash-attn2" # choose the desired FlashAttention variant +) + +training_args = SFTConfig( + use_liger_kernel=True, + # ... other TRL training args +) +``` + +Learn more about the [Liger Kernel Integration](./liger_kernel_integration). diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/kto_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/kto_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..708448620b00a4bd61ea121cdd40b4f85f228f19 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/kto_trainer.md @@ -0,0 +1,144 @@ +# KTO Trainer + +[![model badge](https://img.shields.io/badge/All_models-KTO-blue)](https://huggingface.co/models?other=kto,trl) + +> [!WARNING] +> As of TRL v1.0, `KTOTrainer` and `KTOConfig` have been moved to the `trl.experimental.kto` module. +> KTO API is experimental and may change at any time. +> Promoting KTO back into the stable API is a high-priority task: KTO is slated for refactoring to align with the standard core trainer architecture. + +## Overview + +Kahneman-Tversky Optimization (KTO) was introduced in [KTO: Model Alignment as Prospect Theoretic Optimization](https://huggingface.co/papers/2402.01306) by [Kawin Ethayarajh](https://huggingface.co/kawine), [Winnie Xu](https://huggingface.co/xwinxu), [Niklas Muennighoff](https://huggingface.co/Muennighoff), Dan Jurafsky, [Douwe Kiela](https://huggingface.co/douwekiela). + +The abstract from the paper is the following: + +> Kahneman & Tversky's prospect theory tells us that humans perceive random variables in a biased but well-defined manner; for example, humans are famously loss-averse. We show that objectives for aligning LLMs with human feedback implicitly incorporate many of these biases -- the success of these objectives (e.g., DPO) over cross-entropy minimization can partly be ascribed to them being human-aware loss functions (HALOs). However, the utility functions these methods attribute to humans still differ from those in the prospect theory literature. Using a Kahneman-Tversky model of human utility, we propose a HALO that directly maximizes the utility of generations instead of maximizing the log-likelihood of preferences, as current methods do. We call this approach Kahneman-Tversky Optimization (KTO), and it matches or exceeds the performance of preference-based methods at scales from 1B to 30B. Crucially, KTO does not need preferences -- only a binary signal of whether an output is desirable or undesirable for a given input. This makes it far easier to use in the real world, where preference data is scarce and expensive. + +The official code can be found in [ContextualAI/HALOs](https://github.com/ContextualAI/HALOs). + +This post-training method was contributed by [Kashif Rasul](https://huggingface.co/kashif), [Younes Belkada](https://huggingface.co/ybelkada), [Lewis Tunstall](https://huggingface.co/lewtun) and Pablo Vicente. + +## Quick start + +This example demonstrates how to train a model using the KTO method. We use the [Qwen 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) as the base model. We use the preference data from the [KTO Mix 14k](https://huggingface.co/datasets/trl-lib/kto-mix-14k). You can view the data in the dataset here: + + + +Below is the script to train the model: + +```python +# train_kto.py +from datasets import load_dataset +from trl.experimental.kto import KTOConfig, KTOTrainer +from transformers import AutoModelForCausalLM, AutoTokenizer + +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +train_dataset = load_dataset("trl-lib/kto-mix-14k", split="train") + +training_args = KTOConfig(output_dir="Qwen2-0.5B-KTO") +trainer = KTOTrainer(model=model, args=training_args, processing_class=tokenizer, train_dataset=train_dataset) +trainer.train() +``` + +Execute the script using the following command: + +```bash +accelerate launch train_kto.py +``` + +Distributed across 8 x H100 GPUs, the training takes approximately 30 minutes. You can verify the training progress by checking the reward graph. An increasing trend in the reward margin indicates that the model is improving and generating better responses over time. + +![kto qwen2 reward margin](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/kto-qwen2-reward-margin.png) + +To see how the [trained model](https://huggingface.co/trl-lib/Qwen2-0.5B-KTO) performs, you can use the [Transformers Chat CLI](https://huggingface.co/docs/transformers/quicktour#chat-with-text-generation-models). + +
$ transformers chat trl-lib/Qwen2-0.5B-KTO
+<quentin_gallouedec>:
+What is the best programming language?
+
+<trl-lib/Qwen2-0.5B-KTO>:
+The best programming language can vary depending on individual preferences, industry-specific requirements, technical skills, and familiarity with the specific use case or task. Here are some widely-used programming languages that have been noted as popular and widely used:
+
+Here are some other factors to consider when choosing a programming language for a project:
+
+ 1 JavaScript: JavaScript is at the heart of the web and can be used for building web applications, APIs, and interactive front-end applications like frameworks like React and Angular. It's similar to C, C++, and F# in syntax structure and is accessible and easy to learn, making it a popular choice for beginners and professionals alike.
+ 2 Java: Known for its object-oriented programming (OOP) and support for Java 8 and .NET, Java is used for developing enterprise-level software applications, high-performance games, as well as mobile apps, game development, and desktop applications.
+ 3 C++: Known for its flexibility and scalability, C++ offers comprehensive object-oriented programming and is a popular choice for high-performance computing and other technical fields. It's a powerful platform for building real-world applications and games at scale.
+ 4 Python: Developed by Guido van Rossum in 1991, Python is a high-level, interpreted, and dynamically typed language known for its simplicity, readability, and versatility.
+
+ +## Expected dataset format + +KTO requires an [unpaired preference dataset](dataset_formats#unpaired-preference). Alternatively, you can provide a *paired* preference dataset (also known simply as a *preference dataset*). In this case, the trainer will automatically convert it to an unpaired format by separating the chosen and rejected responses, assigning `label = True` to the chosen completions and `label = False` to the rejected ones. + +The [`experimental.kto.KTOTrainer`] supports both [conversational](dataset_formats#conversational) and [standard](dataset_formats#standard) dataset formats. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset. + +In theory, the dataset should contain at least one chosen and one rejected completion. However, some users have successfully run KTO using *only* chosen or only rejected data. If using only rejected data, it is advisable to adopt a conservative learning rate. + +## Example script + +We provide an example script to train a model using the KTO method. The script is available in [`trl/scripts/kto.py`](https://github.com/huggingface/trl/blob/main/trl/scripts/kto.py) + +To test the KTO script with the [Qwen2 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) on the [UltraFeedback dataset](https://huggingface.co/datasets/trl-lib/kto-mix-14k), run the following command: + +```bash +accelerate launch trl/scripts/kto.py \ + --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ + --dataset_name trl-lib/kto-mix-14k \ + --num_train_epochs 1 \ + --output_dir Qwen2-0.5B-KTO +``` + +## Usage tips + +### For Mixture of Experts Models: Enabling the auxiliary loss + +MOEs are the most efficient if the load is about equally distributed between experts. +To ensure that we train MOEs similarly during preference-tuning, it is beneficial to add the auxiliary loss from the load balancer to the final loss. + +This option is enabled by setting `output_router_logits=True` in the model config (e.g. [`~transformers.MixtralConfig`]). +To scale how much the auxiliary loss contributes to the total loss, use the hyperparameter `router_aux_loss_coef=...` (default: `0.001`) in the model config. + +### Batch size recommendations + +Use a per-step batch size that is at least 4, and an effective batch size between 16 and 128. Even if your effective batch size is large, if your per-step batch size is poor, then the KL estimate in KTO will be poor. + +### Learning rate recommendations + +Each choice of `beta` has a maximum learning rate it can tolerate before learning performance degrades. For the default setting of `beta = 0.1`, the learning rate should typically not exceed `1e-6` for most models. As `beta` decreases, the learning rate should also be reduced accordingly. In general, we strongly recommend keeping the learning rate between `5e-7` and `5e-6`. Even with small datasets, we advise against using a learning rate outside this range. Instead, opt for more epochs to achieve better results. + +### Imbalanced data + +The `desirable_weight` and `undesirable_weight` of the [`experimental.kto.KTOConfig`] refer to the weights placed on the losses for desirable/positive and undesirable/negative examples. +By default, they are both 1. However, if you have more of one or the other, then you should upweight the less common type such that the ratio of (`desirable_weight` \\(\times\\) number of positives) to (`undesirable_weight` \\(\times\\) number of negatives) is in the range 1:1 to 4:3. + +## Logged metrics + +While training and evaluating, we record the following reward metrics: + +- `rewards/chosen_sum`: the sum of log probabilities of the policy model for the chosen responses scaled by beta +- `rewards/rejected_sum`: the sum of log probabilities of the policy model for the rejected responses scaled by beta +- `logps/chosen_sum`: the sum of log probabilities of the chosen completions +- `logps/rejected_sum`: the sum of log probabilities of the rejected completions +- `logits/chosen_sum`: the sum of logits of the chosen completions +- `logits/rejected_sum`: the sum of logits of the rejected completions +- `count/chosen`: the count of chosen samples in a batch +- `count/rejected`: the count of rejected samples in a batch + +## KTOTrainer + +[[autodoc]] experimental.kto.KTOTrainer + - train + - save_model + - push_to_hub + +## KTOConfig + +[[autodoc]] experimental.kto.KTOConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/liger_kernel_integration.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/liger_kernel_integration.md new file mode 100644 index 0000000000000000000000000000000000000000..7a387c813fd3dd16b3daeca082e08e704eddaed4 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/liger_kernel_integration.md @@ -0,0 +1,78 @@ +# Liger Kernel Integration + +[Liger Kernel](https://github.com/linkedin/Liger-Kernel) is a collection of Triton kernels designed specifically for LLM training. It can effectively increase multi-GPU training throughput by 20% and reduce memory usage by 60%. That way, we can **4x** our context length, as described in the benchmark below. They have implemented Hugging Face compatible `RMSNorm`, `RoPE`, `SwiGLU`, `CrossEntropy`, `FusedLinearCrossEntropy`, with more to come. The kernel works out of the box with [FlashAttention](https://github.com/Dao-AILab/flash-attention), [PyTorch FSDP](https://pytorch.org/tutorials/intermediate/FSDP_tutorial.html), and [Microsoft DeepSpeed](https://github.com/microsoft/DeepSpeed). + +With this memory reduction, you can potentially turn off `cpu_offloading` or gradient checkpointing to further boost the performance. + +| Speed Up | Memory Reduction | +| --- | --- | +| ![Speed up](https://raw.githubusercontent.com/linkedin/Liger-Kernel/main/docs/images/e2e-tps.png) | ![Memory](https://raw.githubusercontent.com/linkedin/Liger-Kernel/main/docs/images/e2e-memory.png) | + +## Supported Trainers + +Liger Kernel is supported in the following TRL trainers: +- **SFT** (Supervised Fine-Tuning) +- **DPO** (Direct Preference Optimization) +- **GRPO** (Group Relative Policy Optimization) +- **KTO** (Kahneman-Tversky Optimization) +- **GKD** (Generalized Knowledge Distillation) + +## Usage + +1. First, install Liger Kernel: + + ```bash + pip install liger-kernel + ``` + +2. Once installed, set `use_liger_kernel=True` in your trainer config. No other changes are needed! + + + + +```python +from trl import SFTConfig + +training_args = SFTConfig(..., use_liger_kernel=True) +``` + + + + +```python +from trl import DPOConfig + +training_args = DPOConfig(..., use_liger_kernel=True) +``` + + + + +```python +from trl import GRPOConfig + +training_args = GRPOConfig(..., use_liger_kernel=True) +``` + + + + +```python +from trl import KTOConfig + +training_args = KTOConfig(..., use_liger_kernel=True) +``` + + + + +```python +from trl.experimental.gkd import GKDConfig + +training_args = GKDConfig(..., use_liger_kernel=True) +``` + + + + +To learn more about Liger-Kernel, visit their [official repository](https://github.com/linkedin/Liger-Kernel/). diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/lora_without_regret.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/lora_without_regret.md new file mode 100644 index 0000000000000000000000000000000000000000..c77392e2e19c7eeef2462d4cd862f1de451ca80c --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/lora_without_regret.md @@ -0,0 +1,346 @@ +# LoRA Without Regret + +Recent research from the team at [Thinking Machines Lab](https://thinkingmachines.ai/blog/lora/) (Schulman et al., 2025) shows that **LoRA can match full fine-tuning performance** when configured correctly, while using only ~67% of the compute. These findings are exciting to TRL users because they're straightforward to implement and can improve model performance on smaller budgets. + +This guide provides simple instructions to reproduce the results of the blog post in TRL. + +> [!TIP] +> It is recommended to read the blog post before following this guide, or to consult both resources in parallel for best results. + +## Benefits of LoRA over full fine-tuning + +First of all, let's remind ourselves of the benefits of [LoRA over full fine-tuning](https://huggingface.co/docs/trl/en/peft_integration). + +LoRA adds adapter layers on top of the base model, which contains significantly fewer parameters than the base model itself. This design reduces GPU memory requirements and enables more efficient training. As described in the [blog](https://thinkingmachines.ai/blog/lora/), this approach was originally thought to involve a performance trade-off, although careful configuration can overcome this trade-off and match full fine-tuning performance. + +## Examples with TRL + +Let's implement and train LoRA adapters in TRL scripts based on the core findings of the blog post. Afterwards, we'll revisit each finding in light of the TRL results. + +### Supervised Fine-Tuning (SFT) + +The blog post performs SFT on a range of models and datasets from the Hub, which we can reproduce in TRL. + +| Model | Dataset | +| --- | --- | +| [Llama-3.2-1B-Instruct](https://huggingface.co/meta-llama/Llama-3.2-1B) | [allenai/tulu-3-sft-mixture](https://huggingface.co/datasets/allenai/tulu-3-sft-mixture) | +| [Llama-3.2-1B-Instruct](https://huggingface.co/meta-llama/Llama-3.2-1B) | [open-thoughts/OpenThoughts-114k](https://huggingface.co/datasets/open-thoughts/OpenThoughts-114k) | +| [Llama-3.1-8B-Instruct](https://huggingface.co/meta-llama/Llama-3.1-8B) | [allenai/tulu-3-sft-mixture](https://huggingface.co/datasets/allenai/tulu-3-sft-mixture) | +| [Llama-3.1-8B-Instruct](https://huggingface.co/meta-llama/Llama-3.1-8B) | [open-thoughts/OpenThoughts-114k](https://huggingface.co/datasets/open-thoughts/OpenThoughts-114k) | + + + + +We can integrate these findings with the TRL Python API like so: + +```python + +from datasets import load_dataset +from peft import LoraConfig +from trl import SFTTrainer, SFTConfig + +dataset = load_dataset("open-thoughts/OpenThoughts-114k", split="train") + +peft_config = LoraConfig(r=256, lora_alpha=16, target_modules="all-linear") + +training_args = SFTConfig( + learning_rate=2e-4, + per_device_train_batch_size=1, + gradient_accumulation_steps=4, + num_train_epochs=1, + report_to=["trackio"], +) + +trainer = SFTTrainer( + model="Qwen/Qwen2.5-3B-Instruct", + train_dataset=dataset, + peft_config=peft_config, + args=training_args, +) + +trainer.train() + +``` + + + + +```bash + +hf jobs uv run \ + --flavor a100-large \ + --timeout 8h \ + --secrets HF_TOKEN \ + "https://raw.githubusercontent.com/huggingface/trl/main/trl/scripts/sft.py" \ + --model_name_or_path Qwen/Qwen2.5-3B-Instruct \ + --dataset_name open-thoughts/OpenThoughts-114k \ + --learning_rate 2.0e-5 \ + --num_train_epochs 1 \ + --packing \ + --per_device_train_batch_size 2 \ + --gradient_accumulation_steps 16 \ + --use_peft \ + --lora_r 256 \ + --lora_alpha 16 \ + --lora_target_modules all-linear \ + --output_dir Qwen2.5-3B-OpenThoughts-LoRA \ + --report_to trackio \ + --push_to_hub + +``` + +To use Hugging Face Jobs, you will need to be logged in to the Hugging Face Hub (`hf auth login`) and have a [Pro](https://hf.co/pro), [Team](https://hf.co/enterprise), or [Enterprise](https://hf.co/enterprise) plan. Check out the [Jobs documentation](https://huggingface.co/docs/huggingface_hub/en/guides/jobs) for more details. + + + + +```bash + +uv run "https://raw.githubusercontent.com/huggingface/trl/main/trl/scripts/sft.py" \ + --model_name_or_path Qwen/Qwen2.5-3B-Instruct \ + --dataset_name open-thoughts/OpenThoughts-114k \ + --learning_rate 2.0e-5 \ + --num_train_epochs 1 \ + --packing \ + --per_device_train_batch_size 2 \ + --gradient_accumulation_steps 16 \ + --eval_strategy no \ + --use_peft \ + --lora_r 256 \ + --lora_alpha 16 \ + --lora_target_modules all-linear \ + --output_dir Qwen2.5-3B-OpenThoughts-LoRA \ + --report_to trackio \ + --push_to_hub + +``` + +To run the script locally, you will need to have `uv` installed. Check out the [uv documentation](https://docs.astral.sh/uv/) for more details. + + + + +Once training starts, you can monitor the progress in [Trackio](https://huggingface.co/trackio), which will log the URL. + +### Reinforcement Learning (GRPO) + +The blog post performs GRPO on a range of models and datasets from the Hub, and once again we can reproduce the results in TRL. + +| Model | Dataset | +| --- | --- | +| [Llama-3.1-8B-Base](https://huggingface.co/meta-llama/Llama-3.2-1B) | [GSM8k](https://huggingface.co/datasets/openai/gsm8k) | +| [Llama-3.1-8B-Base](https://huggingface.co/meta-llama/Llama-3.2-1B) | [DeepMath-103K](https://huggingface.co/datasets/zwhe99/DeepMath-103K) | +| [Qwen3-8b-base](https://huggingface.co/Qwen/Qwen3-8b-base) | [DeepMath-103K](https://huggingface.co/datasets/zwhe99/DeepMath-103K) | + +For reinforcement learning, the blog uses a math reasoning task that we can reproduce as a Python function. + + + + +We can implement these recommendations with the TRL Python API like so: + +```python + +from datasets import load_dataset +from peft import LoraConfig +from trl import GRPOConfig, GRPOTrainer +from trl.rewards import reasoning_accuracy_reward + +dataset = load_dataset("HuggingFaceH4/OpenR1-Math-220k-default-verified", split="train") + +peft_config = LoraConfig( + r=1, + lora_alpha=32, + target_modules="all-linear" +) + +training_args = GRPOConfig( + learning_rate=5e-5, + per_device_train_batch_size=1, + gradient_accumulation_steps=4, + num_train_epochs=1, + num_generations=8, + generation_batch_size=8, + report_to=["trackio"], +) + +trainer = GRPOTrainer( + model="Qwen/Qwen3-0.6B", + reward_funcs=reasoning_accuracy_reward, + args=training_args, + train_dataset=dataset, + peft_config=peft_config, +) + +trainer.train() + +``` + +> [!WARNING] +> This snippet skips the reward function which is defined above to keep the example concise. + + + + +```bash + +hf jobs uv run \ + --flavor a100-large \ + --timeout 4h \ + --secrets HF_TOKEN \ + --env PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \ + "https://huggingface.co/datasets/burtenshaw/lora-without-regrets/resolve/main/grpo.py" \ + --model_name_or_path Qwen/Qwen3-0.6B \ + --dataset_name HuggingFaceH4/OpenR1-Math-220k-default-verified \ + --output_dir grpo-full-qwen3-0.6b \ + --learning_rate 1.0e-6 \ + --lr_scheduler_type cosine \ + --warmup_steps 0.0 \ + --max_grad_norm 1.0 \ + --beta 0.0 \ + --max_completion_length 4096 \ + --num_generations 16 \ + --generation_batch_size 16 \ + --gradient_accumulation_steps 8 \ + --per_device_train_batch_size 1 \ + --num_train_epochs 1 \ + --lora_r 1 \ + --lora_alpha 32 \ + --lora_dropout 0.0 \ + --lora_target_modules all-linear \ + --vllm_mode colocate \ + --save_strategy steps \ + --save_steps 50 \ + --save_total_limit 1 \ + --logging_steps 1 \ + --max_steps 200 \ + --report_to trackio +``` + +To use Hugging Face Jobs, you will need to be logged in to the Hugging Face Hub (`hf auth login`) and have a [Pro](https://hf.co/pro), [Team](https://hf.co/enterprise), or [Enterprise](https://hf.co/enterprise) plan. Check out the [Jobs documentation](https://huggingface.co/docs/huggingface_hub/en/guides/jobs) for more details. + + + + +```bash +uv run "https://huggingface.co/datasets/burtenshaw/lora-without-regrets/resolve/main/grpo.py" \ + --model_name_or_path Qwen/Qwen3-0.6B \ + --dataset_name HuggingFaceH4/OpenR1-Math-220k-default-verified \ + --output_dir grpo-full-qwen3-0.6b \ + --learning_rate 1.0e-6 \ + --lr_scheduler_type cosine \ + --warmup_steps 0.0 \ + --max_grad_norm 1.0 \ + --beta 0.0 \ + --max_completion_length 4096 \ + --num_generations 16 \ + --generation_batch_size 16 \ + --gradient_accumulation_steps 8 \ + --per_device_train_batch_size 1 \ + --num_train_epochs 1 \ + --lora_r 1 \ + --lora_alpha 32 \ + --lora_dropout 0.0 \ + --lora_target_modules all-linear \ + --vllm_mode colocate \ + --save_strategy steps \ + --save_steps 50 \ + --save_total_limit 1 \ + --logging_steps 1 \ + --max_steps 200 \ + --report_to trackio +``` + +To run the script locally, you will need to have `uv` installed. Check out the [uv documentation](https://docs.astral.sh/uv/) for more details. + + + + +The reinforcement learning script with GRPO is implemented as a custom script in TRL, which uses the reward function shown above. You can review it at [`grpo.py`](https://huggingface.co/datasets/burtenshaw/lora-without-regrets/blob/main/grpo.py) - Reinforcement learning with LoRA best practices + +## Key findings in optimizing LoRA + +The authors recommend applying LoRA to all weight matrices rather than limiting it to attention layers, as increasing the rank does not compensate for this restriction. In TRL, this can be configured using `--lora_target_modules all-linear` to apply LoRA to all weight matrices. + +We were able to reproduce the results of the blog post using TRL and the SmolLM3 model. We trained the model for 500 steps on the [Math 220k dataset](https://huggingface.co/datasets/HuggingFaceH4/OpenR1-Math-220k-default-verified) with the reward function and configuration above. As you can see in the figure below, the LoRA model's average train reward curve matches the full fine-tuning curve. + +![train reward](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/lora_without_regret/5.png) + +And most importantly, the LoRA model uses significantly less memory than the full fine-tuning model, as we can see in the figure below. + +![memory usage](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/lora_without_regret/6.png) + +Here are the parameters we used to train the above models + +| Parameter | LoRA | Full FT | +| --- | --- | --- | +| `--model_name_or_path` | HuggingFaceTB/SmolLM3-3B | HuggingFaceTB/SmolLM3-3B | +| `--dataset_name` | HuggingFaceH4/OpenR1-Math-220k-default-verified | HuggingFaceH4/OpenR1-Math-220k-default-verified | +| `--learning_rate` | 1.0e-5 | 1.0e-6 | +| `--max_completion_length` | 4096 | 4096 | +| `--lora_r` | 1 | - | +| `--lora_alpha` | 32 | - | +| `--lora_dropout` | 0.0 | - | +| `--lora_target_modules` | all-linear | - | + +Let's break down the key findings of the blog post and how we were able to reproduce them. + +### 1. *LoRA performs better when applied to all weight matrices* + +The authors recommend applying LoRA to all weight matrices rather than limiting it to attention layers, as increasing the rank does not compensate for this restriction. + +![all layers](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/lora_without_regret/1.png) + +Attention-only LoRA underperforms even when using a higher rank to match parameter count. In TRL, this can be configured using `--lora_target_modules all-linear` to apply LoRA to all weight matrices. In Python, we can do this like so: + +```python +from peft import LoraConfig + +peft_config = LoraConfig(target_modules="all-linear") +``` + +### 2. *The adapter needs sufficient capacity to learn from the dataset* + +The blog post recommends using a sufficient LoRA rank to learn from the dataset. The rank determines the number of trainable parameters in the LoRA adapter. Therefore, "For datasets that exceed LoRA capacity, LoRA underperforms FullFT". + +![learning rate](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/lora_without_regret/3.png) + +In the TRL script, we could use `--lora_r` to set the rank and adapt it based on the task and dataset we're training on. The blog post recommends the following ranks based on the task and dataset size: + +Reinforcement learning tasks typically require lower capacity, so smaller LoRA ranks can be used. This is because policy gradient algorithms extract roughly ~1 bit of information per episode, demanding minimal parameter capacity. + +The blog post defines the ideal dataset size for LoRA to match full fine-tuning as "Post-training scale". Which we can use to determine the recommended rank for SFT and RL LoRAs as: + +| Task Type | Dataset Size | Recommended Rank | +| --- | --- | --- | +| **SFT** | Post-training scale | 256 | +| **RL** | Any size | 1-32 | + +### 3. *"FullFT and high-rank LoRAs have similar learning curves"* + +Counterintuitively, the blog post recommends using a higher learning rate than for full fine-tuning. In the table above, we used 1.0e-5 for LoRA and 1.0e-6 for full fine-tuning. In the TRL script, we could use `--learning_rate` to set the learning rate. The \\( \frac{1}{r} \\) scaling in LoRA makes the optimal learning rate approximately rank-independent. + +![learning rate](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/lora_without_regret/2.png) + +### 4. *"In some scenarios, LoRA is less tolerant of large batch sizes than full fine-tuning."* + +The blog post recommends using an effective batch size < 32 because the authors found LoRA to be less tolerant of large batch sizes. This could not be mitigated by increasing the LoRA rank. In the TRL script, we could use `--per_device_train_batch_size` and `--gradient_accumulation_steps` to set the batch size. + +![learning rate](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/lora_without_regret/4.png) + +## Takeaways + +Using TRL, you can efficiently implement LoRA adapters to match full fine-tuning performance, applying the core insights (targeting all weight matrices, choosing the right rank, and managing batch size and learning rate) without the heavy compute cost of FullFT. + +## Citation + +```bibtex +@article{schulman2025lora, + title = {{LoRA Without Regret}}, + author = {John Schulman and Thinking Machines Lab}, + year = 2025, + journal = {Thinking Machines Lab: Connectionism}, + doi = {10.64434/tml.20250929}, + note = {https://thinkingmachines.ai/blog/lora/} +} +``` diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/merge_model_callback.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/merge_model_callback.md new file mode 100644 index 0000000000000000000000000000000000000000..fd7241e7d15f070698410505ccdadc041726e466 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/merge_model_callback.md @@ -0,0 +1,3 @@ +# MergeModelCallback + +[[autodoc]] experimental.merge_model_callback.MergeModelCallback diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/minillm_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/minillm_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..ca4c46680544c1db7e4a6e5a4ce30452516347fc --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/minillm_trainer.md @@ -0,0 +1,67 @@ +# MiniLLM Trainer + +[![All_models-MiniLLM-blue](https://img.shields.io/badge/All_models-MiniLLM-blue)](https://huggingface.co/models?other=minillm,trl) + +## Overview + +TRL supports the MiniLLM Trainer for distilling large language models into smaller ones using reverse KLD for better precision, quality, and performance, as described in the paper [Knowledge Distillation of Large Language Models](https://huggingface.co/papers/2306.08543) by [Yuxian Gu](https://huggingface.co/t1101675), [Li Dong](https://huggingface.co/unilm), [Furu Wei](https://huggingface.co/thegenerality), and Minlie Huang. +The abstract from the paper is the following: + +> Knowledge Distillation (KD) is a promising technique for reducing the high computational demand of large language models (LLMs). However, previous KD methods are primarily applied to white-box classification models or training small models to imitate black-box model APIs like ChatGPT. How to effectively distill the knowledge from white-box generative LLMs is still under-explored, which becomes more and more important with the prosperity of LLMs. In this work, we propose MiniLLM that distills smaller language models from generative larger language models. We first replace the forward Kullback-Leibler divergence (KLD) objective in the standard KD approaches with reverse KLD, which is more suitable for KD on generative language models, to prevent the student model from overestimating the low-probability regions of the teacher distribution. Then, we derive an effective optimization approach to learn this objective. Extensive experiments in the instruction-following setting show that the MiniLLM models generate more precise responses with the higher overall quality, lower exposure bias, better calibration, and higher long-text generation performance. Our method is also scalable for different model families with 120M to 13B parameters. We will release our code and model checkpoints at https://aka.ms/MiniLLM. + +This post-training method was contributed by [Yuxian Gu](https://huggingface.co/t1101675). + +It is a generalized version of [Think Machine Lab's On-Policy Distillation](https://thinkingmachines.ai/blog/on-policy-distillation/), with the option to add distribution-level single-step distillation signals (like GKD when `beta=1`) and long-context reverse KLD signals. + +$$ +\begin{align} +L_{\text{MiniLLM}}&=\alpha_1\mathbb{E}_{x\sim \pi_{\theta}}\sum_{t'=t}^{|x|}\frac{\gamma^{t'-t}}{\sum_{t'}\gamma^{t'-t}}\left[\log \frac{\pi_{\theta}(x_{t'+1}|x_{1..t'})}{\pi_{\text{teacher}}(x_{t'+1}|x_{1..t'})}\right] \\ +&+ \alpha_2\mathbb{E}_{x\sim \pi_{\theta}} \text{KL}\left[\pi_\theta(\cdot|x_{1..t})||\pi_{\text{teacher}}(\cdot | x_{1..t})\right]. +\end{align} +$$ + +When \\( \alpha_1=1 \\), \\( \alpha_2=0 \\), \\( \gamma=0 \\), which corresponds to + +```python +from trl.experimental.minillm import MiniLLMConfig + +training_args = MiniLLMConfig( + rkl_advantage=True, + single_step_decomposition=False, + gamma=False +) +``` + +\\( L_{\text{MiniLLM}} \\) becomes the on-policy KD implemented in [Tinker](https://github.com/thinking-machines-lab/tinker-cookbook/blob/5d08be6d130596b7bedd02197861c41fa81ea436/tinker_cookbook/distillation/train_on_policy.py#L88): + +$$ +L_{\text{tinker}}=\mathbb{E}_{x\sim \pi_{\theta}}\left[\log \frac{\pi_{\theta}(x_{t'+1}|x_{1..t'})}{\pi_{\text{teacher}}(x_{t'+1}|x_{1..t'})}\right]. +$$ + +When \\( \alpha_1=0 \\), \\( \alpha_2=1 \\), which corresponds to + +```python +from trl.experimental.minillm import MiniLLMConfig + +training_args = MiniLLMConfig( + rkl_advantage=False, + single_step_decomposition=True +) +``` + +\\( L_{\text{MiniLLM}} \\) becomes the reverse KLD version of the GKD loss as in [GKD Trainer](gkd_trainer): + +$$ +L_{\text{GKD-RKL}}=\mathbb{E}_{x\sim \pi_{\theta}} \text{KL}\left[\pi_\theta(\cdot|x_{1..t})||\pi_{\text{teacher}}(\cdot | x_{1..t})\right]. +$$ + +## MiniLLMTrainer + +[[autodoc]] experimental.minillm.MiniLLMTrainer + - train + - save_model + - push_to_hub + +## MiniLLMConfig + +[[autodoc]] experimental.minillm.MiniLLMConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/nash_md_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/nash_md_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..74ff77c593ff721f38a78df4ca18218c80cbc44c --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/nash_md_trainer.md @@ -0,0 +1,140 @@ +# Nash-MD Trainer + +[![model badge](https://img.shields.io/badge/All_models-Nash--MD-blue)](https://huggingface.co/models?other=nash-md,trl) + +## Overview + +Nash-MD was proposed in the paper [Nash Learning from Human Feedback](https://huggingface.co/papers/2312.00886) by Rémi Munos, [Michal Valko](https://huggingface.co/misovalko), Daniele Calandriello, Mohammad Gheshlaghi Azar, Mark Rowland, Daniel Guo, Yunhao Tang, Matthieu Geist, Thomas Mésnard, and Andrea Michi. + +The abstract from the paper is the following: + +> Reinforcement learning from human feedback (RLHF) has emerged as the main paradigm for aligning large language models (LLMs) with human preferences. Typically, RLHF involves the initial step of learning a reward model from human feedback, often expressed as preferences between pairs of text generations produced by a pre-trained LLM. Subsequently, the LLM's policy is fine-tuned by optimizing it to maximize the reward model through a reinforcement learning algorithm. However, an inherent limitation of current reward models is their inability to fully represent the richness of human preferences and their dependency on the sampling distribution. In this study, we introduce an alternative pipeline for the fine-tuning of LLMs using pairwise human feedback. Our approach entails the initial learning of a preference model, which is conditioned on two inputs given a prompt, followed by the pursuit of a policy that consistently generates responses preferred over those generated by any competing policy, thus defining the Nash equilibrium of this preference model. We term this approach Nash learning from human feedback (NLHF). In the context of a tabular policy representation, we present a novel algorithmic solution, Nash-MD, founded on the principles of mirror descent. This algorithm produces a sequence of policies, with the last iteration converging to the regularized Nash equilibrium. Additionally, we explore parametric representations of policies and introduce gradient descent algorithms for deep-learning architectures. To demonstrate the effectiveness of our approach, we present experimental results involving the fine-tuning of a LLM for a text summarization task. We believe NLHF offers a compelling avenue for preference learning and policy optimization with the potential of advancing the field of aligning LLMs with human preferences. + +This post-training method was contributed by [Kashif Rasul](https://huggingface.co/kashif) and [Daniil Tiapkin](https://huggingface.co/dtiapkin), [Pierre Ménard](https://huggingface.co/menardprr), Daniele Calandriello and [Quentin Gallouédec](https://huggingface.co/qgallouedec). + +## Quick start + +This example demonstrates how to train a model using the Nash-MD method. We use the [Qwen 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) as the base model and the [trl-lib/Qwen2-0.5B-Reward](https://huggingface.co/trl-lib/Qwen2-0.5B-Reward) reward model. We use the prompts from the [UltraFeedback dataset](https://huggingface.co/datasets/openbmb/UltraFeedback). You can view the prompts in the dataset here: + + + +Below is the script to train the model: + +```python +# train_nash_md.py +from datasets import load_dataset +from trl.experimental.nash_md import NashMDConfig, NashMDTrainer +from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer + +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +reward_model = AutoModelForSequenceClassification.from_pretrained("trl-lib/Qwen2-0.5B-Reward", num_labels=1) +train_dataset = load_dataset("trl-lib/ultrafeedback-prompt", split="train") + +training_args = NashMDConfig(output_dir="Qwen2-0.5B-NashMD") +trainer = NashMDTrainer( + model=model, reward_funcs=reward_model, args=training_args, processing_class=tokenizer, train_dataset=train_dataset +) +trainer.train() +``` + +Execute the script using the following command: + +```bash +accelerate launch train_nash_md.py +``` + +Distributed across 8 GPUs, the training takes approximately 3 hours. + +To see how the [trained model](https://huggingface.co/trl-lib/Qwen2-0.5B-NashMD) performs, you can use the [Transformers Chat CLI](https://huggingface.co/docs/transformers/quicktour#chat-with-text-generation-models). + +
$ transformers chat trl-lib/Qwen2-0.5B-NashMD
+<quentin_gallouedec>:
+What is the best programming language?
+
+<trl-lib/Qwen2-0.5B-NashMD>:
+The best programming language depends on personal preference, the complexity of the project, and the specific requirements of the task. Some programming languages that are often recommended include Python, Java, and JavaScript, and there are many other languages to choose from depending on individual needs.
+
+ +## Expected dataset type + +Nash-MD requires a [prompt-only dataset](dataset_formats#prompt-only). The [`experimental.nash_md.NashMDTrainer`] supports both [conversational](dataset_formats#conversational) and [standard](dataset_formats#standard) dataset formats. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset. + +## Usage tips + +### Encourage EOS token generation + +We may want the model to generate completions within a given length. During training, the model will generate completions up to the maximum length specified in the `max_new_tokens` argument of [`experimental.nash_md.NashMDConfig`]. If you want to penalize the model for not generating an EOS token before reaching the maximum length, you can use the `missing_eos_penalty` argument of [`experimental.nash_md.NashMDConfig`]: + +```python +training_args = NashMDConfig(..., max_new_tokens=128, missing_eos_penalty=1.0) +``` + +> [!WARNING] +> Make sure that the SFT model and reward model use the _same_ chat template and the same tokenizer. Otherwise, you may find the model completions are scored incorrectly during training. + +### Logging Completions + +To better understand your model's behavior during training, you can log sample completions periodically using the [`LogCompletionsCallback`]. + +```python +trainer = NashMDTrainer(..., eval_dataset=eval_dataset) +completions_callback = LogCompletionsCallback(trainer, num_prompts=8) +trainer.add_callback(completions_callback) +``` + +This callback logs the model's generated completions directly to Weights & Biases. + +![Logged Completions](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/wandb_completions.png) + +## Example script + +We provide an example script to train a model using the Nash-MD method. The script is available in [`examples/scripts/nash_md.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/nash_md.py) + +To test the Nash-MD script with the [Qwen2.5 0.5B model](https://huggingface.co/trl-lib/Qwen/Qwen2.5-0.5B-Instruct) on the [UltraFeedback dataset](https://huggingface.co/datasets/openbmb/UltraFeedback), run the following command: + +```bash +python examples/scripts/nash_md.py \ + --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ + --reward_model_path trl-lib/Qwen2-0.5B-Reward \ + --dataset_name trl-lib/ultrafeedback-prompt \ + --learning_rate 5.0e-7 \ + --output_dir Qwen2.5-0.5B-NashMD \ + --warmup_steps 0.1 \ + --push_to_hub +``` + +## Logged metrics + +While training and evaluating, we record the following reward metrics: + +* `loss/kl`: The mean KL divergence between the model and reference data. +* `objective/entropy`: The mean entropy of the model and reference data. +* `loss/score`: The mean reinforce score loss. +* `rewards/chosen`: The mean scores (according to the reward model) of the model completions. +* `rewards/rejected`: The mean scores (according to the reward model) of the mixture completions. +* `rewards/probabilities`: The mean probability (according to the reward model) of the model completions chosen vs the mixture completion. +* `rewards/accuracies`: The accuracies of the Nash-MD's implicit reward model. +* `rewards/margins`: The mean reward margin (according to reward model) between the chosen and mixture completions. +* `logps/chosen`: The mean log probabilities of the chosen completions. +* `logps/rejected`: The mean log probabilities of the reference completions. +* `val/model_contain_eos_token`: The amount of times the model's output contains the eos token. +* `val/ref_contain_eos_token`: The amount of times the mixture's output contains the eos token. +* `beta`: The parameter that controls the weight of the loss term representing the deviation from the reference model. Typically fixed, but can be made dynamic by passing a list to [`experimental.nash_md.NashMDConfig`]. +* `mixture_coef`: Logit mixture coefficient for the model and reference model. Typically fixed, but can be made dynamic by passing a list to [`experimental.nash_md.NashMDConfig`]. + +## NashMDTrainer + +[[autodoc]] experimental.nash_md.NashMDTrainer + - train + - save_model + - push_to_hub + +## NashMDConfig + +[[autodoc]] experimental.nash_md.NashMDConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/online_dpo_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/online_dpo_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..b82029f13fc71286498429166f0a7ba3e8ab6a5c --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/online_dpo_trainer.md @@ -0,0 +1,206 @@ +# Online DPO Trainer + +[![model badge](https://img.shields.io/badge/All_models-Online_DPO-blue)](https://huggingface.co/models?other=online-dpo,trl) + +## Overview + +Online DPO was proposed in [Direct Language Model Alignment from Online AI Feedback](https://huggingface.co/papers/2402.04792) by Shangmin Guo, Biao Zhang, Tianlin Liu, Tianqi Liu, Misha Khalman, Felipe Llinares, Alexandre Rame, Thomas Mesnard, Yao Zhao, Bilal Piot, Johan Ferret, and Mathieu Blondel. + +The abstract from the paper is the following: + +> Direct alignment from preferences (DAP) methods, such as DPO, have recently emerged as efficient alternatives to reinforcement learning from human feedback (RLHF), that do not require a separate reward model. However, the preference datasets used in DAP methods are usually collected ahead of training and never updated, thus the feedback is purely offline. Moreover, responses in these datasets are often sampled from a language model distinct from the one being aligned, and since the model evolves over training, the alignment phase is inevitably off-policy. In this study, we posit that online feedback is key and improves DAP methods. Our method, online AI feedback (OAIF), uses an LLM as annotator: on each training iteration, we sample two responses from the current model and prompt the LLM annotator to choose which one is preferred, thus providing online feedback. Despite its simplicity, we demonstrate via human evaluation in several tasks that OAIF outperforms both offline DAP and RLHF methods. We further show that the feedback leveraged in OAIF is easily controllable, via instruction prompts to the LLM annotator. + +This post-training method was contributed by [Michael Noukhovitch](https://huggingface.co/mnoukhov), [Shengyi Costa Huang](https://huggingface.co/vwxyzjn), [Quentin Gallouédec](https://huggingface.co/qgallouedec), and [Edward Beeching](https://huggingface.co/edbeeching). + +## Quick start + +This example demonstrates how to train a model using the online DPO method. We use the [Qwen 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) as the base model and the [trl-lib/Qwen2-0.5B-Reward](https://huggingface.co/trl-lib/Qwen2-0.5B-Reward) reward model. We use the prompts from the [UltraFeedback dataset](https://huggingface.co/datasets/openbmb/UltraFeedback). You can view the prompts in the dataset here: + + + +Below is the script to train the model: + +```python +# train_online_dpo.py +from datasets import load_dataset +from trl.experimental.online_dpo import OnlineDPOConfig, OnlineDPOTrainer +from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer + +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +reward_model = AutoModelForSequenceClassification.from_pretrained("trl-lib/Qwen2-0.5B-Reward", num_labels=1) +train_dataset = load_dataset("trl-lib/ultrafeedback-prompt", split="train") + +training_args = OnlineDPOConfig(output_dir="Qwen2-0.5B-OnlineDPO") +trainer = OnlineDPOTrainer( + model=model, reward_funcs=reward_model, args=training_args, processing_class=tokenizer, train_dataset=train_dataset +) +trainer.train() +``` + +Execute the script using the following command: + +```bash +accelerate launch train_online_dpo.py +``` + +Distributed across 8 GPUs, the training takes approximately 1 hour. You can verify the training progress by checking the reward graph. An increasing trend in both the reward for rejected and chosen completions indicates that the model is improving and generating better responses over time. + +![](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/online-dpo-qwen2.png) + +To see how the [trained model](https://huggingface.co/trl-lib/Qwen2-0.5B-OnlineDPO) performs, you can use the [Transformers Chat CLI](https://huggingface.co/docs/transformers/quicktour#chat-with-text-generation-models). + +
$ transformers chat trl-lib/Qwen2-0.5B-OnlineDPO
+<quentin_gallouedec>:
+What is the best programming language?
+
+<trl-lib/Qwen2-0.5B-OnlineDPO>:
+The best programming language depends on your specific needs and priorities. Some people prefer imperative programming languages (like Haskell or Lisp), while others prefer functional programming languages (like Scala or Python). It's important to consider your work style, programming environment, and project requirements when choosing a programming language.
+
+ +## Expected dataset type + +Online DPO only requires a [prompt-only dataset](dataset_formats#prompt-only) (unlike offline DPO, that expects [preference dataset](dataset_formats#preference)). The [`experimental.online_dpo.OnlineDPOTrainer`] supports both [conversational](dataset_formats#conversational) and [standard](dataset_formats#standard) dataset formats. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset. + +## Usage tips + +### Encourage EOS token generation + +When using a reward model, we may want the model to generate completions within a given length. During training, the model will generate completions up to the maximum length specified in the `max_new_tokens` argument of [`experimental.online_dpo.OnlineDPOConfig`]. If you want to penalize the model for not generating an EOS token before reaching the maximum length, you can use the `missing_eos_penalty` argument of [`experimental.online_dpo.OnlineDPOConfig`]: + +```python +training_args = OnlineDPOConfig(..., max_new_tokens=128, missing_eos_penalty=1.0) +``` + +### Logging Completions + +To better understand your model's behavior during training, you can log sample completions periodically using the [`LogCompletionsCallback`]. + +```python +trainer = OnlineDPOTrainer(..., eval_dataset=eval_dataset) +completions_callback = LogCompletionsCallback(trainer, num_prompts=8) +trainer.add_callback(completions_callback) +``` + +This callback logs the model's generated completions directly to Weights & Biases. + +![Logged Completions](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/wandb_completions.png) + +## Example script + +We provide an example script to train a model using the online DPO method. The script is available in [`examples/scripts/dpo_online.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/dpo_online.py) + +To test the online DPO script with the [Qwen2.5 0.5B model](https://huggingface.co/trl-lib/Qwen/Qwen2.5-0.5B-Instruct) on the [UltraFeedback dataset](https://huggingface.co/datasets/openbmb/UltraFeedback), run the following command: + +```bash +python examples/scripts/dpo_online.py \ + --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ + --reward_model_path trl-lib/Qwen2-0.5B-Reward \ + --dataset_name trl-lib/ultrafeedback-prompt \ + --learning_rate 5.0e-7 \ + --output_dir Qwen2.5-0.5B-Online-DPO \ + --warmup_steps 0.1 \ + --push_to_hub +``` + +## Logged metrics + +While training and evaluating, we record the following reward metrics. Here is an example [tracked run at Weights and Biases](https://wandb.ai/huggingface/trl/runs/w4apmsi9) + +* `objective/kl`: The mean Kullback-Leibler (KL) divergence between the current model and reference model. +* `objective/entropy`: The mean entropy of the model, indicating the randomness of the actions chosen by the model. +* `objective/non_score_reward`: The mean reward from non-score-related sources, basically `beta * kl.sum(1)`, where `beta` is the KL penalty coefficient and `kl` is the per-token KL divergence. +* `objective/rlhf_reward`: The mean RLHF reward, which is `scores - non_score_reward`. The `rlhf_reward` is the ultimate objective of online DPO training. If training works as intended, this metric should keep going up. +* `objective/scores`: The mean scores returned by the reward model. +* `objective/scores_margin`: The mean score margin (according to the external reward model) between the chosen and rejected completions. +* `rewards/chosen`: The mean reward (according to online DPO's implicit reward model)of the chosen completions. +* `rewards/rejected`: The mean reward (according to online DPO's implicit reward model) of the rejected completions. +* `rewards/accuracies`: The accuracies of the online DPO's implicit reward model. +* `rewards/margins`: The mean reward margin (according to online DPO's implicit reward model) between the chosen and rejected completions. +* `logps/chosen`: The mean log probabilities of the chosen completions. +* `logps/rejected`: The mean log probabilities of the rejected completions. +* `val/contain_eos_token`: The fraction of completions which contain an EOS token. +* `beta`: The parameter that controls the weight of the loss term representing the deviation from the reference model. Typically fixed, but can be made dynamic by passing a list to [`experimental.online_dpo.OnlineDPOConfig`]. + +## Benchmark experiments + +To validate the online DPO implementation works, we ran experiments with the Pythia 1B, 2.8B, and 6.9B models on a single node of 8 x H100s. Here are the commands we used to run the experiments. We take the SFT / RM models directly from [The N+ Implementation Details of RLHF with PPO: A Case Study on TL;DR Summarization](https://huggingface.co/papers/2403.17031). + +```shell +# 1B Online DPO experiment +accelerate launch --config_file examples/accelerate_configs/multi_gpu.yaml \ + examples/scripts/dpo_online.py \ + --model_name_or_path trl-lib/pythia-1b-deduped-tldr-sft \ + --reward_model_path trl-lib/pythia-1b-deduped-tldr-rm \ + --dataset_name trl-lib/tldr \ + --learning_rate 5.0e-7 \ + --output_dir pythia-1b-deduped-tldr-online-dpo \ + --beta 0.1 \ + --per_device_train_batch_size 8 \ + --gradient_accumulation_steps 2 \ + --num_train_epochs 3 \ + --max_new_tokens 53 \ + --warmup_steps 0.1 \ + --missing_eos_penalty 1.0 \ + --save_steps 0.1 \ + --push_to_hub + +# 2.8B Online DPO experiment +accelerate launch --config_file examples/accelerate_configs/deepspeed_zero2.yaml \ + examples/scripts/dpo_online.py \ + --model_name_or_path trl-lib/pythia-2.8b-deduped-tldr-sft \ + --reward_model_path trl-lib/pythia-2.8b-deduped-tldr-rm \ + --dataset_name trl-lib/tldr \ + --learning_rate 5.0e-7 \ + --output_dir pythia-2.8b-deduped-tldr-online-dpo \ + --beta 0.1 \ + --per_device_train_batch_size 8 \ + --gradient_accumulation_steps 2 \ + --num_train_epochs 3 \ + --max_new_tokens 53 \ + --warmup_steps 0.1 \ + --missing_eos_penalty 1.0 \ + --save_steps 0.1 \ + --push_to_hub + +# 6.9B Online DPO experiment +accelerate launch --config_file examples/accelerate_configs/deepspeed_zero2.yaml \ + examples/scripts/dpo_online.py \ + --model_name_or_path trl-lib/pythia-6.9b-deduped-tldr-sft \ + --reward_model_path trl-lib/pythia-6.9b-deduped-tldr-rm \ + --dataset_name trl-lib/tldr \ + --learning_rate 5.0e-7 \ + --output_dir pythia-6.9b-deduped-tldr-online-dpo \ + --beta 0.1 \ + --per_device_train_batch_size 4 \ + --gradient_accumulation_steps 4 \ + --num_train_epochs 3 \ + --max_new_tokens 53 \ + --warmup_steps 0.1 \ + --missing_eos_penalty 1.0 \ + --save_steps 0.1 \ + --push_to_hub +``` + +Checkpoints and experiment tracking are available at: + +* [🤗 Model checkpoints](https://huggingface.co/collections/trl-lib/online-dpo-66acd3fa38a331a9cd457b07) +* [🐝 Tracked experiment](https://wandb.ai/huggingface/trl/reports/Online-DPO-experiments-for-TL-DR-summarisation--Vmlldzo5MTczMDU0) + +The online DPO checkpoint gets increasingly more win rate as we scale up the model sizes. This is a good sign that the online DPO implementation is working as intended. + +## OnlineDPOTrainer + +[[autodoc]] experimental.online_dpo.OnlineDPOTrainer + - train + - save_model + - push_to_hub + +## OnlineDPOConfig + +[[autodoc]] experimental.online_dpo.OnlineDPOConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/openenv.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/openenv.md new file mode 100644 index 0000000000000000000000000000000000000000..0f26904e7b809487e4c959c390761d9ca7863d49 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/openenv.md @@ -0,0 +1,663 @@ +# OpenEnv Integration for Training LLMs with Environments + +[OpenEnv](https://github.com/huggingface/OpenEnv) is an open-source framework for defining, deploying, and interacting with environments in reinforcement learning (RL) and agentic workflows. It provides standardized APIs for environment interaction and supports running environments as backend servers (via WebSocket or containerised execution). You can find a collection of ready-to-use OpenEnv environments on the [Hugging Face Hub](https://huggingface.co/collections/openenv/openenv-environment-hub). + +This guide covers **how to integrate OpenEnv with TRL**. For more on OpenEnv itself, see the [OpenEnv docs](https://huggingface.co/docs/openenv). + +> [!NOTE] +> You can explore ready-to-use example [scripts](example_overview#openenv-scripts) and [notebooks](example_overview#openenv-notebooks) in the Examples Overview. + +## When to use environments + +[`GRPOTrainer`] can be used to train agents. For agentic tasks, it supports two modes: **tools**, where the model can call external functions but each call is stateless and independent, and **environments**, which maintain state across turns, enabling genuine multi-turn interaction where the agent's actions shape future observations. Use environments when continuity matters — for example, navigating a game, browsing a web page, or any task where what the agent sees next depends on what it did before. + +## Choosing an environment integration + +OpenEnv is the native path documented here. Two further integrations — [OpenReward](openreward) and [Harbor](harbor) — conform to the same `environment_factory` contract and are interchangeable at the TRL level. See the [comparison of environment integrations](grpo_trainer#agent-training) in the GRPO guide to pick the one whose ecosystem fits your task. + +## Installation + +OpenEnv environments are hosted as Hugging Face Spaces, which are also pip-installable Git repositories: + +```bash +# Echo environment +pip install "openenv-echo-env @ git+https://huggingface.co/spaces/openenv/echo_env" + +# Wordle (TextArena) environment +pip install "openenv-textarena @ git+https://huggingface.co/spaces/openenv/wordle" + +# Catch (OpenSpiel) environment +pip install "openenv-openspiel-env @ git+https://huggingface.co/spaces/openenv/openspiel_env" +``` + +This installs the **environment client** (e.g., `EchoEnv`) that communicates with the remote environment server via WebSocket, along with the action/observation models and all required dependencies (including `openenv`). + +> [!TIP] +> You can find the install command for any environment on its HF Space page. Click the **⋮ (three dots)** menu and select **"Use this Space"** to see the install instructions. + +> [!TIP] +> You can also install the core package from PyPI with `pip install "openenv[core]>=0.3.1"`, but note that environment-specific dependencies may need to be installed separately. + +For development, you can clone the OpenEnv repo and install locally: + +```bash +git clone https://github.com/huggingface/OpenEnv.git +cd OpenEnv/envs/echo_env +pip install -e . +``` + +> [!NOTE] +> Each environment script in TRL includes inline dependency metadata (PEP 723) so you can also run them directly with [uv](https://docs.astral.sh/uv/): +> +> ```bash +> uv run examples/scripts/openenv/echo.py +> ``` +> +> This automatically installs the required environment package in an isolated virtual environment. + +## Quick start + +The fastest way to understand the integration is a complete example. The [echo.py](https://github.com/huggingface/trl/blob/main/examples/scripts/openenv/echo.py) script trains a model with the [Echo environment](https://huggingface.co/docs/openenv/environments/echo), which rewards completions based on their text length: + +```python +from datasets import Dataset +from echo_env import EchoEnv +from echo_env.models import EchoAction + +from trl import GRPOConfig, GRPOTrainer + +ENV_URL = "https://openenv-echo-env.hf.space" + +class EchoToolEnv: + def __init__(self): + self.env = EchoEnv(base_url=ENV_URL) + self.reward = 0.0 + + def reset(self, **kwargs) -> str | None: + self.reward = 0.0 + return None + + def echo(self, message: str) -> str: + """ + Echo the message back from the environment. + + Args: + message: The message to echo + + Returns: + The echoed message. + """ + observation = self.env.step(EchoAction(message=message)) + self.reward = observation.observation.reward + return observation.observation.echoed_message + +def reward_func(environments, **kwargs): + return [env.reward for env in environments] + +dataset = Dataset.from_dict( + {"prompt": [[{"role": "user", "content": "Try to echo 'Hello World!' in the environment."}]] * 64} +) + +trainer = GRPOTrainer( + model="Qwen/Qwen3-0.6B", + train_dataset=dataset, + reward_funcs=reward_func, + args=GRPOConfig( + chat_template_kwargs={"enable_thinking": False}, + log_completions=True, + ), + environment_factory=EchoToolEnv, +) +trainer.train() +``` + +That's it. Here's what happens under the hood: + +1. **`environment_factory=EchoToolEnv`**: The trainer creates one `EchoToolEnv` instance per generation (pass the class, not an instance). +2. **`reset()`** is called at the start of each episode to initialize state. Returns an observation string (or `None`). +3. **Tool discovery**: The trainer discovers all public methods on the environment instance (here, `echo()`) and exposes them as function-calling tools. Each method must have a proper docstring with typed arguments, which the trainer uses to build the tool schema. +4. **Multi-turn loop**: The trainer generates a completion, parses tool calls, executes `echo()`, appends the result, and generates again, until the model stops calling tools or `max_completion_length` is reached. +5. **Reward function**: Reads `env.reward` from each environment instance after the episode (before the environment is reset). + +```bash +# Run the example +python examples/scripts/openenv/echo.py + +# Customize model and environment URL +python examples/scripts/openenv/echo.py --model Qwen/Qwen3-0.6B --env-host https://openenv-echo-env.hf.space +``` + +Below is the reward curve from training: + + + +> [!NOTE] +> You can explore more ready-to-use example [scripts](example_overview#openenv-scripts) and [notebooks](example_overview#openenv-notebooks) in the Examples Overview. + +## How `environment_factory` works + +TRL's [`GRPOTrainer`] supports interactive environment training through the `environment_factory` argument. When provided, the trainer automatically handles the multi-turn tool-calling loop: it generates completions, parses tool calls, executes them against the environment, and feeds the results back to the model. All without custom rollout code. + +### Environment class requirements + +Your environment class must follow these rules: + +- `__init__(self)` *(optional)*: If provided, must take no arguments. Use it to initialize state or clients. If you need external configuration (e.g., a URL), capture it from the enclosing scope or module-level variables. +- `reset(self, **kwargs)`: Called at the start of each episode. Receives all dataset columns as keyword arguments. Return a string observation (or `None` for no initial observation). +- **Tool methods**: Any public method (not starting with `_`) other than `reset` is automatically exposed as a tool. Each tool method must have a docstring with `Args:` descriptions, since the trainer uses these to generate the tool schema for the model. + +### Tips for environment classes + +- **State for reward**: You can store any state you want on the environment instance (e.g., `self.reward`, `self.done`, etc.) and access it in your reward function via the `environments` parameter. Refer to the [Quick Start guide](#quick-start) for an example of this pattern. +- **Error handling**: If a tool method raises an exception (e.g., `ValueError("Game over.")`), the trainer catches it and feeds the error message back to the model as a tool response. This is the recommended way to signal that an action is invalid or that the episode has ended. + +```python +ENV_URL = "https://my-env.hf.space" + +class MyEnv: + def __init__(self): + self.client = MyClient(base_url=ENV_URL) # captured from enclosing scope + self.reward = 0.0 + + def reset(self, **kwargs) -> str | None: + self.reward = 0.0 + return "Initial observation for the model" + + def my_tool(self, arg1: str, arg2: int) -> str: + """ + Description of what this tool does. + + Args: + arg1: Description of arg1 + arg2: Description of arg2 + + Returns: + The result message. + """ + self.reward = 1.0 + return "Tool result" +``` + +> [!IMPORTANT] +> Tools must be **individual methods** with descriptive names and typed arguments (e.g., `guess(word: str)`, `move(direction: str)`). We do not recommend using generic methods like `step(action)`, since the model needs meaningful tool names and argument descriptions to learn tool calling. + +### Reward functions + +Reward functions receive the `environments` parameter (a list of environment instances), so you can access any state stored during the episode: + +```python +def reward_func(environments, **kwargs) -> list[float]: + return [env.reward for env in environments] +``` + +For more information on reward functions, see the [GRPO - Custom Reward Functions](grpo_trainer#using-a-custom-reward-function). + +### Tips for reward functions + +A few things we've found helpful when working with OpenEnv environments and GRPO: + +- **Simple rewards work well.** In our experiments with Wordle and Sudoku, binary rewards (1.0 for success, 0.0 otherwise) gave cleaner training signals than shaped rewards with partial credit. GRPO compares completions within a group, so the relative ranking matters more than the absolute values. +- **Check the final state, not the path.** When possible, let the environment judge the outcome (e.g., "did the model solve the puzzle?") rather than checking if it followed a specific sequence of actions. This gives the model freedom to discover its own strategies. +- **Test your reward before training.** Run a few episodes manually (see the [Wordle example notebook](https://github.com/huggingface/trl/blob/main/examples/notebooks/openenv_wordle_grpo.ipynb)) to confirm the environment returns sensible rewards. If a capable model can't score higher than a random baseline, the reward signal may need adjustment. + +### `max_completion_length` in multi-turn episodes + +The `max_completion_length` parameter limits the **total number of tokens across the entire multi-turn conversation** (all model generations + tool results combined), not just a single generation. For environments with many turns (e.g., Sudoku with dozens of moves), you may need to increase it: + +```python +args = GRPOConfig( + max_completion_length=4096, # default is usually 256-1024, increase for long episodes + # ... +) +``` + +If episodes are being cut short (model stops mid-game), this is likely the cause. + +## Advanced example: Wordle + +Let's train a model to play [Wordle](https://www.nytimes.com/games/wordle/index.html) using the [`TextArena`](https://huggingface.co/docs/openenv/environments/textarena) environment. This demonstrates multi-turn interaction, cumulative feedback handling, and episode termination via exceptions. + +> [!NOTE] +> You can explore the notebook version of this example in [the OpenEnv Wordle GRPO example](https://github.com/huggingface/trl/blob/main/examples/notebooks/openenv_wordle_grpo.ipynb). + +### The TextArena Environment + +[TextArena](https://huggingface.co/papers/2504.11442) is an open-source collection of competitive text-based games designed to evaluate reasoning skills in LLMs using textual games like Wordle, Snake, Tic-Tac-Toe, and more. + +![image of TextArena](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/text_arena_evals.png) + +### Why Wordle? + +Wordle is a good benchmark for environment-based RL because it requires reasoning about feedback, is purely text-based, and models from 1B parameters can improve at it. Each guess is only 8 tokens, making it lightweight to experiment with. + +> [!NOTE] How does Wordle work? +> Wordle is a word guessing game where the player has to guess a 5-letter word in 6 attempts. After each guess, the environment provides letter-by-letter feedback: +> +> ``` +> G U E S S +> X G Y X X +> ``` +> X = not in the word, G = correct position (green), Y = wrong position (yellow). Here, "U" is correct and in place, "E" is in the word but misplaced. + +### Environment class + +The `WordleEnv` class wraps the TextArena client and exposes `guess()` as the tool: + +```python +from textarena_env import TextArenaAction, TextArenaEnv + +class WordleEnv: + def __init__(self): + self.client = TextArenaEnv(base_url="https://openenv-wordle.hf.space") + + def reset(self, **kwargs) -> str | None: + result = self.client.reset() + self._last_full_feedback = result.observation.messages[0].content + self.reward = 0.0 + self.done = False + return self._last_full_feedback + + def guess(self, guess: str) -> str: + """ + Make a guess in the Wordle environment. + + Args: + guess: The guessed word, formatted as '[abcde]' + + Returns: + The feedback message from the environment. + """ + if self.done: + raise ValueError("Game over.") + result = self.client.step(TextArenaAction(message=guess)) + _full_feedback = result.observation.messages[0].content + feedback = _full_feedback[len(self._last_full_feedback):] + self._last_full_feedback = _full_feedback + if "You attempted an invalid move" in feedback: + self.reward = 0.0 + else: + self.reward = result.reward + self.done = result.done + return feedback +``` + +Key design choices: + +- **`reset()`** returns the initial game message as the first observation the model sees. +- **`guess()`** is the only tool. The model calls it each turn with a 5-letter word. +- **Cumulative feedback slicing**: TextArena returns the full game history each turn. We slice out only the new part to avoid repeating context. +- **Exception on done**: If the model tries to guess after the game ends, `guess()` raises a `ValueError`. The trainer catches this and feeds `"Game over."` back to the model as a tool response. The model learns to stop calling tools after this signal. + +### Reward function and training + +```python +from datasets import Dataset +from trl import GRPOConfig, GRPOTrainer + +def reward_func(environments, **kwargs) -> list[float]: + return [env.reward for env in environments] + +prompt = """You are an expert Wordle solver with deep knowledge of English vocabulary... +Use the tool `guess` to make a guess.""" + +dataset = Dataset.from_dict({"prompt": [[{"role": "user", "content": prompt}]] * 1000}) + +trainer = GRPOTrainer( + model="Qwen/Qwen3-1.7B", + reward_funcs=reward_func, + train_dataset=dataset, + args=GRPOConfig( + use_vllm=True, + vllm_mode="colocate", + chat_template_kwargs={"enable_thinking": False}, + max_completion_length=1024, + num_generations=4, + gradient_accumulation_steps=64, + ), + environment_factory=WordleEnv, +) +trainer.train() +``` + +The environment returns `1.0` if the model wins and `0.0` otherwise. + +### Running the example + + + + + +**Colocate mode (1 GPU, recommended)** + +```bash +python examples/scripts/openenv/wordle.py --vllm-mode colocate +``` + +This runs vLLM in the same process as training, requiring only a single GPU. + + + + + +**Server mode (2+ GPUs, scalable)** + +```bash +# Terminal 1: Start vLLM inference server +CUDA_VISIBLE_DEVICES=0 trl vllm-serve --model Qwen/Qwen3-1.7B --host 0.0.0.0 --port 8000 + +# Terminal 2: Run GRPO training with OpenEnv +CUDA_VISIBLE_DEVICES=1 python examples/scripts/openenv/wordle.py --vllm-mode server --vllm-server-url http://localhost:8000 +``` + + + + + +### Results + +The model improves its performance by reducing repetitions and increasing correct guesses. However, Qwen3-1.7B with `enable_thinking=False` is not able to consistently win the game. + + + +> [!NOTE] +> With `enable_thinking=False` (the default in these examples), small models like Qwen3-1.7B can learn to improve their guesses but should not be expected to consistently solve the game. For significantly better results, use larger models or enable thinking mode (`enable_thinking=True`), which allows the model to reason before making a guess at the cost of longer completions. + +We experimented with larger models like [`gpt-oss-20b`](https://huggingface.co/openai/gpt-oss-20b) and found that it was able to consistently win the game, though this requires significantly more compute. + +## Multi-environment training + +You can train a single model across multiple environments simultaneously. This is useful when you want a model to learn different skills in parallel. For example, playing Wordle (language reasoning) and Catch (spatial reasoning) in the same training run. + +The key idea is to create a **meta-environment class** that wraps multiple environments and routes each sample to the correct one using a dataset column. + +### How it works + +1. Add an `"env"` column (or similar) to your dataset that identifies which environment each sample belongs to. +2. In `reset(**kwargs)`, read `kwargs["env"]` to select the active environment for that episode. +3. Expose tools from all environments; the trainer discovers all public methods. +4. Use separate reward functions per environment, returning `None` for samples that don't belong to that environment. TRL handles `None` values with `nansum`/`nanmean`. + +### Example: Wordle + Catch + +The [multi_env.py](https://github.com/huggingface/trl/blob/main/examples/scripts/openenv/multi_env.py) script trains on Wordle and Catch simultaneously: + +```python +class MultiEnv: + def __init__(self): + self._wordle_client = None + self._catch_client = None + self.active = None + self.reward = 0.0 + self.done = False + + def reset(self, **kwargs) -> str | None: + self.active = kwargs.get("env", "wordle") + self.reward = 0.0 + self.done = False + + if self.active == "wordle": + if self._wordle_client is not None: + try: + self._wordle_client.close() + except Exception: + pass + self._wordle_client = TextArenaEnv(base_url=WORDLE_URL) + result = self._wordle_client.reset() + self._last_full_feedback = result.observation.messages[0].content + self.reward = 0.0 + return self._last_full_feedback + elif self.active == "catch": + if self._catch_client is not None: + try: + self._catch_client.close() + except Exception: + pass + self._catch_client = OpenSpielEnv(base_url=CATCH_URL) + result = self._catch_client.reset() + self.done = result.observation.done + return _format_catch_obs(result.observation.info_state) + + # Wordle tool + def guess(self, guess: str) -> str: + """Make a guess in the Wordle environment. ...""" + ... + + # Catch tools + def move(self, direction: str) -> str: + """Move the paddle left or right. ...""" + ... + + def stay(self) -> str: + """Do nothing and let the ball fall one step. ...""" + ... +``` + +Key patterns: + +- **Lazy client initialization**: Create clients in `reset()`, not `__init__()`, to avoid unnecessary WebSocket connections. +- **Close before reopen**: Close the previous client before creating a new one to avoid server capacity errors. +- **`kwargs` routing**: The `"env"` column from the dataset is passed to `reset()` as a keyword argument. +- **All tools are exposed simultaneously**: The model sees `guess`, `move`, and `stay` as available tools regardless of the active environment. If it calls the wrong tool (e.g., `move` during Wordle), the method raises a `ValueError` that the trainer catches gracefully. In practice, models learn to use the correct tools based on the system prompt. + +### Per-environment reward functions + +Each reward function returns `None` for samples from other environments: + +```python +def wordle_reward(environments, **kwargs) -> list[float | None]: + return [env.reward if env.active == "wordle" else None for env in environments] + +def catch_reward(environments, **kwargs) -> list[float | None]: + rewards = [] + for env in environments: + if env.active != "catch": + rewards.append(None) + elif env.done: + rewards.append(max(env.reward, 0.0)) + else: + rewards.append(0.0) + return rewards +``` + +TRL converts `None` to `nan` internally and uses `nansum`/`nanmean` for aggregation, so each sample is only scored by its relevant reward function. + +### Dataset with environment routing + +```python +n = 500 +dataset = Dataset.from_dict({ + "prompt": ( + [[{"role": "user", "content": wordle_prompt}]] * n + + [[{"role": "user", "content": catch_prompt}]] * n + ), + "env": ["wordle"] * n + ["catch"] * n, +}) +``` + +### Running the multi-environment example + +```bash +python examples/scripts/openenv/multi_env.py \ + --wordle-url https://openenv-wordle.hf.space \ + --catch-url https://openenv-openspiel-env.hf.space \ + --vllm-mode colocate \ + --gradient-accumulation-steps 4 \ + --num-generations 8 +``` + +> [!TIP] +> When training across multiple environments, monitor the per-reward-function metrics (`train/reward_func_0`, `train/reward_func_1`, etc.) rather than the combined `train/reward`. The combined metric alternates between environments and can appear noisy. + +## Running the environments + +When using `environment_factory`, the trainer connects to the environment server automatically. You just need the server to be running. There are three ways to run an OpenEnv environment server: + + + + + +**Connect to a remote Hugging Face Space** *(simplest)* + +Most example scripts default to a hosted Space (no setup needed): + +```python +env = EchoEnv(base_url="https://openenv-echo-env.hf.space") +``` + +> [!WARNING] +> For training, **duplicate the Space to your own account** to avoid concurrency issues. The trainer opens N simultaneous WebSocket connections (one per generation), and shared Spaces may not support this. See [Server concurrency](#server-concurrency) for details. + + + + + +**Docker container** *(recommended for production)* + +```bash +docker run -d -p 8001:8000 --platform linux/amd64 registry.hf.space/openenv-echo-env:latest +``` + +Then connect: + +```python +env = EchoEnv(base_url="http://0.0.0.0:8001") +``` + +We map port 8001 to 8000 to leave port 8000 available for a vLLM server. + +You can also start the container programmatically: + +```python +env = EchoEnv.from_docker_image("registry.hf.space/openenv-echo-env:latest") +``` + +> [!NOTE] +> You can find the Docker image for any Space on the Hub: open the Space page → **⋮ (three dots)** → **"Run locally."** +> +> ![open_env_launch_docker](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/open_env_launch_docker.png) + + + + + +**Local Python process** *(for development)* + +```bash +hf download openenv/echo_env --repo-type=space --local-dir=echo_env +python -m uvicorn echo_env.src.envs.echo_env.server.app:app --host 0.0.0.0 --port 8001 +``` + +Then connect: + +```python +env = EchoEnv(base_url="http://0.0.0.0:8001") +``` + +For more details, see the [OpenEnv catalog](https://huggingface.co/docs/openenv/environments). + + + + + +## Environments catalog + +The best way to explore the current catalog of maintained environments is by visiting the official OpenEnv [catalog](https://huggingface.co/collections/openenv/environment-hub). + +To create your own environment, check out the guide on [Building Your Own Environment with OpenEnv](https://huggingface.co/docs/openenv/getting_started/environment-builder). Environments are tightly integrated with the Hub, so you can push new environments for the community to reuse. + +## Server concurrency + +When using `environment_factory`, the trainer creates N environment instances (one per generation), each opening a WebSocket connection to the server. By default, OpenEnv servers allow only 1 concurrent session, which will cause failures during training. + +To support parallel training, configure the server for concurrency: + +1. In your environment file, declare concurrent session support: +```python +SUPPORTS_CONCURRENT_SESSIONS: bool = True +``` + +2. In your server app, set the concurrency limit: +```python +app = create_app( + create_my_environment, + MyAction, + MyObservation, + max_concurrent_envs=64, # match or exceed generation_batch_size +) +``` + +> [!TIP] +> `max_concurrent_envs` should be ≥ `generation_batch_size` (which defaults to `per_device_train_batch_size × gradient_accumulation_steps`). For example, with `gradient_accumulation_steps=64` and batch size 1, you need at least 64 concurrent sessions. + +## `environment_factory` vs `rollout_func` + +[`GRPOTrainer`] supports two approaches for environment-based training: + +- **`environment_factory`** (recommended): You define an environment class with tool methods, and the trainer handles generation, tool-call parsing, and the multi-turn loop automatically. This is the approach used throughout this guide. +- **`rollout_func`**: You write the entire generation and environment interaction loop yourself. This gives full control over how completions are produced, how tools are executed, and how rewards are computed. + +Use `rollout_func` when `environment_factory` doesn't fit your use case. For example, **external agent servers** where an external server owns the generation loop and manages its own agent-environment interaction protocol. + +### Migrating from `rollout_func` to `environment_factory` + +If you have existing `rollout_func` code and want to migrate, here's the mapping: + +| `rollout_func` pattern | `environment_factory` equivalent | +|------------------------|----------------------------------| +| Manual generation loop | Handled automatically by the trainer | +| `generate_rollout_completions()` | Not needed, trainer generates internally | +| `env.step(Action(...))` in rollout | Wrap in a tool method on the environment class | +| Reward via `kwargs["env_reward"]` | Reward via `environments` parameter | +| `env_mask` construction | Automatic, trainer builds `tool_mask` | +| Token concatenation | Automatic, trainer manages token sequences | + +**Before** (`rollout_func`): + +```python +def rollout_func(prompts, trainer): + outputs = generate_rollout_completions(trainer, prompts) + env_rewards = [] + for out in outputs: + text = tokenizer.decode(out["completion_ids"], skip_special_tokens=True) + result = client.step(EchoAction(message=text)) + env_rewards.append(result.reward) + return { + "prompt_ids": [out["prompt_ids"] for out in outputs], + "completion_ids": [out["completion_ids"] for out in outputs], + "logprobs": [out["logprobs"] for out in outputs], + "env_reward": env_rewards, + } + +trainer = GRPOTrainer(..., rollout_func=rollout_func) +``` + +**After** (`environment_factory`): + +```python +class EchoToolEnv: + def __init__(self): + self.env = EchoEnv(base_url=url) + self.reward = 0.0 + + def reset(self, **kwargs) -> str | None: + self.reward = 0.0 + return None + + def echo(self, message: str) -> str: + """Echo the message back. + + Args: + message: The message to echo + + Returns: + The echoed message. + """ + result = self.env.step(EchoAction(message=message)) + self.reward = result.observation.reward + return result.observation.echoed_message + +def reward_func(environments, **kwargs): + return [env.reward for env in environments] + +trainer = GRPOTrainer(..., environment_factory=EchoToolEnv, reward_funcs=reward_func) +``` diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/openreward.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/openreward.md new file mode 100644 index 0000000000000000000000000000000000000000..51305fbd85f5183726bb570dfd0cd05213985fe8 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/openreward.md @@ -0,0 +1,207 @@ +# OpenReward Integration for Training LLMs with Environments + +[OpenReward](https://openreward.ai) is an open ecosystem for RL environments built on the [Open Reward Standard (ORS)](https://openrewardstandard.io) — a public, language-agnostic HTTP/SSE protocol for how an environment exposes its tasks, tools, sessions, and rewards. Because ORS is just a protocol, the same environment can run on the [OpenReward platform](https://openreward.ai), self-hosted on any container service, or locally on `localhost` for development. A catalog of ready-to-use environments is available at [openreward.ai](https://openreward.ai). + +This guide covers **how to integrate OpenReward with TRL**. For more on the standard itself, see the [ORS docs](https://docs.openreward.ai/). + +> [!NOTE] +> The integration lives at `trl.experimental.openreward` and is gated behind the `trl[openreward]` extra (lazy-imported — non-users pay nothing). + +## When to use OpenReward environments + +[`GRPOTrainer`] supports environment-based training via the `environment_factory` slot — see [OpenEnv](openenv) for the general contract. Use OpenReward when you want to train against an ORS-speaking environment: the [OpenReward catalog](https://openreward.ai) (e.g. `Eigent/SETA`, `kanishk/EndlessTerminals`, `nebius/SWE-rebench-V2`), an env you self-host on your own infra, or a local server you're developing. + +## Installation + +```bash +pip install trl[openreward] +``` + +This installs the `openreward` Python SDK. The integration itself imports `openreward` lazily, so users who don't touch `trl.experimental.openreward` aren't affected. + +## Quick start + +The `OpenRewardSpec` class wires a single ORS environment into the three TRL trainer slots — `train_dataset`, `environment_factory`, `reward_funcs` — by exposing properties that map 1:1 to those kwarg names: + +```python +from trl import GRPOConfig, GRPOTrainer +from trl.experimental.openreward import OpenRewardSpec + +spec = OpenRewardSpec("Eigent/SETA", num_tasks=64) + +trainer = GRPOTrainer( + model="Qwen/Qwen3-4B", + args=GRPOConfig( + num_generations=2, + max_steps=5, + max_tool_calling_iterations=20, + log_completions=True, + ), + train_dataset=spec.train_dataset, + environment_factory=spec.environment_factory, + reward_funcs=spec.reward_funcs, +) +trainer.train() +``` + +Under the hood `OpenRewardSpec` does three things, lazily on first access: + +1. **`spec.train_dataset`**: derives a `datasets.Dataset` from the env's task list (one HTTP roundtrip via the SDK). Has at minimum `prompt`, `task_index`, plus per-task metadata columns folded in. +2. **`spec.environment_factory`**: returns a zero-arg callable that produces a fresh per-rollout adapter on each call. The adapter exposes one Python method per ORS tool, with a typed signature and docstring auto-generated from the env's JSON Schema. TRL's tool collector picks them up via `inspect.getmembers`. +3. **`spec.reward_funcs`**: an outcome-only reward function (last non-null reward in the trajectory) suitable for sparse-reward envs like SETA. + +## Using a hub environment + +Pass an [openreward.ai](https://openreward.ai) catalog name as the target. The SDK reads `OPENREWARD_API_KEY` from the environment for authentication. + +```python +spec = OpenRewardSpec("Eigent/SETA", num_tasks=64) +``` + +## Using a self-hosted environment + +Pass the URL directly. No API key is needed if your server doesn't enforce one. + +```python +spec = OpenRewardSpec("https://my-org-my-env.hf.space", env_name="my_env") +``` + +> [!IMPORTANT] +> The `openreward` SDK by default expects a two-subdomain platform layout (`api.` for stateless calls and `sessions.` for SSE-based session calls). For **single-host** self-hosted servers (one URL serving everything), set the override env vars below before constructing `OpenRewardSpec`: +> +> ```python +> import os +> +> URL = "https://my-org-my-env.hf.space" +> os.environ["OPENREWARD_API_URL"] = URL +> os.environ["OPENREWARD_SESSION_URL"] = URL +> +> spec = OpenRewardSpec(URL, env_name="my_env") +> ``` + +## Running a minimal environment locally + +The fastest way to try the integration end-to-end without external dependencies is a tiny ORS server defined with the `openreward` SDK's `Environment` + `Server` scaffolding. The example below is a complete `echo` environment — the model wins by calling `echo(text=...)` with the task's target string. + +```python +# server.py +from pydantic import BaseModel +from openreward.environments import Environment, JSONObject, Server, TextBlock, ToolOutput, tool + + +class EchoTaskSpec(BaseModel): + target: str + +class EchoParams(BaseModel): + text: str + + +class EchoEnvironment(Environment): + def __init__(self, task_spec: JSONObject = {}, secrets: dict[str, str] = {}): + super().__init__(task_spec) + self.config = EchoTaskSpec.model_validate(task_spec) + + @classmethod + def list_splits(cls) -> list[str]: + return ["train"] + + @classmethod + def list_tasks(cls, split: str) -> list[JSONObject]: + return [{"target": "hello"}, {"target": "world"}] + + def get_prompt(self) -> list[TextBlock]: + return [TextBlock(type="text", text=f"Echo '{self.config.target}' to win.")] + + @tool + async def echo(self, params: EchoParams) -> ToolOutput: + """Submit a string. Reward 1.0 + finished if it matches the target. + + Args: + text: The string to echo back. + """ + correct = params.text == self.config.target + return ToolOutput( + blocks=[TextBlock(type="text", text="match" if correct else "no match")], + reward=1.0 if correct else 0.0, + finished=correct, + ) + + +if __name__ == "__main__": + Server([EchoEnvironment]).run(host="0.0.0.0", port=8000) +``` + +Run it: + +```bash +pip install openreward fastapi uvicorn pydantic +python server.py # listens on :8000 +``` + +Then point `OpenRewardSpec` at it (with the URL overrides described above): + +```python +import os +URL = "http://127.0.0.1:8000" +os.environ["OPENREWARD_API_URL"] = URL +os.environ["OPENREWARD_SESSION_URL"] = URL + +from trl.experimental.openreward import OpenRewardSpec +spec = OpenRewardSpec(URL, env_name="echoenvironment") +print(spec.train_dataset) # 2 rows, task_index + target columns +``` + +This is also the fixture pattern used by TRL's own tests — see [`trl-internal-testing/openreward-echo-env`](https://huggingface.co/spaces/trl-internal-testing/openreward-echo-env) for the deployed Space. + +## Selecting tasks + +`OpenRewardSpec` accepts either a count or an explicit index list: + +```python +spec = OpenRewardSpec("Eigent/SETA", num_tasks=10) # first 10 tasks +spec = OpenRewardSpec("Eigent/SETA", indices=[0, 5, 13, 27]) # specific indices +spec = OpenRewardSpec("Eigent/SETA", indices=list(range(50, 100))) # range +``` + +`num_tasks` and `indices` are mutually exclusive and both fetch only the tasks they need (no full task list scan). + +## How tool binding works + +At construction the spec calls the env's `/tools` endpoint to fetch a list of tool specs (each with a name, description, and JSON Schema for arguments). For each tool it generates a Python method on the per-rollout adapter with a typed signature and a docstring derived from the schema. So `transformers.utils.get_json_schema` and TRL's `inspect.getmembers(env, ismethod)` both produce the right tool schema for the model with no per-env wrapper code. + +If a tool description contains characters that aren't safe to splice into Python source, the binder falls back to a sanitized form so binding never fails on real envs. + +## Reward functions + +`spec.reward_funcs` defaults to an outcome-only reward — for each rollout it returns the last non-null reward observed during the trajectory. This is the right default for sparse-reward envs (e.g. SETA, where only `submit_solution` returns a non-null reward). + +If you want a custom reward, write a regular TRL reward function and pass it directly: + +```python +def my_reward(environments, **kwargs) -> list[float]: + return [env.reward * 2.0 for env in environments] # double the env reward, etc. + +trainer = GRPOTrainer( + ..., + reward_funcs=my_reward, +) +``` + +The per-rollout adapter exposes the running state TRL needs — `env.reward`, `env.rewards`, `env.metadata`, `env.finished`, `env.last_output` — for arbitrary post-hoc reward shaping. + +## OpenRewardSpec + +[[autodoc]] trl.experimental.openreward.OpenRewardSpec + +## Limitations + +- The integration is in `trl.experimental` — APIs may change. Set `TRL_EXPERIMENTAL_SILENCE=1` to silence the warning in CI logs. +- Currently exposes a single `OpenRewardSpec` covering one environment; multi-environment training (à la the OpenEnv "meta-environment" pattern) is not supported yet. +- Long-running rollouts (>15 min per episode) need a keepalive ping — not yet wired. + +## Reference + +- [Open Reward Standard](https://openrewardstandard.io) +- [OpenReward platform](https://openreward.ai) +- [`openreward` Python SDK](https://pypi.org/project/openreward/) +- [Echo env Space — `trl-internal-testing/openreward-echo-env`](https://huggingface.co/spaces/trl-internal-testing/openreward-echo-env) diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/orpo_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/orpo_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..555f0858316a3a2ff87b111e1100f3a69993e7f4 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/orpo_trainer.md @@ -0,0 +1,131 @@ +# ORPO Trainer + +[![model badge](https://img.shields.io/badge/All_models-ORPO-blue)](https://huggingface.co/models?other=orpo,trl) [![model badge](https://img.shields.io/badge/smol_course-Chapter_2-yellow)](https://github.com/huggingface/smol-course/tree/main/2_preference_alignment) + +## Overview + +Odds Ratio Preference Optimization (ORPO) was introduced in [ORPO: Monolithic Preference Optimization without Reference Model](https://huggingface.co/papers/2403.07691) by [Jiwoo Hong](https://huggingface.co/JW17), [Noah Lee](https://huggingface.co/nlee-208), and [James Thorne](https://huggingface.co/j6mes). + +The abstract from the paper is the following: + +> While recent preference alignment algorithms for language models have demonstrated promising results, supervised fine-tuning (SFT) remains imperative for achieving successful convergence. In this paper, we study the crucial role of SFT within the context of preference alignment, emphasizing that a minor penalty for the disfavored generation style is sufficient for preference-aligned SFT. Building on this foundation, we introduce a straightforward and innovative reference model-free monolithic odds ratio preference optimization algorithm, ORPO, eliminating the necessity for an additional preference alignment phase. We demonstrate, both empirically and theoretically, that the odds ratio is a sensible choice for contrasting favored and disfavored styles during SFT across the diverse sizes from 125M to 7B. Specifically, fine-tuning Phi-2 (2.7B), Llama-2 (7B), and Mistral (7B) with ORPO on the UltraFeedback alone surpasses the performance of state-of-the-art language models with more than 7B and 13B parameters: achieving up to 12.20% on AlpacaEval_{2.0} (Figure 1), 66.19% on IFEval (instruction-level loose, Table 6), and 7.32 in MT-Bench (Figure 12). We release code and model checkpoints for Mistral-ORPO-alpha (7B) and Mistral-ORPO-beta (7B). + +It studies the crucial role of SFT within the context of preference alignment. Using preference data the method posits that a minor penalty for the disfavored generation together with a strong adaption signal to the chosen response via a simple log odds ratio term appended to the NLL loss is sufficient for preference-aligned SFT. + +Thus ORPO is a reference model-free preference optimization algorithm eliminating the necessity for an additional preference alignment phase thus saving compute and memory. + +The official code can be found in [xfactlab/orpo](https://github.com/xfactlab/orpo). + +This post-training method was contributed by [Kashif Rasul](https://huggingface.co/kashif), [Lewis Tunstall](https://huggingface.co/lewtun) and [Alvaro Bartolome](https://huggingface.co/alvarobartt). + +## Quick start + +This example demonstrates how to train a model using the ORPO method. We use the [Qwen 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) as the base model. We use the preference data from the [UltraFeedback dataset](https://huggingface.co/datasets/openbmb/UltraFeedback). You can view the data in the dataset here: + + + +Below is the script to train the model: + +```python +# train_orpo.py +from datasets import load_dataset +from trl.experimental.orpo import ORPOConfig, ORPOTrainer +from transformers import AutoModelForCausalLM, AutoTokenizer + +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +train_dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") + +training_args = ORPOConfig(output_dir="Qwen2-0.5B-ORPO") +trainer = ORPOTrainer(model=model, args=training_args, processing_class=tokenizer, train_dataset=train_dataset) +trainer.train() +``` + +Execute the script using the following command: + +```bash +accelerate launch train_orpo.py +``` + +Distributed across 8 GPUs, the training takes approximately 30 minutes. You can verify the training progress by checking the reward graph. An increasing trend in the reward margin indicates that the model is improving and generating better responses over time. + +![orpo qwen2 reward margin](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/orpo-qwen2-reward-margin.png) + +To see how the [trained model](https://huggingface.co/trl-lib/Qwen2-0.5B-ORPO) performs, you can use the [Transformers Chat CLI](https://huggingface.co/docs/transformers/quicktour#chat-with-text-generation-models). + +
$ transformers chat trl-lib/Qwen2-0.5B-ORPO
+<quentin_gallouedec>:
+What is the best programming language?
+
+<trl-lib/Qwen2-0.5B-ORPO>:
+It's challenging to determine the best programming language as no one language is perfect, as the complexity of a task and the type of project are significant factors. Some popular languages include Java, Python, JavaScript, and
+C++. If you have specific needs or requirements for a specific project, it's important to choose the language that best suits those needs.
+
+Here are some other factors to consider when choosing a programming language for a project:
+
+ • Language proficiency: A good programming language is more likely to be easy to understand and use, and will allow developers to collaborate on projects more efficiently.
+ • Ease of use: There are tools and libraries available to make programming more accessible, so developers should choose a language that can help them get started easier.
+ • Code readability: A clear and concise codebase should be easy to read and understand, especially when working with large projects.
+ • Tool and framework support: There are numerous libraries available for Python, Java, and JavaScript, along with tools like IDEs and static code analysis tools.
+ • Accessibility: Some languages and tools have features that make them more accessible to developers with disabilities, such as support for screen readers.
+ • Version control: As your projects grow and complexity increases, version control tools can be beneficial for tracking changes.
+
+
+ +## Expected dataset type + +ORPO requires a [preference dataset](dataset_formats#preference). The [`experimental.orpo.ORPOTrainer`] supports both [conversational](dataset_formats#conversational) and [standard](dataset_formats#standard) dataset format. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset. + +Although the [`experimental.orpo.ORPOTrainer`] supports both explicit and implicit prompts, we recommend using explicit prompts. If provided with an implicit prompt dataset, the trainer will automatically extract the prompt from the `"chosen"` and `"rejected"` columns. For more information, refer to the [preference style](dataset_formats#preference) section. + +## Example script + +We provide an example script to train a model using the ORPO method. The script is available in [`examples/scripts/orpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/orpo.py) + +To test the ORPO script with the [Qwen2 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) on the [UltraFeedback dataset](https://huggingface.co/datasets/trl-lib/ultrafeedback_binarized), run the following command: + +```bash +accelerate launch examples/scripts/orpo.py \ + --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ + --dataset_name trl-lib/ultrafeedback_binarized \ + --num_train_epochs 1 \ + --output_dir Qwen2-0.5B-ORPO +``` + +## Usage tips + +### For Mixture of Experts Models: Enabling the auxiliary loss + +MOEs are the most efficient if the load is about equally distributed between experts. +To ensure that we train MOEs similarly during preference-tuning, it is beneficial to add the auxiliary loss from the load balancer to the final loss. + +This option is enabled by setting `output_router_logits=True` in the model config (e.g. [`~transformers.MixtralConfig`]). +To scale how much the auxiliary loss contributes to the total loss, use the hyperparameter `router_aux_loss_coef=...` (default: `0.001`) in the model config. + +## Logged metrics + +While training and evaluating, we record the following reward metrics: + +- `rewards/chosen`: the mean log probabilities of the policy model for the chosen responses scaled by beta +- `rewards/rejected`: the mean log probabilities of the policy model for the rejected responses scaled by beta +- `rewards/accuracies`: mean of how often the chosen rewards are > than the corresponding rejected rewards +- `rewards/margins`: the mean difference between the chosen and corresponding rejected rewards +- `log_odds_chosen`: the mean log odds ratio of the chosen responses over the rejected responses +- `log_odds_ratio`: the mean of the `log(sigmoid(log_odds_chosen))` +- `nll_loss`: the mean negative log likelihood loss from the SFT part of the loss over chosen responses + +## ORPOTrainer + +[[autodoc]] experimental.orpo.ORPOTrainer + - train + - save_model + - push_to_hub + +## ORPOConfig + +[[autodoc]] experimental.orpo.ORPOConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/paper_index.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/paper_index.md new file mode 100644 index 0000000000000000000000000000000000000000..533bb98a8b4c1003fbbaac5c823725ad981f7a0f --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/paper_index.md @@ -0,0 +1,1925 @@ +# Paper Index + + + +## Group Relative Policy Optimization + +Papers relating to the [`GRPOTrainer`]. + +### DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models + +**📜 Paper**: https://huggingface.co/papers/2402.03300 + +Introduces Group Relative Policy Optimization (GRPO) and shows strong math-reasoning gains from math-centric pretraining plus group-relative PPO-style optimization. Used in TRL via [`GRPOTrainer`]. + +```python +from trl import GRPOConfig, GRPOTrainer + +# The paper doesn't specify its hyperparameters, so here we provide hyperparameters from "DeepSeek-R1 incentivizes reasoning in LLMs through reinforcement learning" instead. +training_args = GRPOConfig( + loss_type="grpo", + beta=0.001, # "the KL coefficient to 0.001" + epsilon=10.0, # "the GRPO clip ratio ϵ to 10" + num_generations=16, # "For each question, we sample 16 outputs..." + max_completion_length=32_768, # "...with a maximum length of 32,768" + steps_per_generation=16, # "To accelerate training, each rollout generates 8,192 outputs, which are randomly split into 16 minibatches" + # "resulting in a training batch size of 512". One way to achieve this setting with 1 device is per_device_train_batch_size=4, gradient_accumulation_steps=128 + per_device_train_batch_size=4, + gradient_accumulation_steps=128, +) +trainer = GRPOTrainer( + ..., + args=training_args, +) +``` + +### DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning + +**📜 Paper**: https://huggingface.co/papers/2501.12948 + +DeepSeek-R1 achieves reasoning performance comparable to OpenAI-o1 through a multi-stage pipeline that transitions from pure reinforcement learning (RL) to a refined, human-aligned model. Unlike its predecessor, DeepSeek-R1-Zero, which used pure RL on a base model, R1 follows a structured four-stage evolution: +1. Cold Start: The base model is fine-tuned on a small set of high-quality, long Chain-of-Thought (CoT) data to provide a stable starting point. +2. Reasoning-Oriented RL: Large-scale RL is applied to enhance performance in math, coding, and logic, using rule-based rewards and a language consistency reward to reduce language mixing. +3. Rejection Sampling & SFT: The RL checkpoint generates 600k reasoning samples via rejection sampling, which are combined with 200k non-reasoning (general) samples to create a new dataset for a second round of Supervised Fine-Tuning. +4. RL for all Scenarios: A final RL stage aligns the model with human preferences (helpfulness and harmlessness) across all domains while maintaining reasoning strength. + +Distillation: Empowering Small Models + +A key contribution of the paper is demonstrating that reasoning patterns can be distilled from a large model (DeepSeek-R1) into smaller dense models (e.g., Qwen and Llama series). Distillation was found to be more effective for small models than training them with pure RL from scratch. + + +You can use the GRPOTrainer to replicate the reasoning-heavy stages of this pipeline. +```python +from trl import GRPOConfig, GRPOTrainer + +# Example configuration for a reasoning-oriented GRPO stage +# Based on the Open-R1 recipe for Qwen-7B +training_args = GRPOConfig( + learning_rate=4.0e-5, + max_completion_length=32768, # Support for long Chain-of-Thought + num_generations=16, # Sample 16 outputs per prompt for group relative advantage + beta=0.001, # KL coefficient + use_vllm=True, # Use vLLM backend for accelerated rollout generation +) + +trainer = GRPOTrainer( + model=model, + args=training_args, + train_dataset=dataset, + reward_funcs=[accuracy_reward, format_reward], # R1-Zero used rule-based rewards +) + +trainer.train() +``` + + +### Group Sequence Policy Optimization + +**📜 Paper**: https://huggingface.co/papers/2507.18071 + +GSPO is a GRPO variant that computes importance sampling weights at the sequence level instead of per-token. To reproduce the paper's setting, use this configuration: + +```python +from trl import GRPOConfig + +training_args = GRPOConfig( + importance_sampling_level="sequence", + loss_type="grpo", + beta=0.0, # GSPO set KL regularization to zero: https://github.com/volcengine/verl/pull/2775#issuecomment-3131807306 + epsilon=3e-4, # GSPO paper (v2), section 5.1 + epsilon_high=4e-4, # GSPO paper (v2), section 5.1 + gradient_accumulation_steps=1, + steps_per_generation=4, # partition rollout batch into 4 mini-batches. GSPO paper (v2), section 5.1. Must be 4 times gradient_accumulation_steps +) +``` + +Note that this method only has an effect when training goes slightly off-policy—for example, when `steps_per_generation > gradient_accumulation_steps` or `num_iterations > 1`. Otherwise, it is effectively equivalent to no modification. + +TRL also provide an experimental implementation of GSPO-token, see [Experimental - GSPO-Token](gspo_token). + +#### Policy ratio: GRPO vs. GSPO + +In GSPO, the policy ratio is defined at the sequence-level. In other words, it is the ratio between the probability of the current policy generating a sequence over the old policy generating that same sequence. + +The sequence likelihood is defined as: + +$$ +\pi_\theta (o_i | q) = \prod_{t=1}^{|o_i|} \pi_\theta (o_{i,t} | q, o_{i, < t} ), +$$ + +where \\( \pi_\theta \\) is the policy \\( \pi \\) with parameters \\(\theta\\), \\( o_i \\) is the \\( i \\)-th output sequence \\( o \\) and \\(o_{i,t}\\) is the \\( t \\)-th token in this sequence, \\( q \\) is the input query. The sequence likelihood ratio \\( s_i (\theta) \\) is defined as: + +$$ +s_i (\theta) = \left(\frac{\pi_\theta (o_i | q)}{\pi_{\theta_{old}} (o_i | q)} \right)^{\frac{1}{|o_i|}} +$$ + +The exponent \\( \frac{1}{|o_i|} \\) represents a sequence-length normalization, minimizing the influence of sequence length in sequence likelihood. In other terms, it computes the geometric mean of token probabilities, ensuring a fair comparison across sequences of varying lengths. + +While GSPO defines the policy ratio at the sequence level, GRPO operates at the token level. Specifically, GRPO computes an importance ratio for each token in the sequence: + +$$ +w_{i,t}(\theta) = \frac{\pi_\theta (o_{i,t} | q, o_{i,< t})}{\pi_{\theta_{\text{old}}} (o_{i,t} | q, o_{i,< t})} +$$ + +This token-level ratio is then combined with a shared advantage \\( \hat{A}_i \\), and the GRPO objective clips and optimizes each token independently across the sequence. + +### Geometric-Mean Policy Optimization + +**📜 Paper**: https://huggingface.co/papers/2507.20673 + +Geometric-Mean Policy Optimization (GMPO) is a GRPO variant that maximizes the *geometric* mean of the token-level importance ratios instead of the arithmetic mean. The geometric mean is far less sensitive to outlier ratios, so the policy update is more stable and tolerates a much wider clipping range. Clipping is applied per token, in log space, and is one-sided per the advantage sign (the standard PPO trust region) — crucially, *before* the geometric mean is taken. This is what distinguishes GMPO from GSPO (`importance_sampling_level="sequence"`), which clips the sequence-level ratio *after* averaging. + +The GMPO objective replaces GRPO's per-token arithmetic mean with the geometric mean of the (clipped) token ratios: + +$$ +\mathcal{J}_{\text{GMPO}}(\theta) = \mathbb{E}_{q, \{o_i\}} \left[ \frac{1}{G} \sum_{i=1}^{G} \left( \prod_{t=1}^{|o_i|} \min\left[ w_{i,t}(\theta)^{\operatorname{sgn}(\hat{A}_i)},\ \operatorname{clip}\left(w_{i,t}(\theta)^{\operatorname{sgn}(\hat{A}_i)}, \epsilon_1, \epsilon_2\right) \right]^{\operatorname{sgn}(\hat{A}_i)} \right)^{\frac{1}{|o_i|}} \hat{A}_i \right] +$$ + +where \\( w_{i,t}(\theta) \\) is the per-token importance ratio. In practice the product and clipping are computed in log space for numerical stability, and the clip range \\( (\epsilon_1, \epsilon_2) = (e^{-0.4}, e^{0.4}) \\) is markedly wider than GRPO/DAPO to encourage exploration. + +TRL provides an experimental implementation, see [Experimental - GMPO](gmpo): + +```python +from trl.experimental.gmpo import GMPOConfig, GMPOTrainer + +training_args = GMPOConfig( + epsilon=0.4, # log-space clip range -> ratios clipped to (exp(-0.4), exp(0.4)); paper, Sec. 4 + beta=0.0, +) +``` + +### DAPO: An Open-Source LLM Reinforcement Learning System at Scale + +**📜 Paper**: https://huggingface.co/papers/2503.14476 + +The DAPO algorithm includes 5 key components: + +- Overlong Filtering +- Clip-Higher +- Soft Overlong Punishment +- Token-level Loss +- Dynamic Sampling (⚠️ Not supported in TRL) + +To reproduce the paper's setting, use this configuration: + +```python +from trl import GRPOConfig, GRPOTrainer + +training_args = GRPOConfig( + # Overlong Filtering + mask_truncated_completions=True, + # Token-level Loss + loss_type="dapo", + # Clip-Higher + epsilon_high=0.28, # DAPO paper: section 4.1 + epsilon=0.2, # DAPO paper: section 4.1 + # Other parameters used + per_device_train_batch_size=512, # mini-batch size for training in the paper, DAPO paper: section 4.1 + num_generations=16, # number of sample responses in the paper, DAPO paper: section 4.1 + max_completion_length=20480, # maximum number of tokens for generation in the paper, DAPO paper: section 4.1 + beta=0.0, # section 2.3, DAPO paper + +) +# Soft Overlong Punishment +sop_reward = get_soft_overlong_punishment(max_completion_len=20480, soft_punish_cache=4096) # DAPO paper: section 4.1 +trainer = GRPOTrainer( + ..., + args=training_args, + reward_funcs=[..., sop_reward], +) +``` + +### Demystifying Long Chain-of-Thought Reasoning in LLMs + +**📜 Paper**: https://huggingface.co/papers/2502.03373 + +This paper studies long chain-of-thought RL and introduces two complementary rule-based rewards: + +- A **cosine length-scaled reward** ([`~rewards.get_cosine_scaled_reward`], Appendix C.1) that scales the correctness reward by completion length: a correct completion is rewarded more when it is shorter, while a wrong completion is penalized less when it is longer (preserving exploration). +- An **n-gram repetition penalty** ([`~rewards.get_repetition_penalty_reward`], Appendix C.2) that discourages the degenerate, repetitive completions that emerge as a reward-hacking strategy under length shaping. + +The two are designed to be used together: + +```python +from trl import GRPOTrainer +from trl.rewards import get_cosine_scaled_reward, get_repetition_penalty_reward + +# max_len should match the generation budget (in tokens) +cosine_scaled_reward = get_cosine_scaled_reward(max_len=4096) +# Penalize repeated 3-grams, down to -1.0 for fully repetitive completions +repetition_penalty = get_repetition_penalty_reward(ngram_size=3, max_penalty=-1.0) +trainer = GRPOTrainer( + ..., + reward_funcs=[cosine_scaled_reward, repetition_penalty], +) +``` + +### INTELLECT-2: A Reasoning Model Trained Through Globally Decentralized Reinforcement Learning + +**📜 Paper**: https://huggingface.co/papers/2505.07291 + +INTELLECT-2 is the first globally distributed reinforcement learning training run of a 32 billion parameter language model using fully asynchronous RL across a dynamic, heterogeneous swarm of permissionless compute contributors. The authors propose modifications to the standard GRPO training recipe, including two-sided GRPO clipping for increased training stability. To reproduce the paper's setting, use this configuration: + +```python +from trl import GRPOConfig + +training_args = GRPOConfig( + delta=4, # δ in section 4.1 of the paper + epsilon=0.2, # ε in section 4.1 of the paper + beta=0.001, # KL divergence coefficient in section 4.1 of the paper + num_generations=16, # responses per prompt in section 4.1 of the paper + learning_rate=3e-7, # section 4.1 of the paper +) +``` + +### Beyond the 80/20 Rule: High-Entropy Minority Tokens Drive Effective Reinforcement Learning for LLM Reasoning + +**📜 Paper**: https://huggingface.co/papers/2506.01939 + +A minority of tokens with high entropy act as reasoning "forks" in the CoT path, driving exploration and performance gains for RLVR, while low-entropy majority tokens contribute little or even impede learning. RLVR mainly adjusts high-entropy tokens, largely preserving the base model’s overall entropy patterns. Thus landing on the 80/20 rule, training on only 20% of the tokens with the highest entropy is comparable or supasses full-gradient updates for Qwen3 models. + +The paper's main results use vanilla DAPO (⚠️ Dynamic Sampling is not supported in TRL). To replicate the main results, use the following configuration: + +```python +from trl import GRPOConfig, GRPOTrainer +from trl.rewards import get_soft_overlong_punishment + +training_args = GRPOConfig( + # --- vanilla DAPO parameters (80/20 rule: section 5.2) --- # + # Overlong Filtering + mask_truncated_completions=True, + # Token-level Loss + loss_type="dapo", + # Clip-Higher + epsilon_high=0.28, # DAPO paper: section 4.1 + epsilon=0.2, # DAPO paper: section 4.1 + # Other parameters used + per_device_train_batch_size=512, # mini-batch size for training in the paper, DAPO paper: section 4.1 + num_generations=16, # number of sample responses in the paper, DAPO paper: section 4.1 + max_completion_length=20480, # maximum number of tokens for generation in the paper, DAPO paper: section 4.1 + beta=0.0, # section 2.3, DAPO paper + # --- Gradients on the highest entropy tokens --- # + top_entropy_quantile=0.2 +) +# Soft Overlong Punishment +sop_reward = get_soft_overlong_punishment(max_completion_len=20480, soft_punish_cache=4096) # DAPO paper: section 4.1 +trainer = GRPOTrainer( + ..., + args=training_args, + reward_funcs=[..., sop_reward], +) +``` + +### Dr. GRPO: Understanding R1-Zero-Like Training: A Critical Perspective + +**📜 Paper**: https://huggingface.co/papers/2503.20783 + +A study of R1-Zero training identifies pretraining effects on RL performance and proffers Dr. GRPO to enhance token efficiency, achieving superior accuracy on AIME 2024. To reproduce the paper's setting, use this configuration: + +```python +from trl import GRPOConfig + +training_args = GRPOConfig( + loss_type="dr_grpo", + per_device_train_batch_size=1, # train_batch_size_per_device in the Training section of the repository + num_generations=8, # num_samples in the Training section of the repository + max_completion_length=3000, # generate_max_length in the Training section of the repository + beta=0.0, # β in the Training section of the repository +) +``` + +### Part I: Tricks or Traps? A Deep Dive into RL for LLM Reasoning (Lite PPO) + +**📜 Paper**: https://huggingface.co/papers/2508.08221 + +The authors of this paper find that the combination of: + +1. scaling rewards by the standard deviation computed over the entire batch and +2. aggregating loss over the total number of tokens + +can unlock the learning capability of critic-free policies using vanilla PPO loss. Their results demonstrate that this simple combination consistently improves performance, surpassing strategies like GRPO and [DAPO](https://huggingface.co/papers/2503.14476). + +TRL supports using these learnings to train a GRPO model by: + +```python +from trl import GRPOConfig + +training_args = GRPOConfig( + ... + scale_rewards="batch", + loss_type="dapo", + # Other parameters used + beta=0.0, # = init_kl_coef in the paper + top_p=0.99, + top_k=100, + temperature=0.99, + num_generations=8, # = num_return_sequences in the paper + num_iterations=1, # = ppo_epochs in the paper + per_device_train_batch_size=4, + gradient_accumulation_steps=32, + steps_per_generation=8, # (rollout_batch_size*num_return_sequences) / (per_device_train_batch_size*gradient_accumulation_steps) +) +``` + +Note that when using gradient accumulation, the loss is aggregated over the total number of tokens in the batch, but not over the accumulated batch. For more details, see the [GRPO Trainer - Loss types](grpo_trainer#loss-types). + +### Truncated Importance Sampling + +**📰 Blog**: https://fengyao.notion.site/off-policy-rl + +**📜 Paper**: https://huggingface.co/papers/1606.02647 + +Online policy learning methods commonly use an optimized inference framework for rollout generation (e.g vLLM) that is separate from the training backend. This introduces a rollout-training mismatch, exemplified in the following PPO objective: + +$$ +\small{ +\mathbb{E}_{a\sim\textcolor{red}{\pi_{\text{inference}}}(\theta_{\mathrm{old}})} +\Bigl[ +\min\Bigl( +\frac{\textcolor{blue}{\pi_{\text{training}}}(a, \theta)}{\textcolor{blue}{\pi_{\text{training}}}(a, \theta_{\mathrm{old}})}\,\hat A, +\;\mathrm{clip}\bigl(\frac{\textcolor{blue}{\pi_{\text{training}}}(a, \theta)}{\textcolor{blue}{\pi_{\text{training}}}(a, \theta_{\mathrm{old}})},\,1-\epsilon,\,1+\epsilon\bigr)\,\hat A +\Bigr) +\Bigr] +} +$$ + +Despite \\( \textcolor{red}{\pi_{\text{inference}}} \\) and \\( \textcolor{blue}{\pi_{\text{training}}} \\) sharing the same model parameters \\( \theta \\), they can produce significantly different token probabilities. This unexpected behavior implicitly breaks the on-policy assumption, and silently turns training off-policy. + +Truncated Importance Sampling (TIS) addresses this issue by adapting the model update via importance-sampling correction. The gradient computation of the aforementioned PPO objective becomes + +$$ +\small{ +\mathbb{E}_{a\sim\textcolor{red}{\pi_{\text{inference}}}(\theta_{\mathrm{old}})} +\Bigl[ +\underbrace{\text{clip}\bigl(\frac{\textcolor{blue}{\pi_{\text{training}}}(a, \theta_{\mathrm{old}})}{\textcolor{red}{\pi_{\text{inference}}}(a, \theta_{\mathrm{old}})}, C_{\min}, C_{\max}\bigr)}_{\text{truncated importance ratio}} \cdot +\nabla_\theta +\min\Bigl( +\frac{\textcolor{blue}{\pi_{\text{training}}}(a, \theta)}{\textcolor{blue}{\pi_{\text{training}}}(a, \theta_{\mathrm{old}})}\,\hat A, +\;\mathrm{clip}\bigl(\frac{\textcolor{blue}{\pi_{\text{training}}}(a, \theta)}{\textcolor{blue}{\pi_{\text{training}}}(a, \theta_{\mathrm{old}})},\,1-\epsilon,\,1+\epsilon\bigr)\,\hat A +\Bigr) +\Bigr] +} +$$ + +where \\( C_{\min} \\) and \\( C_{\max} \\) are hyper-parameters. TIS is implemented in GRPO, and is enabled by selecting a `vllm_importance_sampling_mode` variant that includes the term `truncate`, such as `"sequence_truncate"` or `"token_truncate"`. + +```python +from trl import GRPOConfig + +training_args = GRPOConfig( + ... + use_vllm=True, + vllm_importance_sampling_correction=True, # default True + vllm_importance_sampling_mode="sequence_truncate", # or "token_truncate" + vllm_importance_sampling_clip_max=2.0, # hyper-parameter C_max +) +``` + +### Masked Importance Sampling + +**📰 Blog**: https://ringtech.notion.site/icepop + +**📜 Paper**: https://huggingface.co/papers/2510.18855 + +**📰 Blog**: https://yingru.notion.site/When-Speed-Kills-Stability-Demystifying-RL-Collapse-from-the-Training-Inference-Mismatch-271211a558b7808d8b12d403fd15edda + +Masked Importance Sampling (MIS) addresses the same issue as [Truncated Importance Sampling](#truncated-importance-sampling) but replaces clipping with masking. MIS takes a more decisive stance by discarding updates whose discrepancy falls outside the range \\( [C_{\min}, C_{\max}] \\). + + +$$ +\small{ +\mathbb{E}_{a\sim\textcolor{red}{\pi_{\text{inference}}}(\theta_{\mathrm{old}})} +\Bigl[ +\underbrace{\mathbf{1}\left[ +C_{\min} \le \frac{\pi_{\text{training}}(a, \theta_{\mathrm{old}})} +{\pi_{\text{inference}}(a, \theta_{\mathrm{old}})} +\le C_{\max} +\right] +\cdot +\frac{\pi_{\text{training}}(a, \theta_{\mathrm{old}})} +{\pi_{\text{inference}}(a, \theta_{\mathrm{old}})}}_{\text{masked importance ratio}} \cdot +\nabla_\theta +\min\Bigl( +\frac{\textcolor{blue}{\pi_{\text{training}}}(a, \theta)}{\textcolor{blue}{\pi_{\text{training}}}(a, \theta_{\mathrm{old}})}\,\hat A, +\;\mathrm{clip}\bigl(\frac{\textcolor{blue}{\pi_{\text{training}}}(a, \theta)}{\textcolor{blue}{\pi_{\text{training}}}(a, \theta_{\mathrm{old}})},\,1-\epsilon,\,1+\epsilon\bigr)\,\hat A +\Bigr) +\Bigr] +} +$$ + +MIS is implemented for GRPO, and is enabled by selecting a `vllm_importance_sampling_mode` variant that includes the term `"mask"`, such as `"sequence_mask"` or `"token_mask"`. + +```python +from trl import GRPOConfig + +training_args = GRPOConfig( + ... + use_vllm=True, + vllm_importance_sampling_correction=True, # default True + vllm_importance_sampling_mode="sequence_mask", # or "token_mask" + vllm_importance_sampling_clip_max=2.0, # hyper-parameter C_max + vllm_importance_sampling_clip_min=0.5, # hyper-parameter C_min +) +``` + +### Sequence-level Importance Sampling + +**📰 Blog**: https://yingru.notion.site/When-Speed-Kills-Stability-Demystifying-RL-Collapse-from-the-Training-Inference-Mismatch-271211a558b7808d8b12d403fd15edda + +The theoretically principled way to correct for the training-inference distribution shift is importance sampling, as introduced in the two papers above [Truncated Importance Sampling](#truncated-importance-sampling) and [Masked Importance Sampling](#masked-importance-sampling). However, the choice of formulation is crucial for keeping the gradient unbiased and ensuring stable training. + +This work shows that sequence-level importance sampling is the sound approach for addressing the training–inference mismatch. Although token-level importance sampling achieves lower variance than a sequence-level ratio, it introduces bias and is therefore argued to be unsuitable for autoregressive models. The token-level gradient estimator is + +$$ +\mathbb{E}_{x\sim\mathcal{D},\, y\sim \pi^{\text{inference}}_\theta(\cdot|x)} +\Bigg[ + R(x,y)\,\cdot\, + \sum_{t=0}^{|y|-1} + \frac{\pi^{\text{training}}_\theta(y_t\,|\,x, y_{ 0`: + +```python +from trl import GRPOConfig + +training_args = GRPOConfig( + ..., + beta=0.001, # the paper doesn't specify the value used, so we use the value from "DeepSeek-R1 incentivizes reasoning in LLMs through reinforcement learning" + use_bias_correction_kl=True, +) +``` + +- The **Off-Policy Masking**, which stabilizes training by ignoring sequences where the policy performs poorly (negative advantage) **and** has drifted significantly from the old policy (high KL divergence). + +The off-policy binary mask \\(\textcolor{red}{M_{i,t}}\\) is defined as: + +$$ +\textcolor{red}{M_{i,t}} = \begin{cases} +0 & \text{if } \hat{A}_{i,t} < 0 \quad \text{and} \quad \frac{1}{|o_i|} \sum_{t=1}^{|o_i|} \log \frac{\pi_{\theta_{\text{old}}}(o_{i,t} \mid q, o_{i, \textcolor{blue}{\delta} \\ +1 & \text{otherwise} +\end{cases} +$$ + +This mask is then applied to the GRPO loss as follows: + +$$ +\mathcal{L}_{\text{GRPO}}(\theta) = -\frac{1}{G} \sum_{i=1}^G \frac{1}{|o_i|} \sum_{t=1}^{|o_i|} \left[ \min \left( \frac{\pi_\theta(o_{i,t} \mid q, o_{i,< t})}{\pi_{\theta_{\text{old}}}(o_{i,t} \mid q, o_{i,< t})} \hat{A}_{i,t}, \, \text{clip}\left( \frac{\pi_\theta(o_{i,t} \mid q, o_{i,< t})}{\pi_{\theta_{\text{old}}}(o_{i,t} \mid q, o_{i,< t})}, 1 - \epsilon, 1 + \epsilon \right) \hat{A}_{i,t} \right) \textcolor{red}{M_{i,t}} - \beta \mathbb{D}_{\text{KL}}\left[\pi_\theta \| \pi_{\text{ref}}\right] \right] +$$ + +To enable this feature, use the `off_policy_mask_threshold` (corresponding to \\( \textcolor{blue}{\delta} \\)) in the [`GRPOConfig`]: + +```python +from trl import GRPOConfig + +training_args = GRPOConfig( + ..., + off_policy_mask_threshold=0.5, +) +``` + +While the paper doesn't specify a \\( \textcolor{blue}{\delta} \\) value used, a good starting point could be \\( \textcolor{blue}{\delta} = 0.5 \\). If training seems too conservative or too many sequences are masked, you can increase the value. +For reference, \\( \textcolor{blue}{\delta} = 1.0 \\) corresponds to an average log-ratio divergence of 1 nat per token, i.e. on sequences where this threshold is exceeded, the old policy was on average \\( e^1 \approx 2.7 \\) times more likely to generate these tokens than the current policy. + +### GDPO: Group reward-Decoupled Normalization Policy Optimization for Multi-reward RL Optimization + +**📜 Paper**: https://huggingface.co/papers/2601.05242 + +GDPO is a reinforcement learning optimization method designed for multi-reward training. While existing approaches commonly apply Group Relative Policy Optimization (GRPO) in multi-reward settings, the authors show that this leads to reward advantages collapse, reducing training signal resolution and causing unstable or failed convergence. GDPO resolves this issue by decoupling reward normalization across individual rewards, preserving their relative differences and enabling more faithful preference optimization. To enable GDPO for multi-reward RL training, simply set: + +For a group of \\( N \\) rewards and \\( G \\) samples per group, GDPO normalizes each reward independently: + +$$ +A_n^{(i,j)} = \frac{r_n^{(i,j)} - \text{mean}\{r_n^{(i,1)}, \ldots, r_n^{(i,G)}\}}{\text{std}\{r_n^{(i,1)}, \ldots, r_n^{(i,G)}\} + \epsilon} +$$ + +The normalized group advantage is then aggregated across rewards: + +$$ +A^{(i,j)} = \sum_{n=1}^{N} w_n A_n^{(i,j)} +$$ + +The final per-batch normalization produces: + +$$ +\hat{A}^{(i,j)} = \frac{A^{(i,j)} - \text{mean}_{i',j'}\{A^{(i',j')}\}}{\text{std}_{i',j'}\{A^{(i',j')}\} + \epsilon} +$$ + +Here, \\( \text{mean}_{i',j'}\{A^{(i',j')}\} \\) and \\( \text{std}_{i',j'}\{A^{(i',j')}\} \\) denote statistics over all groups in the batch. + +```python +from trl import GRPOConfig + + +training_args = GRPOConfig( + ..., + multi_objective_aggregation="normalize_then_sum", +) +``` + +Note that this method only has an effect when training involve more than one reward function. + +The authors provide a easy-to-use, slurm-free training example that enable the community to quickly validate GDPO’s effectiveness over GRPO, see [Experiment-"Aha" moment](https://github.com/NVlabs/GDPO/tree/main/trl-GDPO). + +### Length-Unbiased Sequence Policy Optimization: Revealing and Controlling Response Length Variation in RLVR + +**📜 Paper**: https://huggingface.co/papers/2602.05261 + +Length-Unbiased Sequence Policy Optimization (LUSPO) modifies GSPO by scaling each sequence's loss by its length. This corrects GSPO's gradient bias that penalizes longer responses. To reproduce the paper's setting, use this configuration: + +```python +from trl import GRPOConfig + +training_args = GRPOConfig( + loss_type="luspo", + importance_sampling_level="sequence", + epsilon=2e-3, # section 5.1 of the paper + epsilon_high=2.5e-3, # section 5.1 of the paper +) +``` + +### VESPO: Variational Sequence-Level Soft Policy Optimization for Stable Off-Policy LLM Training + +**📜 Paper**: https://huggingface.co/papers/2602.10693 + +VESPO addresses training instability in off-policy RL caused by policy staleness, asynchronous updates, and train-inference mismatches. Rather than relying on heuristic token-level clipping (GRPO) or sequence-length normalization (GSPO), VESPO derives a principled reshaping kernel from a variational framework. In practice, this yields a smooth, asymmetric Gamma weighting function that gracefully suppresses extreme sequence-level importance weights without introducing length bias. + +$$ +\mathcal{L}_{\text{VESPO}}(\theta) = - \mathbb{E}_{\tau \sim \mu} \left[ \underbrace{W(\tau)^{k} \cdot \exp\left(\lambda +(1 - W(\tau))\right)}_{\phi(W) \text{ detached }} \cdot \mathcal{A}(\tau) \cdot \log \pi_\theta(\tau) \right] +$$ + +with \\( W(\tau) = \frac{\pi_\theta(\tau)}{\mu(\tau)} \\) the sequence level importance ratio, and \\( \phi(W) \\) is detached from the computation graph to serve as a gradient scaling coefficient. + +```python +from trl import GRPOConfig + +training_args = GRPOConfig( + loss_type="vespo", + use_vllm=True, # or False if not using any token-level `vllm_importance_sampling_correction` methods + vllm_importance_sampling_mode="token_truncate", # default correction mode for VESPO, `token_mask` also supported + vespo_k_pos=2.0, # power exponent (c1 in paper Section 3.4) for positive advantages + vespo_lambda_pos=3.0, # decay factor (c2 in paper Section 3.4) for positive advantages + vespo_k_neg=3.0, # power exponent (c1 in paper Section 3.4) for negative advantages + vespo_lambda_neg=2.0, # decay factor (c2 in paper Section 3.4) for negative advantages +) +``` + + +### Rethinking the Trust Region in LLM Reinforcement Learning + +**📜 Paper**: https://huggingface.co/papers/2602.04879 + +DPPO replaces PPO/GRPO's heuristic ratio-clipping with a principled trust region based on direct policy divergence estimates. PPO-style clipping masks tokens based on the probability ratio π/μ, which over-penalizes low-probability tokens and under-penalizes high-probability ones. DPPO instead masks based on direct approximations of policy divergence (TV or KL), ensuring updates stay within a theoretically grounded trust region. Four divergence approximations are supported: `binary_tv`, `binary_kl`, `topk_tv`, and `topk_kl`. + +```python +from trl.experimental.dppo import DPPOConfig, DPPOTrainer + +training_args = DPPOConfig( + divergence_type="binary_tv", # divergence approximation + divergence_topk=20, # K for top-K divergence modes (Section 7 / Appendix G.2 of the paper) + epsilon=0.15, # δ_low threshold (Appendix F of the paper) + epsilon_high=0.15, # δ_high threshold (Appendix F of the paper) + clip_ratio_c=20.0, # IS ratio upper bound C (Section 5.4 of the paper) + beta=0.0, # KL regularization coefficient + use_vllm=True, +) + +trainer = DPPOTrainer( + model="your-model", + reward_funcs=[...], + args=training_args, + train_dataset=dataset, +) +trainer.train() +``` + +The official code [sail-sg/Stable-RL](https://github.com/sail-sg/Stable-RL) + +## Optimal Advantage Regression + +Papers relating to the [`experimental.a2po.A2POTrainer`]. + +### Accelerating RL for LLM Reasoning with Optimal Advantage Regression + +**📜 Paper**: https://huggingface.co/papers/2505.20686 + +A\*-PO (Optimal Advantage Regression) is a two-stage RL method for LLM reasoning that avoids both an online critic and multi-sample group rollouts. Stage 1 estimates the optimal value `V*(x) = β·log E_{y∼π_ref}[exp(r(x, y)/β)]` offline from reference-policy samples; Stage 2 performs on-policy updates with a single generation per prompt using a squared-error regression loss `(β·log(π(y|x)/π_ref(y|x)) − (r(x, y) − V*(x)))²`. This yields faster training and lower peak memory than PPO/GRPO/REBEL. The method assumes a binary verifiable reward and cannot exceed the reference policy's Pass@K. See [A2PO](a2po_trainer). The official code can be found in [ZhaolinGao/A-PO](https://github.com/ZhaolinGao/A-PO). + +```python +from trl.experimental.a2po import A2POConfig, A2POTrainer + +# Hyperparameters from the paper (Qwen2.5, GSM8K/MATH) +training_args = A2POConfig( + beta1=0.5, # KL temperature for offline V* estimation + beta2=1e-3, # KL temperature for the on-policy regression target + num_value_samples=8, # N samples per prompt from the reference policy +) +trainer = A2POTrainer( + model=..., + reward_funcs=..., # should return a binary reward in {0, 1} + args=training_args, + train_dataset=..., +) +trainer.train() +``` + +## Direct Policy Optimization + +Papers relating to the [`DPOTrainer`] + +### Direct Preference Optimization: Your Language Model is Secretly a Reward Model + +**📜 Paper**: https://huggingface.co/papers/2305.18290 + +Direct Preference Optimization (DPO) fine-tunes language models more efficiently and with better performance compared to reinforcement learning from human feedback (RLHF), by directly optimizing policy training based on human preferences. To reproduce the paper's setting, use this configuration: + +```python +from trl import DPOConfig + +training_args = DPOConfig( + loss_type="sigmoid", # losses in Appendix B of the paper + per_device_train_batch_size=64, # batch size in Appendix B of the paper + learning_rate=1e-6, # learning rate in Appendix B of the paper + beta=0.1, # β in Appendix B of the paper +) +``` + +### SLiC-HF: Sequence Likelihood Calibration with Human Feedback + +**📜 Paper**: https://huggingface.co/papers/2305.10425 + +Sequence Likelihood Calibration (SLiC) is shown to be an effective and simpler alternative to Reinforcement Learning from Human Feedback (RLHF) for learning from human preferences in language models. To reproduce the paper's setting, use this configuration: + +```python +from trl import DPOConfig + +training_args = DPOConfig( + loss_type="hinge", # Section 2 of the paper + per_device_train_batch_size=512, # batch size in Section 3.2 of the paper + learning_rate=1e-4, # learning rate in Section 3.2 of the paper +) +``` + +These parameters only appear in the [published version](https://openreview.net/pdf?id=0qSOodKmJaN) + +### Statistical Rejection Sampling Improves Preference Optimization + +**📜 Paper**: https://huggingface.co/papers/2309.06657 + +Proposes **RSO**, selecting stronger preference pairs via statistical rejection sampling to boost offline preference optimization; complements DPO/SLiC. They also introduce a new loss defined as: + +$$ +\mathcal{L}_{\text{hinge-norm}}(\pi_\theta) += \mathbb{E}_{(x, y_w, y_l) \sim \mathcal{D}} +\left[ +\max\left(0,\; 1 - \left[\gamma \log \frac{\pi_\theta(y_w \mid x)}{\pi_\text{ref}(y_w \mid x)} - \gamma \log \frac{\pi_\theta(y_l \mid x)}{\pi_\text{ref}(y_l \mid x)}\right]\right) +\right] +$$ + +To train with RSO-filtered data and the hinge-norm loss, you can use the following code: + +```python +from trl import DPOConfig, DPOTrainer + +dataset = ... + +def rso_accept(example): # replace with your actual filter/score logic + return example["rso_keep"] + +train_dataset = train_dataset.filter(rso_accept) + +training_args = DPOConfig( + loss_type="hinge", + beta=0.05, # correspond to γ in the paper +) + +trainer = DPOTrainer( + ..., + args=training_args, + train_dataset=train_dataset, +) +trainer.train() +``` + +### Beyond Reverse KL: Generalizing Direct Preference Optimization with Diverse Divergence Constraints + +**📜 Paper**: https://huggingface.co/papers/2309.16240 + +Proposes \(( f \\)-DPO, extending DPO by replacing the usual reverse-KL regularizer with a general \(( f \\)-divergence, letting you trade off mode-seeking vs mass-covering behavior (e.g. forward KL, JS, \(( \alpha \\)-divergences). The only change is replacing the DPO log-ratio margin with an **f′ score**: + +$$ +\mathcal{L}_{f\text{-DPO}}(\pi_\theta) += \mathbb{E}_{(x, y_w, y_l) \sim \mathcal{D}} +\left[ +-\log \sigma\left( +\beta \textcolor{red}{f'}\textcolor{red}{\Big(}\frac{\pi_\theta(y_w|x)}{\pi_{\text{ref}}(y_w|x)}\textcolor{red}{\Big)} +- +\beta \textcolor{red}{f'}\textcolor{red}{\Big(}\frac{\pi_\theta(y_l|x)}{\pi_{\text{ref}}(y_l|x)}\textcolor{red}{\Big)} +\right) +\right] +$$ + +Where \\( f' \\) is the derivative of the convex function defining the chosen \(( f \\)-divergence. + +To reproduce: + +```python +from trl import DPOConfig + +training_args = DPOConfig( + loss_type="sigmoid", + beta=0.1, + f_divergence_type="js_divergence", # or "reverse_kl" (default), "forward_kl", "js_divergence", "alpha_divergence" + f_alpha_divergence_coef=0.5, # only used if f_divergence_type="alpha_divergence" +) +``` + +### A General Theoretical Paradigm to Understand Learning from Human Preferences + +**📜 Paper**: https://huggingface.co/papers/2310.12036 + +Learning from human preferences can be written as a single KL-regularized objective over pairwise preference probabilities, + +$$ +\max_\pi ;\mathbb{E}\big[\Psi\left(p^*(y \succ y' \mid x)\right)\big] - \tau\mathrm{KL}(\pi||\pi_{\text{ref}}), +$$ + +which reveals RLHF and DPO as special cases corresponding to the logit choice of \\( \Psi \\). +The paper shows that this logit transform amplifies near-deterministic preferences and effectively weakens KL regularization, explaining overfitting. +Using the **Identity transform (IPO)** avoids this pathology by optimizing preferences directly, without assuming a Bradley–Terry reward model. +To reproduce the paper's setting, use this configuration: + +```python +from trl import DPOConfig + +training_args = DPOConfig( + loss_type="ipo", # Section 5.1 of the paper + per_device_train_batch_size=90, # mini-batch size in Section C.1 of the paper + learning_rate=1e-2, # learning rate in Section C.1 of the paper +) +``` + +These parameters only appear in the [published version](https://proceedings.mlr.press/v238/gheshlaghi-azar24a/gheshlaghi-azar24a.pdf) + +### Towards Efficient and Exact Optimization of Language Model Alignment + +**📜 Paper**: https://huggingface.co/papers/2402.00856 + +The paper shows that direct preference methods like DPO optimize the wrong KL direction, leading to blurred preference capture, and proposes EXO as an efficient way to exactly optimize the human‑preference alignment objective by leveraging reverse KL probability matching rather than forward KL approximations. To reproduce the paper's setting, use this configuration: + +```python +from trl import DPOConfig + +training_args = DPOConfig( + loss_type="exo_pair", # Section 3.2 of the paper + # From Section B of the paper + per_device_train_batch_size=64, + learning_rate=1e-6, + beta=0.1, +) +``` + +### Noise Contrastive Alignment of Language Models with Explicit Rewards + +**📜 Paper**: https://huggingface.co/papers/2402.05369 + +The paper reframes language-model alignment as a *noise-contrastive classification* problem, proposing InfoNCA to learn a policy from explicit rewards (or preferences) by matching a reward-induced target distribution over responses, and showing DPO is a special binary case. It then introduces NCA, which adds an absolute likelihood term to prevent the likelihood collapse seen in purely relative (contrastive) objectives. + +With pairwise preferences, treat the chosen/rejected \\( K=2 \\), define scores \\( r=\beta(\log\pi_\theta-\log\pi_{\text{ref}}) \\), and apply the NCA preference loss \\( -\log\sigma(r_w)-\tfrac12\log\sigma(-r_w)-\tfrac12\log\sigma(-r_l) \\). + +To reproduce the paper's setting, use this configuration: + +```python +from trl import DPOConfig + +training_args = DPOConfig( + loss_type="nca_pair", + # From Section C of the paper + per_device_train_batch_size=32, + learning_rate=5e-6, + beta=0.01, +) +``` + +### Provably Robust DPO: Aligning Language Models with Noisy Feedback + +**📜 Paper**: https://huggingface.co/papers/2403.00409 + +DPO breaks under noisy human preferences because label flips bias the objective. Robust DPO fixes this by analytically debiasing the DPO loss under a simple noise model, with provable guarantees. + +$$ +\mathcal{L}_{\text{robust}}(\pi_\theta) = \frac{(1-\varepsilon)\mathcal{L}_{\text{DPO}}(y_w, y_l) - \varepsilon\mathcal{L}_{\text{DPO}}(y_l, y_w)} +{1-2\varepsilon} +$$ + +Where \\( \mathcal{L}_{\text{DPO}} \\) is the DPO loss defined in [Direct Preference Optimization: Your Language Model is Secretly a Reward Model](#direct-preference-optimization-your-language-model-is-secretly-a-reward-model) and \\( \varepsilon \\) is the probability of a label flip. + +This single correction turns noisy preference data into an unbiased estimator of the clean DPO objective. + +```python +from trl import DPOConfig + +training_args = DPOConfig( + loss_type="robust", + per_device_train_batch_size=16, # batch size in Section B of the paper + learning_rate=1e-3, # learning rate in Section B of the paper + beta=0.1, # β in Section B of the paper, + max_length=512, # max length in Section B of the paper + label_smoothing=0.1 # label smoothing $\varepsilon$ in Section 6 of the paper +) +``` + +### Binary Classifier Optimization for Large Language Model Alignment + +**📜 Paper**: https://huggingface.co/papers/2404.04656 + +Theoretical analysis and a new algorithm, Binary Classifier Optimization, explain and enhance the alignment of large language models using binary feedback signals. To reproduce the paper's setting, use this configuration: + +BCO reframes language-model alignment as behavioral cloning from an optimal reward-weighted distribution, yielding simple supervised objectives that avoid RL while remaining theoretically grounded. +It supports both unpaired reward data and pairwise preference data, with a reward-shift–invariant formulation that reduces to a DPO-style loss in the preference setting. + +For the pairwise preference setting, the BCO loss is defined as: + +$$ +\mathcal{L}_{\text{bco\_pair}}(\pi_\theta) = +\mathbb{E}_{(x, y_w, y_l) \sim \mathcal{D}} +\left[ +-\log \sigma\Big( +\beta[(\log\pi_\theta-\log\pi_{\text{ref}})(y_w) +- +(\log\pi_\theta-\log\pi_{\text{ref}})(y_l)] +\Big) +\right] +$$ + +To reproduce the paper in this setting, use this configuration: + +```python +from trl import DPOConfig + +training_args = DPOConfig( + loss_type="bco_pair", + # From Section C of the paper + per_device_train_batch_size=128, + learning_rate=5e-7, + beta=0.01, +) +``` + +For the unpaired version, the user should utilize [`experimental.bco.BCOConfig`] and [`experimental.bco.BCOTrainer`]. + +### Learn Your Reference Model for Real Good Alignment + +**📜 Paper**: https://huggingface.co/papers/2404.09656 + +Trust Region DPO (TR-DPO) updates the reference policy during training, demonstrating effectiveness against DPO on the Anthropic HH and TLDR datasets, outperforming DPO by up to 19% measured by automatic evaluation with GPT-4, improving coherence, correctness, level of detail, helpfulness, and harmlessness. To reproduce the paper's setting, use this configuration: + +```python +from trl import DPOConfig + +training_args = DPOConfig( + sync_ref_model=True, # enable TR-DPO (Section 3 of the paper) + ref_model_mixup_alpha=0.6, # α soft update weight (Table 1 of the paper) + ref_model_sync_steps=512, # τ update frequency in steps (Table 1 of the paper) + beta=0.05, # β temperature (Table 1 of the paper) + learning_rate=1e-6, # learning rate (Table 2 of the paper) + num_train_epochs=1, # Table 2 of the paper + max_length=1024, # max tokens length (Table 2 of the paper) + max_grad_norm=2, # max gradient norm (Table 2 of the paper) + warmup_steps=100, # warm-up steps (Table 2 of the paper) +) +``` + +### Iterative Reasoning Preference Optimization + +**📜 Paper**: https://huggingface.co/papers/2404.19733 + +Iterative RPO improves reasoning by repeatedly generating chain-of-thought candidates, building preference pairs from correct vs. incorrect answers, and training with a DPO + NLL objective. The extra NLL term is key for learning to actually generate winning traces. + +TRL can express the DPO + NLL objective by mixing `"sigmoid"` (DPO) with `"sft"` (NLL): + +```python +from trl import DPOConfig, DPOTrainer + +training_args = DPOConfig( + loss_type=["sigmoid", "sft"], + loss_weights=[1.0, 1.0], # alpha in the paper, recommended value is 1.0 +) +trainer = DPOTrainer( + ..., + args=training_args, +) +``` + +Note that the paper uses an iterative loop: each iteration regenerates CoT candidates with the current model, then retrains on fresh preference pairs. TRL does not automate that loop for you. + +### Self-Play Preference Optimization for Language Model Alignment + +**📜 Paper**: https://huggingface.co/papers/2405.00675 + +A self-play method called SPPO for language model alignment achieves state-of-the-art performance by approximating Nash equilibrium policy in a constant-sum game setting, outperforming other approaches with limited data. To reproduce the paper's setting, use this configuration: + +```python +from trl import DPOConfig + +training_args = DPOConfig( + loss_type="sppo_hard", + # From Section 5 of the paper + beta=0.001, # β = η^−1 + per_device_train_batch_size=64, + learning_rate=5e-7, +) +``` + +### Provably Mitigating Overoptimization in RLHF: Your SFT Loss is Implicitly an Adversarial Regularizer + +**📜 Paper**: https://huggingface.co/papers/2405.16436 + +Regularized Preference Optimization (RPO) mitigates overoptimization in RLHF by fusing the DPO loss with the SFT loss, provably preventing the policy from choosing actions with spurious high proxy rewards. To reproduce the paper's setting, use this configuration: + +```python +from trl import DPOConfig + +training_args = DPOConfig( + loss_type=["sigmoid", "sft"], # RPO loss = DPO + SFT (Section 5 of the paper) + loss_weights=[1.0, 0.005], # η=0.005 SFT weight in Appendix E.1 of the paper + beta=0.01, # β in Appendix E.1 of the paper + learning_rate=5e-7, # learning rate in Appendix E.1 of the paper + num_train_epochs=1, # Appendix E.1 of the paper +) +``` + +### Distributional Preference Alignment of LLMs via Optimal Transport + +**📜 Paper**: https://huggingface.co/papers/2406.05882 + +Alignment via Optimal Transport (AOT) aligns large language models distributionally by penalizing violations of stochastic dominance between positive and negative sample distributions, achieving state-of-the-art performance on alignment benchmarks. To reproduce the paper's setting, use this configuration: + +```python +from trl import DPOConfig + +training_args = DPOConfig( + loss_type="aot", + beta=0.01, # from the caption of Figure 2 +) +``` + +or, for the unpaired version: + +```python +from trl import DPOConfig + +training_args = DPOConfig( + loss_type="aot_unpaired", + beta=0.01, # from the caption of Figure 2 +) +``` + +There is no additional hyperparameter in the paper. + +### Discovering Preference Optimization Algorithms with and for Large Language Models + +**📜 Paper**: https://huggingface.co/papers/2406.08414 + +An LLM-driven method automatically discovers performant preference optimization algorithms, leading to a new algorithm called DiscoPOP that blends logistic and exponential losses. To reproduce the paper's setting, use this configuration: + +```python +from trl import DPOConfig + +training_args = DPOConfig( + loss_type="discopop", + per_device_train_batch_size=64, # batch size in Section B.1 of the paper + learning_rate=5e-7, # learning rate in Section B.1 of the paper + beta=0.05, # β in Section B.1 of the paper, + discopop_tau=0.05 # τ in Section E of the paper +) +``` + +### WPO: Enhancing RLHF with Weighted Preference Optimization + +**📜 Paper**: https://huggingface.co/papers/2406.11827 + +WPO reweights preference pairs by their policy probabilities to reduce the off-policy gap in DPO-style training. The loss is: + +$$ +\mathcal{L}_{\text{WPO}} = -\mathbb{E}_{(x, y_w, y_l) \sim \mathcal{D}} \left[ \textcolor{red}{w(x, y_w) w(x, y_l)} \log p(y_w \succ y_l \mid x) \right] +$$ + +where the weight \\( w(x, y) \\) is defined as: + +$$ +w(x, y) = \exp\left(\frac{1}{|y|}\sum_{t=1}^{|y|} \log \frac{\pi_\theta(y_t \mid x, y_{ 0 (optimism coefficient) and β > 0 (KL regularization) in Algorithm 1 but does not specify numerical values. The following configuration uses TRL defaults: + +```python +from trl.experimental.xpo import XPOConfig + +training_args = XPOConfig( + alpha=1e-5, # α exploration bonus weight, α ≥ 0 where α=0 reduces to online DPO (TRL default) + beta=0.1, # β KL regularization coefficient (TRL default) +) +``` + +## Distillation + +Papers relating to training a student model with the help of a teacher model. + +### On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes + +**📜 Paper**: https://huggingface.co/papers/2306.13649 + +Introduces Generalized Knowledge Distillation (GKD), which addresses distribution mismatch in KD for auto-regressive models by training the student on its own generated outputs with teacher feedback, instead of a fixed set of sequences. GKD supports flexible loss functions (e.g. beyond KL when the student cannot match the teacher) and integrates with RL fine-tuning (RLHF). The paper reports results on summarization, translation, arithmetic reasoning, and instruction-tuning. Used in TRL via [`experimental.distillation.DistillationTrainer`] and [`experimental.gkd.GKDTrainer`]. To reproduce the paper's setting, use this configuration: + +```python +from trl.experimental.distillation import DistillationConfig + +# XSum summarization task (Table A.1 of the paper) +training_args = DistillationConfig( + lmbda=0.5, # λ student data fraction (Section 3 of the paper) + beta=0.5, # β Generalized JSD interpolation, 0=KL, 1=reverse KL (Section 3 of the paper) + temperature=1.0, # student training temperature (Appendix A of the paper) + max_steps=40000, # training steps (Table A.1 of the paper) + learning_rate=3e-4, # learning rate (Table A.1 of the paper) + per_device_train_batch_size=32, # batch size (Table A.1 of the paper) + warmup_steps=2000, # warm-up steps (Table A.1 of the paper) + max_completion_length=64, # max output tokens (Table A.1 of the paper) +) +``` + +### On-Policy Distillation + +**📰 Blog**: https://thinkingmachines.ai/blog/on-policy-distillation/ + +On-Policy Distillation involves a student model generating rollouts for each batch of training data. We subsequently obtain the probability distributions for each token of the rollouts from both the student and teacher models. The student model is then optimized to minimize the negative Kullback-Leibler (KL) divergence between its own token distributions and those of the teacher model. + +| Method | Sampling | Reward signal | +|-------------------------|------------|---------------| +| Supervised finetuning | off-policy | dense | +| Reinforcement learning | on-policy | sparse | +| On-policy distillation | on-policy | dense | + +On-Policy Distillation has been shown to outperform SFT, GRPO and can be used to restore generalization capabilities lost during SFT. + +Additionally on-policy distillation is more compute efficient and is less prone to overfitting when trained with limited data. + +To train a model with on-policy distillation using TRL, you can use the following configuration, with the [`experimental.distillation.DistillationTrainer`] and [`experimental.distillation.DistillationConfig`]: + +```python +from trl.experimental.distillation import DistillationConfig + +training_args = DistillationConfig( + lmbda=1.0, # student produces rollouts for all batches + beta=1.0, # to ensure reverse-kl as the loss function + teacher_model_name_or_path="teacher-model", # specify the teacher model +) +``` + +Alternatively, you can use the [`experimental.gkd.GKDTrainer`] and [`experimental.gkd.GKDConfig`]: + +```python +from trl.experimental.gkd import GKDConfig + +training_args = GKDConfig( + lmbda=1.0, # student produces rollouts for all batches + beta=1.0, # to ensure reverse-kl as the loss function + teacher_model_name_or_path="teacher-model", # specify the teacher model +) +``` + +You can also use the [`GOLDTrainer`] and [`GOLDConfig`] to perform on-policy distillation with a similar configuration: + +```python +from trl.experimental import GOLDConfig + +config = GOLDConfig( + lmbda=1.0, # student produces rollouts for all batches + beta=1.0, # to ensure reverse-kl as the loss function + teacher_model_name_or_path="teacher-model", # specify the teacher model + +) +``` + +### Knowledge Distillation of Large Language Models + +**📜 Paper**: https://huggingface.co/papers/2306.08543 + +MiniLLM is the first on-policy knowledge distillation method, which minimizes the sequence-level reverse KLD between the teacher and the student model and is optimized by reinforcement learning. + +It is a generalized version of [Think Machine Lab's On-Policy Distillation](https://thinkingmachines.ai/blog/on-policy-distillation/), with the option to add distribution-level single-step distillation signals (like GKD when `beta=1`) and long-context reverse KLD signals. + +Alternatively, you can use the [`experimental.MiniLLMTrainer`] and [`experimental.MiniLLMConfig`] to perform MiniLLM distillation as follows: + +```python +from datasets import load_dataset +from trl.experimental.minillm import MiniLLMTrainer + +dataset = load_dataset("trl-lib/tldr", split="train") + +trainer = MiniLLMTrainer( + model="Qwen/Qwen3-0.6B", + teacher_model="Qwen/Qwen3-1.7B", + train_dataset=dataset, +) +trainer.train() +``` + +For more details, see the [MiniLLM Trainer documentation](minillm_trainer). + +### Reinforcement Learning via Self-Distillation + +**📜 Paper**: https://huggingface.co/papers/2601.20802 + +Self-Distillation Policy Optimization (SDPO) enhances reinforcement learning with verifiable rewards by converting rich textual feedback (e.g., runtime errors, judge evaluations) into a dense learning signal without any external teacher or explicit reward model. SDPO treats the current model conditioned on feedback as a self-teacher and distills its feedback-informed next-token predictions back into the policy. Notably, SDPO also outperforms baselines in standard RLVR environments that only return scalar feedback by using successful rollouts as implicit feedback for failed attempts. + +```python +from trl.experimental.sdpo import SDPOConfig, SDPOTrainer + +training_args = SDPOConfig( + distillation_alpha=0.5, # Jensen-Shannon divergence (recommended) + distillation_mode="topk_logits", # Explicitly select top-K logit distillation + distillation_topk=100, # Required for top-K logit distillation + distillation_is_clip=2.0, # Importance sampling clipping + distillation_weight=1.0, # Convex weight: (1-w)*policy + w*distillation; 1.0 = pure distillation + use_successful_as_teacher=True, # Use successful rollouts as teacher + teacher_model_kind="ema", # Supported: "base", "live", "ema" + teacher_update_rate=0.05, # EMA update rate + include_environment_feedback=False, # Use dataset privileged_context when available +) + +trainer = SDPOTrainer( + model="Qwen/Qwen2.5-1.5B-Instruct", + reward_funcs=..., + args=training_args, + train_dataset=..., +) +trainer.train() +``` + +Expected dataset columns: + +- `prompt` +- `privileged_context` for optional environment feedback + +For more details, see the [SDPO Trainer documentation](sdpo_trainer). + +### Self-Distillation Enables Continual Learning + +**📜 Paper**: https://huggingface.co/papers/2601.19897 + +Self-Distilled Fine-Tuning (SDFT) performs on-policy self-distillation by generating completions during training, then distilling an explicit teacher-conditioned view of those same completions back into the student. The teacher is selected by `teacher_model_kind`: `"base"` (the initial student), `"live"` (the current student), or `"ema"` (an exponentially averaged teacher). The teacher prompt is composed internally from the student `prompt` plus the dataset `privileged_context`. + +```python +from datasets import Dataset + +from trl.experimental.sdft import SDFTConfig, SDFTTrainer + +dataset = Dataset.from_dict( + { + "prompt": [[{"role": "user", "content": "Solve 2+2."}]], + "privileged_context": ["Example answer: 4."], + } +) + +training_args = SDFTConfig( + distillation_alpha=0.5, + distillation_mode="topk_logits", + distillation_topk=5, + max_completion_length=64, +) + +trainer = SDFTTrainer( + model="Qwen/Qwen2.5-1.5B-Instruct", + args=training_args, + train_dataset=dataset, +) +trainer.train() +``` + +Expected dataset columns: + +- `prompt` +- `privileged_context` containing only the extra teacher-only information + +For more details, see the [SDFT Trainer documentation](sdft_trainer). + +### Embarrassingly Simple Self-Distillation Improves Code Generation + +**📜 Paper**: https://huggingface.co/papers/2604.01193 + +Simple Self-Distillation (SSD) improves code generation by sampling completions from the model at a training-time temperature and truncation configuration, then fine-tuning on those raw, unverified samples with standard cross-entropy loss. No reward model, verifier, teacher model, or reinforcement learning is needed. SSD reshapes token distributions in a context-dependent way: suppressing distractor tails at "lock" positions (where syntax leaves little ambiguity) while preserving diversity at "fork" positions (where multiple valid continuations exist). + +```python +from trl.experimental.ssd import SSDConfig, SSDTrainer + +training_args = SSDConfig( + temperature=0.6, # Training-time sampling temperature (T_train) + top_k=20, # Training-time top-k truncation + top_p=0.95, # Training-time top-p truncation + max_completion_length=65536, + learning_rate=5e-6, +) + +trainer = SSDTrainer( + model="Qwen/Qwen3-4B-Instruct", + args=training_args, + train_dataset=..., +) +trainer.train() +``` + +Expected dataset columns: + +- `prompt` + +For more details, see the [SSD Trainer documentation](ssd_trainer). + +## Distributed Training + +### ZeRO: Memory Optimizations Toward Training Trillion Parameter Models + +**📜 Paper**: https://huggingface.co/papers/1910.02054 + +ZeRO (Zero Redundancy Optimizer) eliminates memory redundancies in data- and model-parallel training by partitioning optimizer states, gradients, and parameters across devices while retaining low communication volume and high computational granularity. This allows for the efficient training of large models that would otherwise not fit in GPU memory. + +TRL supports ZeRO via the [DeepSpeed integration](deepspeed_integration). To use it, provide a DeepSpeed configuration file with your desired settings, + +```yaml +# config.yaml +distributed_type: DEEPSPEED +num_processes: 2 +deepspeed_config: + zero_stage: 3 +``` + +and launch the training script using `accelerate launch --config_file config_file`. + +```sh +accelerate launch --config_file config.yaml train.py +``` + +## Proximal Policy Optimization + +Papers relating to the [`experimental.ppo.PPOTrainer`] + +### Proximal Policy Optimization Algorithms + +**📜 Paper**: https://huggingface.co/papers/1707.06347 + +Introduces Proximal Policy Optimization (PPO): policy gradient methods that alternate between collecting rollouts and optimizing a clipped surrogate objective over multiple minibatch epochs. PPO retains benefits of trust-region methods (e.g. TRPO) with simpler implementation and strong empirical sample efficiency, and was validated on robotics and Atari benchmarks. Used in TRL via [`experimental.ppo.PPOTrainer`]. To use PPO with TRL, use this configuration: + +```python +from trl.experimental.ppo import PPOConfig + +training_args = PPOConfig( + cliprange=0.2, # ε clipping range (Section 3 and Table 3 of the paper, Mujoco setting) + num_ppo_epochs=4, # K epochs of minibatch updates (TRL default; paper uses K=10 Mujoco, K=3 Atari) + gamma=1.0, # γ discount factor (TRL default for LLM tasks; paper uses γ=0.99) + lam=0.95, # λ GAE parameter (Table 3 of the paper, Mujoco setting) + kl_coef=0.05, # KL penalty coefficient (Section 4 of the paper discusses adaptive KL) + vf_coef=0.1, # c₁ value function loss weight (Equation 9 of the paper) +) +``` diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/papo_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/papo_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..b9ec5aa66ed8e97de062b4e5b66a458f381c7e37 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/papo_trainer.md @@ -0,0 +1,20 @@ +# PAPO Trainer + +[![model badge](https://img.shields.io/badge/All_models-PAPO-blue)](https://huggingface.co/models?other=papo,trl) + +TRL supports the Perception-Aware Policy Optimization (PAPO) as described in the paper [Perception-Aware Policy Optimization for Multimodal Reasoning](https://huggingface.co/papers/2507.06448) by [Zhenhailong Wang](https://huggingface.co/mikewang), Xuehang Guo, Sofia Stoica, [Haiyang Xu](https://huggingface.co/xhyandwyy), Hongru Wang, Hyeonjeong Ha, Xiusi Chen, Yangyi Chen, Ming Yan, Fei Huang, Heng Ji + +The abstract from the paper is the following: + +> Reinforcement Learning with Verifiable Rewards (RLVR) has proven to be a highly effective strategy for endowing Large Language Models (LLMs) with robust multi-step reasoning abilities. However, its design and optimizations remain tailored to purely textual domains, resulting in suboptimal performance when applied to multimodal reasoning tasks. In particular, we observe that a major source of error in current multimodal reasoning lies in the perception of visual inputs. To address this bottleneck, we propose Perception-Aware Policy Optimization (PAPO), a simple yet effective extension of GRPO that encourages the model to learn to perceive while learning to reason, entirely from internal supervision signals. Notably, PAPO does not rely on additional data curation, external reward models, or proprietary models. Specifically, we introduce the Implicit Perception Loss in the form of a KL divergence term to the GRPO objective, which, despite its simplicity, yields significant overall improvements (4.4%) on diverse multimodal benchmarks. The improvements are more pronounced, approaching 8.0%, on tasks with high vision dependency. We also observe a substantial reduction (30.5%) in perception errors, indicating improved perceptual capabilities with PAPO. We conduct comprehensive analysis of PAPO and identify a unique loss hacking issue, which we rigorously analyze and mitigate through a Double Entropy Loss. Overall, our work introduces a deeper integration of perception-aware supervision into RLVR learning objectives and lays the groundwork for a new RL framework that encourages visually grounded reasoning. Project page: https://mikewangwzhl.github.io/PAPO. + +## PAPOTrainer + +[[autodoc]] experimental.papo.PAPOTrainer + - train + - save_model + - push_to_hub + +## PAPOConfig + +[[autodoc]] experimental.papo.PAPOConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/peft_integration.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/peft_integration.md new file mode 100644 index 0000000000000000000000000000000000000000..cfc5c180f9b89e9a5f2c5c75347e7e21e3501be8 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/peft_integration.md @@ -0,0 +1,822 @@ +# PEFT Integration + +TRL supports [PEFT](https://github.com/huggingface/peft) (Parameter-Efficient Fine-Tuning) methods for memory-efficient model training. PEFT enables fine-tuning large language models by training only a small number of additional parameters while keeping the base model frozen, significantly reducing computational costs and memory requirements. + +This guide covers how to use PEFT with different TRL trainers, including LoRA, QLoRA, and prompt tuning techniques. + +For a complete working example, see the [SFT with LoRA/QLoRA notebook](https://github.com/huggingface/trl/blob/main/examples/notebooks/sft_trl_lora_qlora.ipynb). + +## Installation + +To use PEFT with TRL, install the required dependencies: + +```bash +pip install trl[peft] +``` + +For QLoRA support (4-bit and 8-bit quantization), also install: + +```bash +pip install bitsandbytes +``` + +## Quick Start + +All TRL trainers support PEFT through the `peft_config` argument. The simplest way to enable PEFT is by using the command-line interface with the `--use_peft` flag: + +```bash +python trl/scripts/sft.py \ + --model_name_or_path Qwen/Qwen2-0.5B \ + --dataset_name trl-lib/Capybara \ + --use_peft \ + --lora_r 32 \ + --lora_alpha 16 \ + --output_dir Qwen2-0.5B-SFT-LoRA +``` + +Alternatively, you can pass a PEFT config directly in your Python code: + +```python +from peft import LoraConfig +from trl import SFTTrainer + +# Configure LoRA +peft_config = LoraConfig( + r=32, + lora_alpha=16, + lora_dropout=0.05, + bias="none", + task_type="CAUSAL_LM", +) + +# Configure training - note the higher learning rate for LoRA (10x base rate) +training_args = SFTConfig( + learning_rate=2.0e-4, # 10x the base rate (2.0e-5) for LoRA + ... +) + +# Create trainer with PEFT +trainer = SFTTrainer( + model=model, + train_dataset=dataset, + peft_config=peft_config, +) +``` + +## Three Ways to Configure PEFT + +TRL provides three different methods to configure PEFT, each suited for different use cases: + +### 1. Using CLI Flags (Simplest) + +The easiest way to enable PEFT is to use the `--use_peft` flag with the command-line interface. This method is ideal for quick experiments and standard configurations: + +```bash +python trl/scripts/sft.py \ + --model_name_or_path Qwen/Qwen2-0.5B \ + --dataset_name trl-lib/Capybara \ + --use_peft \ + --lora_r 32 \ + --lora_alpha 16 \ + --lora_dropout 0.05 \ + --output_dir Qwen2-0.5B-SFT-LoRA +``` + +**Pros**: Quick setup, no code required + +**Cons**: Limited to LoRA, fewer customization options + +### 2. Passing peft_config to Trainer (Recommended) + +For more control, pass a PEFT configuration directly to the trainer. This is the recommended approach for most use cases: + +```python +from peft import LoraConfig +from trl import SFTConfig, SFTTrainer + +peft_config = LoraConfig( + r=32, + lora_alpha=16, + lora_dropout=0.05, + bias="none", + task_type="CAUSAL_LM", + target_modules=["q_proj", "v_proj", "k_proj", "o_proj"], +) + +trainer = SFTTrainer( + model=model, + args=training_args, + train_dataset=dataset, + peft_config=peft_config, # Pass config here +) +``` + +**Pros**: Full control, supports all PEFT methods (LoRA, Prompt Tuning, etc.) + +**Cons**: Requires Python code + +### 3. Applying PEFT to Model Directly (Advanced) + +For maximum flexibility, you can apply PEFT to your model before passing it to the trainer: + +```python +from peft import LoraConfig, get_peft_model +from transformers import AutoModelForCausalLM +from trl import SFTConfig, SFTTrainer + +# Load base model +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B") + +# Apply PEFT configuration +peft_config = LoraConfig( + r=32, + lora_alpha=16, + lora_dropout=0.05, + bias="none", + task_type="CAUSAL_LM", +) +model = get_peft_model(model, peft_config) + +# Pass PEFT-wrapped model to trainer +trainer = SFTTrainer( + model=model, # Already has PEFT applied + args=training_args, + train_dataset=dataset, + # Note: no peft_config needed here +) +``` + +**Pros**: Maximum control, useful for custom model architectures or complex setups + +**Cons**: More verbose, requires understanding of PEFT internals + +## Learning Rate Considerations + +When using LoRA or other PEFT methods, you typically need to use a **higher learning rate** (approximately 10x) compared to full fine-tuning. This is because PEFT methods train only a small fraction of parameters, requiring a larger learning rate to achieve similar parameter updates. + +**Recommended learning rates:** + +| Trainer | Full Fine-Tuning | With LoRA (10x) | +|---------|------------------|-----------------| +| **SFT** | `2.0e-5` | `2.0e-4` | +| **DPO** | `5.0e-7` | `5.0e-6` | +| **GRPO** | `1.0e-6` | `1.0e-5` | +| **Prompt Tuning** | N/A | `1.0e-2` to `3.0e-2` | + +> **Why 10x?** LoRA adapters have significantly fewer trainable parameters than the full model. A higher learning rate compensates for this reduced parameter count, ensuring effective training. For detailed explanation, see [this blog post](https://thinkingmachines.ai/blog/lora/). + +For additional best practices on using LoRA effectively, refer to the [LoRA Without Regret](lora_without_regret) documentation. + +## PEFT with Different Trainers + +TRL's trainers support PEFT configurations for various training paradigms. Below are detailed examples for each major trainer. + + + + +### Supervised Fine-Tuning (SFT) + +The `SFTTrainer` is used for supervised fine-tuning on instruction datasets. + +#### With LoRA + +```bash +python trl/scripts/sft.py \ + --model_name_or_path Qwen/Qwen2-0.5B \ + --dataset_name trl-lib/Capybara \ + --learning_rate 2.0e-4 \ + --num_train_epochs 1 \ + --per_device_train_batch_size 2 \ + --gradient_accumulation_steps 8 \ + --use_peft \ + --lora_r 32 \ + --lora_alpha 16 \ + --output_dir Qwen2-0.5B-SFT-LoRA +``` + +#### Python Example + +```python +from peft import LoraConfig +from trl import SFTConfig, SFTTrainer + +# Configure LoRA +peft_config = LoraConfig( + r=32, + lora_alpha=16, + lora_dropout=0.05, + bias="none", + task_type="CAUSAL_LM", + target_modules=["q_proj", "v_proj"], # optional: specify target modules +) + +# Configure training with higher learning rate for LoRA +training_args = SFTConfig( + learning_rate=2.0e-4, # 10x the base rate for LoRA + ... +) + +# Create trainer with PEFT config +trainer = SFTTrainer( + model="Qwen/Qwen2-0.5B", # can pass model name or loaded model + args=training_args, + train_dataset=dataset, + peft_config=peft_config, # pass PEFT config here +) +trainer.train() +``` + + + + +### Direct Preference Optimization (DPO) + +The [`DPOTrainer`] implements preference learning from human feedback. + +#### With LoRA + +```bash +python trl/scripts/dpo.py \ + --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ + --dataset_name trl-lib/ultrafeedback_binarized \ + --learning_rate 5.0e-6 \ + --per_device_train_batch_size 2 \ + --gradient_accumulation_steps 8 \ + --use_peft \ + --lora_r 32 \ + --lora_alpha 16 \ + --output_dir Qwen2-0.5B-DPO-LoRA +``` + +#### Python Example + +```python +from peft import LoraConfig +from trl import DPOConfig, DPOTrainer + +# Configure LoRA +peft_config = LoraConfig( + r=32, + lora_alpha=16, + lora_dropout=0.05, + bias="none", + task_type="CAUSAL_LM", +) + +# Configure training with higher learning rate for LoRA +training_args = DPOConfig( + learning_rate=5.0e-6, # 10x the base rate for DPO with LoRA + ... +) + +# Create trainer with PEFT config +trainer = DPOTrainer( + model="Qwen/Qwen2-0.5B", # can pass model name or loaded model + args=training_args, + train_dataset=dataset, + peft_config=peft_config, # pass PEFT config here +) +trainer.train() +``` + +**Note:** When using PEFT with DPO, you don't need to provide a separate reference model (`ref_model`). The trainer automatically uses the frozen base model as the reference. + + + + +### Group Relative Policy Optimization (GRPO) + +The `GRPOTrainer` optimizes policies using group-based rewards. + +#### With LoRA + +```bash +python trl/scripts/grpo.py \ + --model_name_or_path Qwen/Qwen2-0.5B \ + --dataset_name trl-lib/math-reasoning \ + --learning_rate 1.0e-5 \ + --per_device_train_batch_size 2 \ + --use_peft \ + --lora_r 32 \ + --lora_alpha 16 \ + --output_dir Qwen2-0.5B-GRPO-LoRA +``` + +#### Python Example + +```python +from peft import LoraConfig +from trl import GRPOConfig, GRPOTrainer + +# Configure LoRA +peft_config = LoraConfig( + r=32, + lora_alpha=16, + lora_dropout=0.05, + bias="none", + task_type="CAUSAL_LM", +) + +# Configure training with higher learning rate for LoRA +training_args = GRPOConfig( + learning_rate=1.0e-5, # 10x the base rate for GRPO with LoRA + ... +) + +# Create trainer with PEFT config +trainer = GRPOTrainer( + model="Qwen/Qwen2-0.5B", # can pass model name or loaded model + args=training_args, + train_dataset=dataset, + peft_config=peft_config, # pass PEFT config here +) +trainer.train() +``` + + + + +### Proximal Policy Optimization (PPO) + +#### Multi-Adapter RL Training + +You can use a single base model with multiple PEFT adapters for the entire PPO algorithm - including retrieving reference logits, computing active logits, and calculating rewards. This approach is useful for memory-efficient RL training. + +> [!WARNING] +> This feature is experimental and convergence has not been extensively tested. We encourage the community to share feedback and report any issues. + +**Requirements** + +Install PEFT and optionally bitsandbytes for 8-bit models: + +```bash +pip install peft bitsandbytes +``` + +**Training Workflow** + +The multi-adapter approach requires three stages: + +1. **Supervised Fine-Tuning (SFT)**: Train a base model on your target domain (e.g., IMDB dataset) using `SFTTrainer` +2. **Reward Model Training**: Train a reward model adapter using PEFT and `RewardTrainer` (see [reward modeling example](https://github.com/huggingface/trl/tree/main/examples/scripts/reward_modeling.py)) +3. **PPO Training**: Fine-tune new adapters using PPO with the reward adapter + +> [!IMPORTANT] +> Use the same base model (architecture and weights) for stages 2 & 3. + +**Basic Usage** + +After training your reward adapter and pushing it to the Hub: + +```python +from peft import LoraConfig +from trl.experimental.ppo import PPOTrainer, AutoModelForCausalLMWithValueHead + +model_name = "huggyllama/llama-7b" +rm_adapter_id = "trl-lib/llama-7b-hh-rm-adapter" + +# Configure PPO adapter +lora_config = LoraConfig( + r=16, + lora_alpha=32, + lora_dropout=0.05, + bias="none", + task_type="CAUSAL_LM", +) + +# Load model with reward adapter +model = AutoModelForCausalLMWithValueHead.from_pretrained( + model_name, + peft_config=lora_config, + reward_adapter=rm_adapter_id, +) + +trainer = PPOTrainer(model=model, ...) +``` + +In your training loop, compute rewards using: + +```python +rewards = trainer.model.compute_reward_score(**inputs) +``` + +**Advanced Features** + +**Quantized Base Models** + +For memory-efficient training, load the base model in 8-bit or 4-bit while keeping adapters in float32: + +```python +from transformers import BitsAndBytesConfig + +model = AutoModelForCausalLMWithValueHead.from_pretrained( + model_name, + peft_config=lora_config, + reward_adapter=rm_adapter_id, + quantization_config=BitsAndBytesConfig(load_in_8bit=True), +) +``` + +## QLoRA: Quantized Low-Rank Adaptation + +QLoRA combines 4-bit quantization with LoRA to enable fine-tuning of very large models on consumer hardware. This technique can reduce memory requirements by up to 4x compared to standard LoRA. + +### How QLoRA Works + +1. **4-bit Quantization**: The base model is loaded in 4-bit precision using `bitsandbytes` +2. **Frozen Weights**: The quantized model weights remain frozen during training +3. **LoRA Adapters**: Only the LoRA adapter parameters are trained in higher precision +4. **Memory Efficiency**: Enables fine-tuning of models like Llama-70B on a single consumer GPU + +### Using QLoRA with TRL + +Simply combine `load_in_4bit=True` with PEFT configuration: + +#### Command Line + +```bash +python trl/scripts/sft.py \ + --model_name_or_path meta-llama/Llama-2-7b-hf \ + --dataset_name trl-lib/Capybara \ + --load_in_4bit \ + --use_peft \ + --lora_r 32 \ + --lora_alpha 16 \ + --per_device_train_batch_size 1 \ + --gradient_accumulation_steps 16 \ + --output_dir Llama-2-7b-QLoRA +``` + +#### Python Example + +```python +import torch + +from peft import LoraConfig +from transformers import AutoModelForCausalLM, BitsAndBytesConfig +from trl import SFTConfig, SFTTrainer + +# Configure 4-bit quantization +bnb_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_quant_type="nf4", + bnb_4bit_compute_dtype=torch.bfloat16, + bnb_4bit_use_double_quant=True, +) + +# Load model with quantization +model = AutoModelForCausalLM.from_pretrained( + "meta-llama/Llama-2-7b-hf", + quantization_config=bnb_config, + device_map="auto", +) + +# Configure LoRA +peft_config = LoraConfig( + r=32, + lora_alpha=16, + lora_dropout=0.05, + bias="none", + task_type="CAUSAL_LM", +) + +# Configure training with higher learning rate for LoRA +training_args = SFTConfig( + learning_rate=2.0e-4, # 10x the base rate for QLoRA + ... +) + +# Create trainer with PEFT config +trainer = SFTTrainer( + model=model, + args=training_args, + train_dataset=dataset, + peft_config=peft_config, +) + +trainer.train() +``` + +### QLoRA Configuration Options + +The `BitsAndBytesConfig` provides several options to optimize memory and performance: + +```python +import torch + +from transformers import BitsAndBytesConfig + +bnb_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_quant_type="nf4", # or "fp4" + bnb_4bit_compute_dtype=torch.bfloat16, # Compute dtype for 4-bit base models + bnb_4bit_use_double_quant=True, # Nested quantization for additional memory savings +) +``` + +**Configuration Parameters:** +- `bnb_4bit_quant_type`: Quantization data type (`"nf4"` or `"fp4"`). NF4 is recommended. +- `bnb_4bit_compute_dtype`: The dtype used for computation. Use `bfloat16` for better training stability. +- `bnb_4bit_use_double_quant`: Enable nested quantization to save additional ~0.4 bits per parameter. + +### 8-bit Quantization + +For slightly higher precision with reduced memory savings, you can use 8-bit quantization: + +```python +from transformers import BitsAndBytesConfig, AutoModelForCausalLM + +bnb_config = BitsAndBytesConfig(load_in_8bit=True) + +model = AutoModelForCausalLM.from_pretrained( + "meta-llama/Llama-2-7b-hf", + quantization_config=bnb_config, + device_map="auto", +) +``` + +Or via command line: + +```bash +python trl/scripts/sft.py \ + --model_name_or_path meta-llama/Llama-2-7b-hf \ + --load_in_8bit \ + --use_peft \ + --lora_r 32 \ + --lora_alpha 16 +``` + +## Prompt Tuning + +Prompt tuning is another PEFT technique that learns soft prompts (continuous embeddings) prepended to the input, while keeping the entire model frozen. This is particularly effective for large models. + +### How Prompt Tuning Works + +1. **Virtual Tokens**: Adds learnable continuous embeddings (virtual tokens) to the input +2. **Frozen Model**: The entire base model remains frozen +3. **Task-Specific Prompts**: Each task learns its own prompt embeddings +4. **Extreme Efficiency**: Only the prompt embeddings are trained (typically 8-20 tokens) + +### Using Prompt Tuning with TRL + +```python +from peft import PromptTuningConfig, PromptTuningInit, TaskType +from trl import SFTConfig, SFTTrainer + +# Configure Prompt Tuning +peft_config = PromptTuningConfig( + task_type=TaskType.CAUSAL_LM, + prompt_tuning_init=PromptTuningInit.TEXT, + num_virtual_tokens=8, + prompt_tuning_init_text="Classify if the tweet is a complaint or not:", + tokenizer_name_or_path="Qwen/Qwen2-0.5B", +) + +# Configure training with higher learning rate for Prompt Tuning +training_args = SFTConfig( + learning_rate=2.0e-2, # Prompt Tuning typically uses 1e-2 to 3e-2 + ... +) + +# Create trainer with PEFT config +trainer = SFTTrainer( + model=model, + args=training_args, + train_dataset=dataset, + peft_config=peft_config, # pass PEFT config here +) + +trainer.train() +``` + +### Prompt Tuning Configuration + +```python +from peft import PromptTuningConfig, PromptTuningInit, TaskType + +peft_config = PromptTuningConfig( + task_type=TaskType.CAUSAL_LM, # Task type + prompt_tuning_init=PromptTuningInit.TEXT, # Initialize from text + num_virtual_tokens=8, # Number of virtual tokens + prompt_tuning_init_text="Your initialization text here", + tokenizer_name_or_path="model_name", +) +``` + +**Configuration Parameters:** +- `task_type`: The task type (`TaskType.CAUSAL_LM` for language modeling) +- `prompt_tuning_init`: Initialization method (`TEXT`, `RANDOM`) +- `num_virtual_tokens`: Number of virtual tokens to prepend (typically 8-20) +- `prompt_tuning_init_text`: Text to initialize the virtual tokens (when using `TEXT` init) +- `tokenizer_name_or_path`: Tokenizer for initializing from text + +### Prompt Tuning vs LoRA + +| Feature | Prompt Tuning | LoRA | +|---------|---------------|------| +| **Parameters Trained** | ~0.001% | ~0.1-1% | +| **Memory Usage** | Minimal | Low | +| **Training Speed** | Fastest | Fast | +| **Model Modification** | None | Adapter layers | +| **Best For** | Large models, many tasks | General fine-tuning | +| **Learning Rate** | Higher (1e-2 to 3e-2) | Standard (1e-4 to 3e-4) | + +## Advanced PEFT Configurations + +### LoRA Configuration Parameters + +```python +from peft import LoraConfig + +peft_config = LoraConfig( + r=16, # LoRA rank + lora_alpha=32, # LoRA scaling factor + lora_dropout=0.05, # Dropout probability + bias="none", # Bias training strategy + task_type="CAUSAL_LM", # Task type + target_modules=["q_proj", "v_proj"], # Modules to apply LoRA + modules_to_save=None, # Additional modules to train +) +``` + +**Key Parameters:** +- `r`: LoRA rank (typical values: 8, 16, 32, 64). Higher rank = more parameters but potentially better performance. +- `lora_alpha`: Scaling factor (typically 2x the rank). Controls the magnitude of LoRA updates. +- `lora_dropout`: Dropout probability for LoRA layers (typical: 0.05-0.1). +- `target_modules`: Which modules to apply LoRA to. Common choices: + - `["q_proj", "v_proj"]`: Attention query and value (memory efficient) + - `["q_proj", "k_proj", "v_proj", "o_proj"]`: All attention projections + - `["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]`: All linear layers +- `modules_to_save`: Additional modules to fully train (e.g., `["embed_tokens", "lm_head"]`) + +### Target Module Selection + +You can specify which modules to apply LoRA to. Common patterns: + +```python +# Minimal (most memory efficient) +target_modules=["q_proj", "v_proj"] + +# Attention only +target_modules=["q_proj", "k_proj", "v_proj", "o_proj"] + +# All linear layers (best performance, more memory) +target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"] +``` + +### Using Command-Line Arguments + +TRL scripts accept PEFT parameters via command line: + +```bash +python trl/scripts/sft.py \ + --model_name_or_path Qwen/Qwen2-0.5B \ + --dataset_name trl-lib/Capybara \ + --use_peft \ + --lora_r 32 \ + --lora_alpha 16 \ + --lora_dropout 0.05 \ + --lora_target_modules q_proj v_proj \ + --output_dir output +``` + +Available flags: +- `--use_peft`: Enable PEFT +- `--lora_r`: LoRA rank (default: 16) +- `--lora_alpha`: LoRA alpha (default: 32) +- `--lora_dropout`: LoRA dropout (default: 0.05) +- `--lora_target_modules`: Target modules (space-separated) +- `--lora_modules_to_save`: Additional modules to train +- `--use_rslora`: Enable Rank-Stabilized LoRA +- `--use_dora`: Enable Weight-Decomposed LoRA (DoRA) +- `--load_in_4bit`: Enable 4-bit quantization (QLoRA) +- `--load_in_8bit`: Enable 8-bit quantization + +## Saving and Loading PEFT Models + +### Saving + +After training, save your PEFT adapters: + +```python +# Save the adapters +trainer.save_model("path/to/adapters") + +# Or manually +model.save_pretrained("path/to/adapters") +``` + +This saves only the adapter weights (~few MB) rather than the full model (~several GB). + +### Loading + +Load a PEFT model for inference: + +```python +from transformers import AutoModelForCausalLM +from peft import PeftModel + +# Load base model +base_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B") + +# Load PEFT adapters +model = PeftModel.from_pretrained(base_model, "path/to/adapters") + +# Optionally merge adapters into base model for faster inference +model = model.merge_and_unload() +``` + +### Pushing to Hub + +You can easily share your PEFT adapters on the Hugging Face Hub: + +```python +# Push adapters to Hub +model.push_to_hub("username/model-name-lora") + +# Load from Hub +from peft import PeftModel +model = PeftModel.from_pretrained(base_model, "username/model-name-lora") +``` + +## Multi-GPU Training + +PEFT works seamlessly with TRL's multi-GPU support through `accelerate`: + +```bash +# Configure accelerate +accelerate config + +# Launch training +accelerate launch trl/scripts/sft.py \ + --model_name_or_path Qwen/Qwen2-0.5B \ + --dataset_name trl-lib/Capybara \ + --use_peft \ + --lora_r 32 \ + --lora_alpha 16 +``` + +For QLoRA with multiple GPUs, the base model is automatically sharded: + +```bash +accelerate launch trl/scripts/sft.py \ + --model_name_or_path meta-llama/Llama-2-70b-hf \ + --load_in_4bit \ + --use_peft \ + --lora_r 32 +``` + +### Naive Pipeline Parallelism (NPP) for Large Models + +For very large models (>60B parameters), TRL supports Naive Pipeline Parallelism (NPP), which distributes the model and adapters across multiple GPUs. The activations and gradients are communicated across GPUs, supporting both `int8` and other data types. + +![NPP](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/trl-npp.png) + +**How to Use NPP** + +Load your model with a custom `device_map` to split it across multiple devices: + +```python +from transformers import AutoModelForCausalLM +from peft import LoraConfig + +# Create custom device map (see accelerate documentation) +device_map = { + "model.embed_tokens": 0, + "model.layers.0": 0, + # ... distribute layers across GPUs + "lm_head": 0, # Must be on GPU 0 +} + +model = AutoModelForCausalLM.from_pretrained( + "meta-llama/Llama-2-70b-hf", + device_map=device_map, + peft_config=lora_config, +) +``` + +> [!IMPORTANT] +> - Keep the `lm_head` module on the first GPU (device 0) to avoid errors +> - See this [tutorial on device maps](https://github.com/huggingface/blog/blob/main/accelerate-large-models.md) for proper configuration +> - Run training scripts directly (not with `accelerate launch`): `python script.py` +> - Data Parallelism is not yet supported with NPP + +## Resources + +### TRL Examples and Notebooks + +- **[SFT with LoRA/QLoRA Notebook](https://github.com/huggingface/trl/blob/main/examples/notebooks/sft_trl_lora_qlora.ipynb)** - Complete working example showing both LoRA and QLoRA implementations +- **[TRL Examples Directory](https://github.com/huggingface/trl/tree/main/examples)** - Collection of training scripts demonstrating PEFT with different trainers +- **[TRL Cookbook Recipes](https://github.com/huggingface/cookbook/tree/main/notebooks/transformers)** - Step-by-step guides for common PEFT training scenarios + +### Documentation + +- [PEFT Documentation](https://huggingface.co/docs/peft) - Official PEFT library documentation +- [TRL Documentation](https://huggingface.co/docs/trl) - Complete TRL documentation with trainer guides +- [LoRA Without Regret](lora_without_regret) - Best practices for using LoRA effectively + +### Research Papers + +- [LoRA Paper](https://huggingface.co/papers/2106.09685) - Original LoRA methodology and results +- [QLoRA Paper](https://huggingface.co/papers/2305.14314) - Efficient finetuning with 4-bit quantization +- [Prompt Tuning Paper](https://huggingface.co/papers/2104.08691) - The Power of Scale for Parameter-Efficient Prompt Tuning diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/ppo_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/ppo_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..ada0733b7fb024620938841454a7e9c34293d76f --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/ppo_trainer.md @@ -0,0 +1,257 @@ +# PPO Trainer + +[![model badge](https://img.shields.io/badge/All_models-PPO-blue)](https://huggingface.co/models?other=ppo,trl) + +TRL supports training LLMs with [Proximal Policy Optimization (PPO)](https://huggingface.co/papers/1707.06347). + +References: + +- [Fine-Tuning Language Models from Human Preferences](https://github.com/openai/lm-human-preferences) +- [Learning to Summarize from Human Feedback](https://github.com/openai/summarize-from-feedback) +- [The N Implementation Details of RLHF with PPO](https://huggingface.co/blog/the_n_implementation_details_of_rlhf_with_ppo) +- [The N+ Implementation Details of RLHF with PPO: A Case Study on TL;DR Summarization](https://huggingface.co/papers/2403.17031) + +## Get started + +To just run a PPO script to make sure the trainer can run, you can run the following command to train a PPO model with a dummy reward model. + +```bash +python examples/scripts/ppo/ppo.py \ + --dataset_name trl-internal-testing/descriptiveness-sentiment-trl-style \ + --dataset_train_split descriptiveness \ + --learning_rate 3e-6 \ + --num_ppo_epochs 1 \ + --num_mini_batches 1 \ + --output_dir models/minimal/ppo \ + --per_device_train_batch_size 64 \ + --gradient_accumulation_steps 1 \ + --total_episodes 10000 \ + --model_name_or_path EleutherAI/pythia-1b-deduped \ + --sft_model_path EleutherAI/pythia-1b-deduped \ + --reward_model_path EleutherAI/pythia-1b-deduped \ + --missing_eos_penalty 1.0 +``` + +## Explanation of the logged metrics + +The logged metrics are as follows. Here is an example [tracked run at Weights and Biases](https://wandb.ai/huggingface/trl/runs/dd2o3g35) + +- `eps`: Tracks the number of episodes per second. +- `objective/kl`: The mean Kullback-Leibler (KL) divergence between the current policy and reference policy. +- `objective/entropy`: The mean token-level entropy proxy on sampled rollouts, computed as `(-logprobs).sum(1).mean()` before PPO optimization. +- `objective/non_score_reward`: The mean reward from non-score-related sources, basically `beta * kl.sum(1)`, where `beta` is the KL penalty coefficient and `kl` is the per-token KL divergence. +- `objective/rlhf_reward`: The mean RLHF reward, which is `score - non_score_reward`. +- `objective/scores`: The mean scores returned by the reward model / environment. +- `policy/approxkl_avg`: The average approximate KL divergence between consecutive PPO policies. Note that this is not the same as `objective/kl`. +- `policy/clipfrac_avg`: The average fraction of policy updates that are clipped, indicating how often the policy updates are constrained to prevent large changes. +- `loss/policy_avg`: The average policy loss, indicating how well the policy is performing. +- `loss/value_avg`: The average value loss, indicating the difference between the predicted value and the actual reward. +- `val/clipfrac_avg`: The average fraction of value function updates that are clipped, similar to policy/clipfrac_avg but for the value function. +- `policy/entropy_avg`: The average categorical entropy of the current policy during PPO optimization, computed from `logits` each minibatch and averaged across PPO epochs/minibatches. +- `val/ratio`: The mean ratio of the current policy probability to the old policy probability, providing a measure of how much the policy has changed. +- `val/ratio_var`: The variance of the `val/ratio`, indicating the variability in policy changes. +- `val/num_eos_tokens`: The number of end-of-sequence (EOS) tokens generated, which can indicate the number of complete responses. +- `lr`: lr: The current learning rate used by the optimizer. +- `episode`: episode: The current episode count in the training process. + +`objective/entropy` and `policy/entropy_avg` are intentionally different signals: + +- `objective/entropy` is measured on the sampled behavior-policy rollouts used to build PPO advantages for the current update. +- `policy/entropy_avg` is measured during PPO optimization on the evolving policy (after gradient steps), so it can diverge from `objective/entropy`. + +## Cookbook + +- Debugging TIP: `objective/rlhf_reward`: this is the ultimate objective of the RLHF training. If training works as intended, this metric should keep going up. +- Debugging TIP: `val/ratio`: this number should float around 1.0, and it gets clipped by `--cliprange 0.2` with PPO's surrogate loss. So if this `ratio` is too high like 2.0 or 1000.0 or too small like 0.1, it means the updates between consecutive policies are too drastic. You should try understand why this is happening and try to fix it. +- Memory TIP: If you are running out of memory, you can try to reduce the `--per_device_train_batch_size` or increase the `--gradient_accumulation_steps` to reduce the memory footprint. +- Memory TIP: If you have multiple GPUs, you can also run training with DeepSpeed stage 3 to reduce the memory footprint `accelerate launch --config_file examples/accelerate_configs/deepspeed_zero3.yaml`. +- Usage TIP: We recommend to use the "EOS trick" via `--missing_eos_penalty`, which subtracts a static scalar penalty from the score of completions that do not end with an EOS token. This can help the model learn to generate more coherent completions. + +## What is my model doing exactly? + +To help you understand what your model is doing, we periodically log some sample completions from the model. Here is an example of a completion. In an example [tracked run at Weights and Biases](https://wandb.ai/huggingface/trl/runs/dd2o3g35), it looks like the following, allowing you to see the model's response at different stages of training. By default we generate `--num_sample_generations 10` during training, but you can customize the number of generations. + +![ppov2_completions](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/ppov2_completions.gif) + +In the logs the sampled generations look like + +```txt +┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━┓ +┃ query ┃ model response ┃ score ┃ +┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━┩ +│ SUBREDDIT: r/AskReddit │ I'm in love with a friend, and │ 3.921875 │ +│ │ I don't know how to get rid of │ │ +│ TITLE: How do you get someone │ those feelings. I'm │ │ +│ out of your head? │ desperate.<|endoftext|>[PAD][P… │ │ +│ │ │ │ +│ POST: Hi, │ │ │ +│ I'm 22, and I have been with my │ │ │ +│ girlfriend for 5 years now. We │ │ │ +│ recently moved together. We've │ │ │ +│ always loved each other │ │ │ +│ intensely. │ │ │ +│ │ │ │ +│ Problem, I recently started to │ │ │ +│ have feelings for an other │ │ │ +│ person (a friend). This person │ │ │ +│ has had a boyfriend for now 3 │ │ │ +│ years, and has absolutely no │ │ │ +│ ideas. Those feelings were so │ │ │ +│ strong, it was hard to hide │ │ │ +│ them. After 2 months of me │ │ │ +│ being distant and really sad, │ │ │ +│ my girlfriend forced me to say │ │ │ +│ what was bothering me. I'm not │ │ │ +│ a good liar, and now she knows. │ │ │ +│ │ │ │ +│ We decided to give us a week │ │ │ +│ alone, I went to my parents. │ │ │ +│ │ │ │ +│ Now, I'm completely lost. I │ │ │ +│ keep on thinking about this │ │ │ +│ person, and I hate that. I │ │ │ +│ would like for those feelings │ │ │ +│ to go away, to leave me alone. │ │ │ +│ But I can't. │ │ │ +│ │ │ │ +│ What do I do? It's been 3 │ │ │ +│ months now, and I'm just │ │ │ +│ desperate. │ │ │ +│ │ │ │ +│ TL;DR: │ │ │ +├─────────────────────────────────┼─────────────────────────────────┼──────────┤ +│ SUBREDDIT: r/pettyrevenge │ My mom woke me up with a loud │ 6.84375 │ +│ │ TV. I blasted Gangnam Style on │ │ +│ TITLE: So, my mom woke me up │ repeat, with the bass cranked │ │ +│ with a loud TV. │ up as high as it could │ │ +│ │ go.<|endoftext|>[PAD][PAD][PAD… │ │ +│ POST: She was in her living │ │ │ +│ room, watching TV. This was at │ │ │ +│ about 8:30 in the morning, and │ │ │ +│ she was exercising. She turned │ │ │ +│ the TV up extra loud to hear it │ │ │ +│ over her excercycle, and woke │ │ │ +│ me up. I went in there asking │ │ │ +│ for her to turn it down. She │ │ │ +│ said she didn't have to; I │ │ │ +│ explained that I always used │ │ │ +│ headphones so she didn't have │ │ │ +│ to deal with my noise and that │ │ │ +│ she should give me a little │ │ │ +│ more respect, given that I paid │ │ │ +│ rent at the time. │ │ │ +│ │ │ │ +│ She disagreed. I went back to │ │ │ +│ my room, rather pissed off at │ │ │ +│ the lack of equality. I had no │ │ │ +│ lock on my door; but I had a │ │ │ +│ dresser right next to it, so I │ │ │ +│ pulled one of the drawers out │ │ │ +│ enough so that it caused the │ │ │ +│ door to not be openable. Then, │ │ │ +│ I turned my speakers up really │ │ │ +│ loud and blasted Gangnam Style │ │ │ +│ on repeat, with the bass │ │ │ +│ cranked up as high as it could │ │ │ +│ go. │ │ │ +│ │ │ │ +│ If you hate Gangnam Style for │ │ │ +│ being overplayed, you will see │ │ │ +│ why I chose that particular │ │ │ +│ song. I personally don't mind │ │ │ +│ it. But here's the thing about │ │ │ +│ my bass; it vibrates the walls, │ │ │ +│ making one hell of a lot of │ │ │ +│ noise. Needless to say, my mom │ │ │ +│ was not pleased and shut off │ │ │ +│ the internet. But it was oh so │ │ │ +│ worth it. │ │ │ +│ │ │ │ +│ TL;DR: │ │ │ +└─────────────────────────────────┴─────────────────────────────────┴──────────┘ +``` + +## Implementation details + +This PPO implementation is based on the [The N+ Implementation Details of RLHF with PPO: A Case Study on TL;DR Summarization](https://huggingface.co/papers/2403.17031). + +## Benchmark experiments + +To validate the PPO implementation works, we ran experiment on the 1B model. Here are the command we used to run the experiment. We take the SFT / RM models directly from [The N+ Implementation Details of RLHF with PPO: A Case Study on TL;DR Summarization](https://huggingface.co/papers/2403.17031). + +```shell +accelerate launch --config_file examples/accelerate_configs/deepspeed_zero2.yaml \ + examples/scripts/ppo/ppo_tldr.py \ + --dataset_name trl-lib/tldr \ + --dataset_test_split validation \ + --output_dir models/minimal/ppo_tldr \ + --learning_rate 3e-6 \ + --per_device_train_batch_size 16 \ + --gradient_accumulation_steps 4 \ + --total_episodes 1000000 \ + --model_name_or_path EleutherAI/pythia-1b-deduped \ + --sft_model_path cleanrl/EleutherAI_pythia-1b-deduped__sft__tldr \ + --reward_model_path cleanrl/EleutherAI_pythia-1b-deduped__reward__tldr \ + --local_rollout_forward_batch_size 16 \ + --missing_eos_penalty 1.0 \ + --stop_token eos \ + --eval_strategy steps \ + --eval_steps 100 +``` + +Checkpoints and experiment tracking are available at: + +- [🤗 Model checkpoint](https://huggingface.co/trl-lib/ppo_tldr) +- [🐝 Tracked experiment](https://wandb.ai/huggingface/trl/runs/dd2o3g35) + +The PPO checkpoint gets a 64.7% preferred rate vs the 33.0% preference rate of the SFT checkpoint (evaluated with GPT-4o mini as a judge). This is a good sign that the PPO training is working as intended. + +Metrics: + +![PPO v2](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/ppov2.png) + +```bash +# pip install openrlbenchmark==0.2.1a5 +# see https://github.com/openrlbenchmark/openrlbenchmark#get-started for documentation +# to use it, change `?we=huggingface&wpn=trl` to your own project and `?tag=pr-1540` to your own tag +python -m openrlbenchmark.rlops_multi_metrics \ + --filters '?we=huggingface&wpn=trl&xaxis=train/episode&ceik=output_dir&cen=sft_model_path&metrics=train/objective/rlhf_reward&metrics=train/objective/scores&metrics=train/objective/kl&metrics=train/objective/non_score_reward&metrics=train/objective/entropy&metrics=train/policy/approxkl_avg&metrics=train/policy/clipfrac_avg&metrics=train/loss/policy_avg&metrics=train/loss/value_avg&metrics=train/val/clipfrac_avg&metrics=train/policy/entropy_avg&metrics=train/val/ratio&metrics=train/val/ratio_var&metrics=train/val/num_eos_tokens&metrics=train/lr&metrics=train/eps' \ + "cleanrl/EleutherAI_pythia-1b-deduped__sft__tldr?tag=pr-1540" \ + --env-ids models/minimal/ppo_tldr \ + --pc.ncols 4 \ + --pc.ncols-legend 1 \ + --pc.xlabel "Episode" \ + --output-filename benchmark/trl/pr-1540/ppo \ + --scan-history +``` + +## PPOTrainer + +[[autodoc]] experimental.ppo.PPOTrainer + - train + - save_model + - push_to_hub + +## PPOConfig + +[[autodoc]] experimental.ppo.PPOConfig + +## PreTrainedModelWrapper + +[[autodoc]] experimental.ppo.PreTrainedModelWrapper + +## AutoModelForCausalLMWithValueHead + +[[autodoc]] experimental.ppo.AutoModelForCausalLMWithValueHead + - __init__ + - forward + - generate + - _init_weights + +## AutoModelForSeq2SeqLMWithValueHead + +[[autodoc]] experimental.ppo.AutoModelForSeq2SeqLMWithValueHead + - __init__ + - forward + - generate + - _init_weights diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/prm_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/prm_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..29d73e819b377661191a93e495aeeb00dcf81bba --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/prm_trainer.md @@ -0,0 +1,122 @@ +# PRM Trainer + +[![model badge](https://img.shields.io/badge/All_models-PRM-blue)](https://huggingface.co/models?other=prm,trl) + +> [!WARNING] +> PRM Trainer is an experimental API which is subject to change at any time. + +## Overview + +Process-supervised Reward Models (PRM) were proposed in [Solving math word problems with process- and outcome-based feedback](https://huggingface.co/papers/2211.14275) by Jonathan Uesato, Nate Kushman, Ramana Kumar, Francis Song, Noah Siegel, Lisa Wang, Antonia Creswell, Geoffrey Irving, and Irina Higgins. + +The abstract from the paper is the following: + +> Recent work has shown that asking language models to generate reasoning steps improves performance on many reasoning tasks. When moving beyond prompting, this raises the question of how we should supervise such models: outcome-based approaches which supervise the final result, or process-based approaches which supervise the reasoning process itself? Differences between these approaches might naturally be expected not just in final-answer errors but also in reasoning errors, which can be difficult to detect and are problematic in many real-world domains such as education. We run the first comprehensive comparison between process- and outcome-based approaches trained on a natural language task, GSM8K. We find that pure outcome-based supervision produces similar final-answer error rates with less label supervision. However, for correct reasoning steps we find it necessary to use processbased supervision or supervision from learned reward models that emulate process-based feedback. In total, we improve the previous best results from 16.8% → 12.7% final-answer error and 14.0% → 3.4% reasoning error among final-answer-correct solutions. + +This post-training method was contributed by [Gaetan Lopez](https://github.com/gaetanlop), [Lewis Tunstall](https://huggingface.co/lewtun), [Quentin Gallouédec](https://huggingface.co/qgallouedec) and [Agustín Piqueres](https://huggingface.co/plaguss). + +## Quick start + +This example demonstrates how to train a model using the PRM method. We use the [Qwen 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B) as the base model. We use the stepwise supervision data from the [Math Shepherd dataset](https://huggingface.co/datasets/trl-lib/math_shepherd). You can view the data in the dataset here: + + + +Below is the script to train the model: + +```python +# train_prm.py +from datasets import load_dataset +from trl.experimental.prm import PRMConfig, PRMTrainer +from transformers import AutoModelForTokenClassification, AutoTokenizer + +model = AutoModelForTokenClassification.from_pretrained("Qwen/Qwen2-0.5B", num_labels=2) +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B") +train_dataset = load_dataset("trl-lib/math_shepherd", split="train[:10%]") + +training_args = PRMConfig(output_dir="Qwen2-0.5B-Reward-Math-Sheperd") +trainer = PRMTrainer(model=model, args=training_args, processing_class=tokenizer, train_dataset=train_dataset) +trainer.train() +``` + +Execute the script using the following command: + +```bash +accelerate launch train_prm.py +``` + +Distributed across 8 GPUs, the training takes approximately 1 hour. + +To see how the [trained model](https://huggingface.co/trl-lib/Qwen2-0.5B-Reward-Math-Sheperd) performs, you can use the following script. + +```python +from datasets import load_dataset +from transformers import pipeline + +pipe = pipeline("token-classification", model="trl-lib/Qwen2-0.5B-Reward-Math-Sheperd") +dataset = load_dataset("trl-lib/math_shepherd") +example = { + "prompt": "Musa is the class teacher of a class of 45 students. He wants to split them into three groups by age. If a third of the class is under 11 years, and two-fifths are above 11 but under 13, how many students will be in the third group (13 years and above)?", + "completions": [ + "Step 1: A third of the class is under 11 years because 11 - 1/3 = <<11-1/3=7>>7.", + "Step 2: Two-fifths of the class are above 11 but under 13 because 2/5 * 11 = <<2/5*11=8>>8.", + "Step 3: There are 45 students, so the third group will have 45 - 7 - 8 = <<45-7-8=20>>20 students. The answer is: 20", + ], + "labels": [True, False, False], +} + + +separator = "\n" # It's important to use the same separator as the one used during training + +for idx in range(1, len(example["completions"]) + 1): + steps = example["completions"][0:idx] + text = separator.join((example["prompt"], *steps)) + separator # Add a separator between the prompt and each steps + pred_entity = pipe(text)[-1]["entity"] + pred = {"LABEL_0": False, "LABEL_1": True}[pred_entity] + label = example["labels"][idx - 1] + print(f"Step {idx}\tPredicted: {pred} \tLabel: {label}") +``` + +```text +Step 1 Predicted: True Label: True +Step 2 Predicted: False Label: False +Step 3 Predicted: False Label: False +``` + +It's a win! + +## Expected dataset type + +PRM requires a [stepwise supervision](dataset_formats#stepwise-supervision). +The dataset should contain the following columns: `prompt`, `completions` and `labels`, where `completions` contains a list of reasoning steps and `labels` a list of booleans or floats indicating the correctness of each step. + +The [`experimental.prm.PRMTrainer`] only supports [standard](dataset_formats#standard) dataset format. + +## Example script + +We provide an example script to train a model using the PRM method. The script is available in [`examples/scripts/prm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/prm.py) + +To use the PRM script with the [Qwen2 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B) on the [Math Shepherd dataset](https://huggingface.co/datasets/trl-lib/math_shepherd), run the following command: + +```bash +accelerate launch examples/scripts/prm.py \ + --model_name_or_path Qwen/Qwen2-0.5B \ + --dataset_name trl-lib/math_shepherd \ + --num_train_epochs 1 \ + --output_dir Qwen2-0.5B-Reward-Math-Sheperd +``` + +## PRMTrainer + +[[autodoc]] experimental.prm.PRMTrainer + - train + - save_model + - push_to_hub + +## PRMConfig + +[[autodoc]] experimental.prm.PRMConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/ptt_integration.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/ptt_integration.md new file mode 100644 index 0000000000000000000000000000000000000000..3148215c14ec11801d63acd3e73dd175a3657b7a --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/ptt_integration.md @@ -0,0 +1,193 @@ +# Post-Training Toolkit Integration + +[Post-Training Toolkit](https://github.com/microsoft/post-training-toolkit) is a diagnostic and observability layer for RLHF training runs. Add one callback to any TRL trainer and get **auto-metrics**, **crash postmortems**, and **literature-backed heuristics**—without writing glue code. + +It was built to operationalize the debugging patterns we found most useful when running post-training at scale. + +## Usage + +1. First, install Post-Training Toolkit: + +```bash +pip install post-training-toolkit +``` + +2. Add one callback to your trainer. That's it! + + + + +```python +from post_training_toolkit import DiagnosticsCallback +from trl import DPOTrainer + +trainer = DPOTrainer( + model=model, + args=training_args, + callbacks=[DiagnosticsCallback()], # ← Just add this + ... +) +trainer.train() +``` + + + + +```python +from post_training_toolkit import DiagnosticsCallback +from trl.experimental.ppo import PPOTrainer + +trainer = PPOTrainer( + model=model, + args=training_args, + callbacks=[DiagnosticsCallback()], # ← Just add this + ... +) +trainer.train() +``` + + + + +```python +from post_training_toolkit import DiagnosticsCallback +from trl import SFTTrainer + +trainer = SFTTrainer( + model=model, + args=training_args, + callbacks=[DiagnosticsCallback()], # ← Just add this + ... +) +trainer.train() +``` + + + + +```python +from post_training_toolkit import DiagnosticsCallback +from trl.experimental.orpo import ORPOTrainer + +trainer = ORPOTrainer( + model=model, + args=training_args, + callbacks=[DiagnosticsCallback()], # ← Just add this + ... +) +trainer.train() +``` + + + + +```python +from post_training_toolkit import DiagnosticsCallback +from trl import KTOTrainer + +trainer = KTOTrainer( + model=model, + args=training_args, + callbacks=[DiagnosticsCallback()], # ← Just add this + ... +) +trainer.train() +``` + + + + +```python +from post_training_toolkit import DiagnosticsCallback +from trl.experimental.cpo import CPOTrainer + +trainer = CPOTrainer( + model=model, + args=training_args, + callbacks=[DiagnosticsCallback()], # ← Just add this + ... +) +trainer.train() +``` + + + + +```python +from post_training_toolkit import DiagnosticsCallback +from trl import GRPOTrainer + +trainer = GRPOTrainer( + model=model, + args=training_args, + callbacks=[DiagnosticsCallback()], # ← Just add this + ... +) +trainer.train() +``` + + + + +## What You Get + +**Example output:** +```text +[HIGH] DPO loss stuck at ~0.693 (random chance). Model may not be learning preferences. + Ref: Rafailov et al. (2023) 'DPO', Section 4.2 + +[RECOMMENDED] Increase learning rate 2-5x, check data quality, or reduce beta. +``` + +## Example Demo + +See a full working example with auto-stop in action: + +📂 **[demo/live_demo.ipynb](https://github.com/microsoft/post-training-toolkit/blob/main/demo/notebooks/demo_live_output.ipynb)** + +📂 **[demo/scripts/custom_heuristic.py](https://github.com/microsoft/post-training-toolkit/blob/main/demo/scripts/custom_heuristic_demo.py)** + + +### 1. Auto-Metrics +The callback automatically captures algorithm-specific metrics, backed by the latest research and industry push: + +| Trainer | Key Metrics Captured | +|---------|---------------------| +| **DPO** | loss, win_rate, reward_margin, logps_chosen/rejected | +| **PPO** | policy_loss, value_loss, entropy, clip_fraction, KL | +| **GRPO** | group rewards, advantages, policy loss, KL | +| **SFT** | loss, perplexity, accuracy | +| **ORPO** | sft_loss, odds_ratio_loss, log_odds_ratio | +| **KTO** | kl, logps for desirable/undesirable | + + +### 2. Crash Postmortems +If training crashes or gets interrupted, you get a `postmortem.json` with full context: + +```json +{ + "exit_reason": "exception", + "last_step": 847, + "timestamp": "2025-12-17T19:26:04Z", + "final_metrics": {"dpo_loss": 0.693, "win_rate": 0.52} +} +``` + +No more "what step did it die on?" + +### 3. Auto-Stop on Critical Issues + +Enable automatic training termination when critical issues are detected: + +```python +callback = DiagnosticsCallback(stop_on_critical=True) +``` + +## Distributed Training +Works automatically with multi-GPU setups. Zero configuration needed: + +```bash +accelerate launch --num_processes 8 train.py +``` + +Automatically detects stragglers, aggregates metrics across ranks, and tracks memory balance. diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/quickstart.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/quickstart.md new file mode 100644 index 0000000000000000000000000000000000000000..1f66274ca3f4db4373662dbfa2b935bb33ee53b2 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/quickstart.md @@ -0,0 +1,151 @@ +# Quickstart + +TRL is a comprehensive library for post-training foundation models using techniques like Supervised Fine-Tuning (SFT), Group Relative Policy Optimization (GRPO), Direct Preference Optimization (DPO). + +## Quick Examples + +Get started instantly with TRL's most popular trainers. Each example uses compact models for quick experimentation. + +### Supervised Fine-Tuning + +```python +from trl import SFTTrainer +from datasets import load_dataset + +trainer = SFTTrainer( + model="Qwen/Qwen2.5-0.5B", + train_dataset=load_dataset("trl-lib/Capybara", split="train"), +) +trainer.train() +``` + +### Group Relative Policy Optimization + +```python +from trl import GRPOTrainer +from datasets import load_dataset +from trl.rewards import accuracy_reward + +trainer = GRPOTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", + train_dataset=load_dataset("trl-lib/DeepMath-103K", split="train"), + reward_funcs=accuracy_reward, +) +trainer.train() +``` + +### Direct Preference Optimization + +```python +from trl import DPOTrainer +from datasets import load_dataset + +trainer = DPOTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", + train_dataset=load_dataset("trl-lib/ultrafeedback_binarized", split="train"), +) +trainer.train() +``` + +### Reward Modeling + +```python +from trl import RewardTrainer +from datasets import load_dataset + +dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") + +trainer = RewardTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", + train_dataset=dataset, +) +trainer.train() +``` + +## Command Line Interface + +Skip the code entirely - train directly from your terminal: + +```bash +# SFT: Fine-tune on instructions +trl sft --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name trl-lib/Capybara + +# DPO: Align with preferences +trl dpo --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ + --dataset_name trl-lib/ultrafeedback_binarized + +# Reward: Train a reward model +trl reward --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ + --dataset_name trl-lib/ultrafeedback_binarized +``` + +## What's Next? + +### 📚 Learn More + +- [SFT Trainer](sft_trainer) - Complete SFT guide +- [DPO Trainer](dpo_trainer) - Preference alignment +- [GRPO Trainer](grpo_trainer) - Group relative policy optimization + +### 🚀 Scale Up + +- [Distributed Training](distributing_training) - Multi-GPU setups +- [Memory Optimization](reducing_memory_usage) - Efficient training +- [PEFT Integration](peft_integration) - LoRA and QLoRA + +### 💡 Examples + +- [Example Scripts](https://github.com/huggingface/trl/tree/main/examples) - Production-ready code +- [Community Tutorials](community_tutorials) - External guides + +## Troubleshooting + +### Out of Memory? + +Reduce batch size and enable optimizations: + + + + +```python +training_args = SFTConfig( + per_device_train_batch_size=1, # Start small + gradient_accumulation_steps=8, # Maintain effective batch size +) +``` + + + + +```python +training_args = DPOConfig( + per_device_train_batch_size=1, # Start small + gradient_accumulation_steps=8, # Maintain effective batch size +) +``` + + + + +```python +training_args = GRPOConfig( + per_device_train_batch_size=1, # Start small + gradient_accumulation_steps=8, # Maintain effective batch size + num_generations=4, # Reduce from default 8 (GRPO generates num_generations completions per prompt) + max_completion_length=256, # Tune based on task; longer sequences cost more memory +) +``` + + + + +### Loss not decreasing? + +Try adjusting the learning rate: + +```python +training_args = SFTConfig(learning_rate=2e-5) # Good starting point +``` + +For more help, open an [issue on GitHub](https://github.com/huggingface/trl/issues). diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/rapidfire_integration.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/rapidfire_integration.md new file mode 100644 index 0000000000000000000000000000000000000000..c2867922560a8524b295918a059bbfccc2cda3be --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/rapidfire_integration.md @@ -0,0 +1,473 @@ +# RapidFire AI Integration + +RapidFire AI is an open-source experiment execution framework that integrates with TRL to turn "train one configuration at a time" into **real-time, side-by-side comparison of many configurations on the same GPU(s)** — so you can iterate on hyperparameters, LoRA settings, prompt schemes, and ablations **16–24× faster with no extra hardware**. + +Links: [GitHub](https://github.com/RapidFireAI/rapidfireai) · [Docs](https://oss-docs.rapidfire.ai) · [Try in Colab](http://tinyurl.com/rapidfireai-colab) + +## Why use RapidFire AI with TRL? + +When fine-tuning or post-training with TRL, you typically need to: + +- Try different hyperparameter configurations +- Compare different LoRA settings +- Test different prompt schemes +- Run ablation studies + +| Scenario: comparing N training configs on the same GPU(s) | TRL alone | TRL + RapidFire AI | +| --- | --- | --- | +| Training strategy | Run N configs sequentially | Run N configs concurrently | +| When can you compare configs? | After all runs finish | Live, from the first chunk | +| Stop losers / clone winners mid-training | No | Yes (Interactive Control Operations) | + +### How It Works + +RapidFire AI employs **adaptive chunk-based scheduling**: + +``` +GPU Timeline (Single GPU): +Chunk 1: [Config A] → [Config B] → [Config C] → [Config D] +Chunk 2: [Config A] → [Config B] → [Config C] → [Config D] +Chunk 3: [Config A] → [Config B] → [Config C] → [Config D] +``` + +This enables: + +- Early comparison of configurations on same data subsets incrementally +- Efficient GPU utilization and minimizing idle times +- Real-time and automated experiment metrics tracking +- Dynamic control over runs in flight to incentivize more experimentation + +## Key Features + +- **16-24× higher experimentation throughput** compared to sequential training. +- **Almost no code changes** - simple drop-in config APIs that just wrap around existing TRL and PEFT config APIs. +- **Interactive Control Operations** - real-time control to stop, resume, and clone-modify (with or without warm starting) training runs in flight. +- **Integration with Fully Sharded Data Parallel (FSDP)** for training large models that do not fit on a single GPU by sharding parameters, gradients, and optimizer states across multiple GPUs. +- **Full compatibility** with transformers, PEFT, SFTTrainer, DPOTrainer, and GRPOTrainer. +- **Pluggable experiment tracking**: MLflow (default), TensorBoard, and Trackio, enabled individually or in combination. +- **Zero-setup Google Colab support**: one-click tutorial notebooks for SFT, DPO, and GRPO on free T4 GPUs. +- **Production-Ready**: Already used in production environments with complete working examples. + +## Installation + +### Prerequisites + +- Python 3.12.x +- NVIDIA GPU with Compute Capability 7.x or 8.x (multiple GPUs required for FSDP) +- CUDA Toolkit 11.8+ +- PyTorch 2.8+ + +### pip install + +```bash +pip install rapidfireai +``` + +Once installed, authenticate with Hugging Face and initialize RapidFire AI: + +```bash +# Authenticate with Hugging Face +hf auth login --token YOUR_TOKEN + +# Workaround for current issue: https://github.com/huggingface/xet-core/issues/527 +pip uninstall -y hf-xet + +# Initialize RapidFire AI +rapidfireai init + +# Start the RapidFire AI server +rapidfireai start +``` + +The dashboard will be available at `http://localhost:8853` where you can monitor and control experiments in real-time. + +## Quick Start: SFT Training with Multiple Configs + +Here's a complete example showing how to train multiple SFT configurations concurrently: + +```python +from rapidfireai import Experiment +from rapidfireai.automl import List, RFGridSearch, RFModelConfig, RFLoraConfig, RFSFTConfig +from datasets import load_dataset +from transformers import AutoModelForCausalLM, AutoTokenizer + +# Load dataset +dataset = load_dataset("bitext/Bitext-customer-support-llm-chatbot-training-dataset") +train_dataset = dataset["train"].select(range(128)).shuffle(seed=42) +eval_dataset = dataset["train"].select(range(100, 124)).shuffle(seed=42) + +# Define data formatting function +def formatting_function(row): + return { + "prompt": [ + {"role": "system", "content": "You are a helpful customer support assistant."}, + {"role": "user", "content": row["instruction"]}, + ], + "completion": [ + {"role": "assistant", "content": row["response"]} + ] + } + +# Initialize experiment +experiment = Experiment(experiment_name="sft-customer-support") + +# Define multiple LoRA configurations to compare +peft_configs = List([ + RFLoraConfig(r=8, lora_alpha=16, lora_dropout=0.1, + target_modules=["q_proj", "v_proj"], bias="none"), + RFLoraConfig(r=32, lora_alpha=64, lora_dropout=0.1, + target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], bias="none") +]) + +# Define multiple training configurations +# 2 base configs × 2 PEFT configs = 4 total training runs +config_set = List([ + RFModelConfig( + model_name="TinyLlama/TinyLlama-1.1B-Chat-v1.0", + peft_config=peft_configs, + training_args=RFSFTConfig( # Wraps TRL's SFTConfig + learning_rate=1e-3, + per_device_train_batch_size=4, + max_steps=128, + fp16=True, + ), + model_type="causal_lm", + model_kwargs={"device_map": "auto", "dtype": "auto", "use_cache": False}, + formatting_func=formatting_function, + ), + RFModelConfig( + model_name="TinyLlama/TinyLlama-1.1B-Chat-v1.0", + peft_config=peft_configs, + training_args=RFSFTConfig( + learning_rate=1e-4, # Different learning rate + per_device_train_batch_size=4, + max_steps=128, + fp16=True, + ), + model_type="causal_lm", + model_kwargs={"device_map": "auto", "dtype": "auto", "use_cache": False}, + formatting_func=formatting_function, + ) +]) + +# Define model creation function +def create_model(model_config): + model = AutoModelForCausalLM.from_pretrained( + model_config["model_name"], + **model_config["model_kwargs"] + ) + tokenizer = AutoTokenizer.from_pretrained(model_config["model_name"]) + return (model, tokenizer) + +# Create grid search over all configurations +config_group = RFGridSearch(configs=config_set, trainer_type="SFT") + +# Run all 4 configurations concurrently with chunk-based scheduling +experiment.run_fit(config_group, create_model, train_dataset, eval_dataset, + num_chunks=4, seed=42) + +# End experiment +experiment.end() +``` + +### What Happens During Execution + +When you run this example: + +1. **Config Expansion**: 2 base configurations × 2 PEFT configs = 4 total training runs +2. **Chunk-based Scheduling**: Training data is divided into chunks, and all 4 configs train concurrently +3. **GPU Swapping**: Models are swapped in/out of GPU memory based on chunk boundaries +4. **Real-time Tracking**: All metrics visible in the dashboard at `http://localhost:8853` +5. **Interactive Control**: Stop, resume, or clone-modify any configuration from the dashboard + +This delivers **16-24× higher throughput** compared to training each configuration sequentially! + +## Supported TRL Trainers + +### SFTTrainer + +Use `RFSFTConfig` as a drop-in replacement for `SFTConfig`: + +```python +from rapidfireai.automl import RFSFTConfig + +training_args = RFSFTConfig( + learning_rate=5e-5, + per_device_train_batch_size=4, + num_train_epochs=3, + max_length = 512, + # ... all other SFTConfig parameters supported +) +``` + +**Example Notebook**: [SFT for Customer Support](https://github.com/RapidFireAI/rapidfireai/blob/main/tutorial_notebooks/fine-tuning/rf-tutorial-sft-chatqa-lite.ipynb) + +### DPOTrainer + +Use `RFDPOConfig` as a drop-in replacement for `DPOConfig`: + +```python +from rapidfireai.automl import RFDPOConfig + +training_args = RFDPOConfig( + beta=0.1, + loss_type="sigmoid", + max_length=1024, + learning_rate=5e-4, + # ... all other DPOConfig parameters supported +) +``` + +**Example Notebook**: [DPO for Preference Alignment](https://github.com/RapidFireAI/rapidfireai/blob/main/tutorial_notebooks/post-training/rf-tutorial-dpo-alignment-lite.ipynb) + +### GRPOTrainer + +Use `RFGRPOConfig` as a drop-in replacement for `GRPOConfig`: + +```python +from rapidfireai.automl import RFGRPOConfig + +training_args = RFGRPOConfig( + learning_rate=5e-6, + num_generations=8, + max_completion_length=256, + # ... all other GRPOConfig parameters supported +) +``` + +**Example Notebook**: [GRPO for Math Reasoning](https://github.com/RapidFireAI/rapidfireai/blob/main/tutorial_notebooks/post-training/rf-tutorial-grpo-mathreasoning-lite.ipynb) + +## Core Concepts + +### Chunk-Based Concurrent Training + +RapidFire AI divides training data into chunks and alternates between configurations: + +``` +GPU Timeline (Single GPU): +Chunk 1: [Config A] → [Config B] → [Config C] → [Config D] +Chunk 2: [Config A] → [Config B] → [Config C] → [Config D] +Chunk 3: [Config A] → [Config B] → [Config C] → [Config D] +... +``` + +This approach maximizes GPU utilization and enables early comparison of configurations while maintaining training stability through automatic checkpointing. + +### Interactive Control Operations (IC Ops) + +Through the RapidFire AI dashboard, you can dynamically control running experiments: + +- **Stop**: Pause a configuration (checkpointed automatically) +- **Resume**: Continue from last checkpoint +- **Clone-Modify**: Duplicate a configuration with modifications (new run starts from scratch) +- **Clone-Modify with Warm Start**: Clone-modify and initialize from the parent's weights +- **Delete**: Remove failed or unwanted runs + +This enables adaptive experimentation where you can stop underperforming configs early and clone promising ones with tweaked hyperparameters. + +### Multi-Config Experimentation + +Use `RFGridSearch` or `RFRandomSearch` to automatically generate configuration combinations: + +```python +# Grid search: tests all combinations +config_group = RFGridSearch(configs=config_list, trainer_type="SFT") + +# Random search: samples N configurations +config_group = RFRandomSearch(configs=config_list, trainer_type="DPO", num_samples=10) +``` + +## Advanced Features + +### PEFT/LoRA Integration + +Full support for parameter-efficient fine-tuning: + +```python +from rapidfireai.automl import RFLoraConfig +from peft import TaskType + +lora_config = RFLoraConfig( + task_type=TaskType.CAUSAL_LM, + r=64, + lora_alpha=64, + lora_dropout=0.1, + target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], + bias="none" +) +``` + +### Custom Reward Functions (GRPO) + +Define multiple reward functions for GRPO training: + +```python +def correctness_reward(prompts, completions, answer, **kwargs): + """Reward for correct answers""" + responses = [completion[0]['content'] for completion in completions] + extracted = [extract_answer(r) for r in responses] + return [2.0 if r == a else 0.0 for r, a in zip(extracted, answer)] + +def format_reward(completions, **kwargs): + """Reward for proper formatting""" + import re + pattern = r".*?\s*.*?" + responses = [completion[0]["content"] for completion in completions] + matches = [re.match(pattern, r) for r in responses] + return [0.5 if match else 0.0 for match in matches] + +# Use in model config +config = RFModelConfig( + reward_funcs=[correctness_reward, format_reward], + # ... other parameters +) +``` + +### Multi-GPU Support + +RapidFire AI automatically detects and utilizes all available GPUs. By default, the scheduler distributes independent configurations across GPUs (data-parallel across configs), so no special setup is required to run `N` configs on `N` GPUs concurrently. + +For models that do not fit on a single GPU, RapidFire AI also supports **Fully Sharded Data Parallel (FSDP)** to shard a single configuration across multiple GPUs — see the next section. + +### Multi-GPU Training with FSDP + +When a model is too large for a single GPU, enable FSDP directly through the training args of `RFSFTConfig` or `RFDPOConfig` — the same `fsdp` and `fsdp_config` fields exposed by Hugging Face `TrainingArguments`: + +```python +from rapidfireai.automl import RFModelConfig, RFSFTConfig, RFLoraConfig + +model_config = RFModelConfig( + model_name="meta-llama/Llama-3.1-8B-Instruct", + peft_config=RFLoraConfig( + r=16, lora_alpha=32, lora_dropout=0.05, + target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], + bias="none", + ), + training_args=RFSFTConfig( + learning_rate=2e-4, + per_device_train_batch_size=1, + gradient_accumulation_steps=8, + fsdp="full_shard auto_wrap", + fsdp_config={ + "sharding_strategy": "FULL_SHARD", + "auto_wrap_policy": "TRANSFORMER_BASED_WRAP", + "backward_prefetch": "backward_pre", + "forward_prefetch": True, + "use_orig_params": False, + "cpu_ram_efficient_loading": True, + "offload_params": True, + "sync_module_states": True, + "limit_all_gathers": True, + }, + ), + model_type="causal_lm", + model_kwargs={"dtype": "auto"}, +) +``` + +Key points: + +- FSDP works transparently with RapidFire AI's chunk-based scheduling, IC Ops (stop / resume / clone-modify with or without warm-starting), and all supported metric tracking backends. +- FSDP is fully compatible with PEFT / LoRA — LoRA adapter weights are collected efficiently across shards when saving checkpoints. +- FSDP composes with grid search and random search: each expanded config gets its own sharded training run. + +**Example Notebooks**: +- [SFT with FSDP (lite, small model)](https://github.com/RapidFireAI/rapidfireai/blob/main/tutorial_notebooks/fine-tuning/rf-tutorial-sft-chatqa-fsdp-lite.ipynb) +- [SFT with FSDP (large model)](https://github.com/RapidFireAI/rapidfireai/blob/main/tutorial_notebooks/fine-tuning/rf-tutorial-sft-chatqa-fsdp-large.ipynb) +- [DPO with FSDP](https://github.com/RapidFireAI/rapidfireai/blob/main/tutorial_notebooks/post-training/rf-tutorial-dpo-alignment-fsdp-lite.ipynb) + +### Experiment Tracking Backends + +RapidFire AI supports three metric logging backends that can be used individually or together: **MLflow** (the default for local installs), **TensorBoard** (the default in Google Colab), and **Trackio**. + +Select one or more backends at server startup with the `--tracking-backends` flag: + +```bash +# MLflow only (default on local installs) +rapidfireai start --tracking-backends mlflow + +# TensorBoard only +rapidfireai start --tracking-backends tensorboard + +# Any combination +rapidfireai start --tracking-backends mlflow tensorboard trackio +``` + +Equivalent environment variables are also available: + +- `RF_MLFLOW_ENABLED` (default `true`, or `false` in Colab) +- `RF_TENSORBOARD_ENABLED` (default `false`, or `true` in Colab) +- `RF_TRACKIO_ENABLED` (default `false`) + +All three backends receive the same metrics (loss, evaluation scores, learning rate, etc.) and respect IC Ops run lifecycle events, so you can use, for example, Trackio for lightweight sharing alongside MLflow for a full local dashboard. + +### Running in Google Colab + +RapidFire AI runs on free Google Colab T4 GPUs, with tutorial notebooks for SFT, DPO, GRPO, and RAG / context-engineering workflows. In Colab, TensorBoard is the default tracking backend (MLflow is disabled for simplicity), and the usual `rapidfireai init` / `rapidfireai start` commands run directly from notebook cells — no terminal access required. + +Get started: [RapidFire AI in Google Colab](http://tinyurl.com/rapidfireai-colab). + +## Best Practices + +### Tuning Chunk Granularity + +The `num_chunks` parameter controls swap frequency: + +```python +# Fewer chunks = less overhead, less frequent comparison +experiment.run_fit(..., num_chunks=2) + +# More chunks = more overhead, more frequent comparison +experiment.run_fit(..., num_chunks=16) +``` + +**Rule of thumb**: Start with `num_chunks=4` and adjust based on dataset size and number of configurations. + +### Memory Management + +For large models, use quantization: + +```python +from transformers import BitsAndBytesConfig +import torch + +bnb_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_compute_dtype=torch.bfloat16, + bnb_4bit_use_double_quant=True, + bnb_4bit_quant_type="nf4", +) + +model_kwargs = { + "quantization_config": bnb_config, + "device_map": "auto", +} +``` + +## Performance Benchmarks + +Based on internal benchmarks comparing sequential vs. RapidFire AI concurrent training: + +| Scenario | Sequential Time | RapidFire AI Time | Speedup | +|----------|----------------|-------------------|---------| +| 4 configs, 1 GPU | 120 min | 7.5 min | 16× | +| 8 configs, 1 GPU | 240 min | 12 min | 20× | +| 4 configs, 2 GPUs | 60 min | 4 min | 15× | +| 8 configs, 4 GPUs | 60 min | 3 min | 20× | + +*Benchmarks performed on NVIDIA A100 40GB with TinyLlama-1.1B and Llama-3.2-1B models* + +## Troubleshooting + +For troubleshooting guidance, see the [RapidFire AI Troubleshooting Guide](https://oss-docs.rapidfire.ai/en/latest/troubleshooting.html). + +## Additional Resources +- **Colab Notebook**: [RapidFire AI in Google Colab](http://tinyurl.com/rapidfireai-colab) +- **Documentation**: [oss-docs.rapidfire.ai](https://oss-docs.rapidfire.ai) +- **GitHub**: [RapidFireAI/rapidfireai](https://github.com/RapidFireAI/rapidfireai) +- **PyPI**: [pypi.org/project/rapidfireai](https://pypi.org/project/rapidfireai/) +- **Discord**: [Join our Discord](https://discord.gg/6vSTtncKNN) +- **Tutorial Notebooks**: [GitHub Repository](https://github.com/RapidFireAI/rapidfireai/tree/main/tutorial_notebooks) + +Learn more about RapidFire AI in their [official repository](https://github.com/RapidFireAI/rapidfireai) and [documentation](https://oss-docs.rapidfire.ai). + diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/reducing_memory_usage.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/reducing_memory_usage.md new file mode 100644 index 0000000000000000000000000000000000000000..28b70df5b3a0047924d12106f500bf3fb9f7768e --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/reducing_memory_usage.md @@ -0,0 +1,359 @@ +# Reducing Memory Usage + +Training workflows can often be optimized to **reduce memory consumption**, and TRL provides several built-in features to help achieve this. + +Below, we outline these techniques and recommend experimenting with different combinations to figure out which configuration works best for your specific setup. + +Each method includes examples for the supported trainers. If you're unsure whether a technique is compatible with your trainer, please take a look at the corresponding trainer documentation. + +For additional strategies, such as **gradient checkpointing**, which is supported across all trainers, see the [`transformers` performance guide](https://huggingface.co/docs/transformers/perf_train_gpu_one#gradient-checkpointing). + +## Truncation + +Sequence lengths in the dataset can vary widely. When data is batched, sequences are padded to match the longest one in the batch, which can cause high memory usage, even if most sequences are relatively short. + +![Truncation prompt-completion](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/why_you_should_truncate.png) + +To reduce memory usage, it's important to truncate sequences to a reasonable length. While TRL trainers truncate sequences by default, you may want to adjust the default truncation length to better align with your specific use case. + + + + +DPO truncation is controlled via `max_length`, which truncates the combined prompt+completion sequence. + +![DPO truncation](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/truncation_prompt_completion.png) + +To set the truncation parameter, use the following code snippet: + +```python +from trl import DPOConfig + +training_args = DPOConfig(..., max_length=...) +``` + +> [!WARNING] +> The legacy `max_prompt_length` and `max_completion_length` parameters are now removed; instead, filter or pre-truncate overlong prompts/completions in your dataset before training. + + + + +SFT truncation is applied to the input sequence via the `max_length` parameter. + +![Truncation input ids](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/truncation_input_ids.png) + +To set the truncation parameter, use the following code snippet: + +```python +from trl import SFTConfig + +training_args = SFTConfig(..., max_length=...) +``` + + + + +### How to choose the `max_length` value? + +If `max_length` is too small, a significant portion of your tokens will be discarded and won't contribute to training. If it's too large, memory usage can spike, potentially leading to out-of-memory (OOM) errors. Without packing or padding-free, a large `max_length` may also result in inefficient training, as many tokens will be padding. + +To help you choose an appropriate value, we provide a utility to visualize the sequence length distribution in your dataset. + + + +## Packing + +> [!TIP] +> This technique is available only for **SFT** training and setups that use **FlashAttention** (or its variants). + +[Truncation](#truncation) has several drawbacks: + +1. **Loss of information**: Important tokens at the end of sequences may be discarded. +2. **Choosing truncation length**: Too short loses data; too long reduces efficiency. + +Packing mitigates these issues by grouping multiple sequences into the same training row, filling each row up to `max_length`. + +![Packing](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/packing_3.png) + +TRL implements packing using **Best-Fit Decreasing (BFD)** bin packing, which groups sequences efficiently while minimizing padding. When a sequence exceeds `max_length`, different strategies determine how the overflow tokens are handled. + +TRL supports three strategies: + +* `"bfd"` (default): Uses **Best-Fit Decreasing packing**. If a sequence exceeds `max_length`, the overflow tokens are discarded. + +* `"bfd_split"`: Uses **Best-Fit Decreasing packing**, but long sequences are split into chunks ≤ `max_length` before packing. This preserves all tokens and follows the approach proposed in [Fewer Truncations Improve Language Modeling](https://huggingface.co/papers/2404.10830). + +* `"wrapped"`: All tokens are concatenated into a stream and split into fixed-length blocks. This minimizes padding but may mix unrelated examples. This strategy corresponds to the *concatenate-then-split* preprocessing described in the literature (e.g., [Fewer Truncations Improve Language Modeling](https://huggingface.co/papers/2404.10830)). It has the downside of breaking sequence continuity for a large fraction of the dataset, which hurts performance, as discussed in the [Qwen3-Coder-Next Technical Report](https://huggingface.co/papers/2603.00729). + +> [!NOTE] +> If all sequences are shorter than `max_length`, **`bfd` and `bfd_split` behave identically**, since no truncation or splitting is required. + +```python +from trl import SFTConfig + +training_args = SFTConfig( + ..., + packing=True, + packing_strategy="bfd", + max_length=512, +) +``` + +## PEFT for parameter-efficient fine-tuning + +Parameter-Efficient Fine-Tuning (PEFT) methods like LoRA are among the most effective techniques for reducing memory usage during training. Instead of training all model parameters, PEFT methods train only a small number of adapter parameters, significantly reducing memory requirements and enabling fine-tuning of larger models on limited hardware. + +For comprehensive details on using PEFT with TRL, including various adapter methods, quantization options, and advanced configurations, see [PEFT Integration](peft_integration). + +To use PEFT for reducing memory usage: + +```python +from datasets import load_dataset +from peft import LoraConfig +from trl import SFTTrainer + +dataset = load_dataset("trl-lib/Capybara", split="train") + +peft_config = LoraConfig() + +trainer = SFTTrainer( + model="Qwen/Qwen2.5-0.5B", + train_dataset=dataset, + peft_config=peft_config, +) +``` + +PEFT can be combined with other memory reduction techniques such as quantization (4-bit or 8-bit) for even greater memory savings. See [PEFT Integration](peft_integration) for quantization examples. + +## Liger for reducing peak memory usage + +[Liger Kernel](https://github.com/linkedin/Liger-Kernel) is a collection of Triton kernels designed specifically for LLM training. It can effectively increase multi-GPU training throughput by 20% and reduce memory usage by 60%. + +For more information, see [Liger Kernel Integration](liger_kernel_integration). + +To use Liger for reducing peak memory usage, use the following code snippet: + + + + +```python +from trl import SFTConfig + +training_args = SFTConfig(..., use_liger_kernel=True) +``` + + + + +```python +from trl import DPOConfig + +training_args = DPOConfig(..., use_liger_kernel=True) +``` + + + + +```python +from trl import GRPOConfig + +training_args = GRPOConfig(..., use_liger_kernel=True) +``` + + + + +```python +from trl.experimental.kto import KTOConfig + +training_args = KTOConfig(..., use_liger_kernel=True) +``` + + + + +```python +from trl.experimental.gkd import GKDConfig + +training_args = GKDConfig(..., use_liger_kernel=True) +``` + + + + +## Chunked cross-entropy for reducing peak memory usage + +At large vocabulary sizes, the `[batch × seq_len × vocab]` logits tensor produced by the LM head is one of the dominant activations held in memory across forward and backward. `loss_type="chunked_nll"` in [`SFTTrainer`] avoids materializing it all at once: positions with `labels == -100` are dropped *before* the `lm_head` matmul, and the cross-entropy is computed in chunks of tokens using gradient checkpointing, so peak activation memory scales with `chunk_size × vocab_size` instead of `(batch × seq_len) × vocab_size`. + +Same math as the standard `"nll"` loss — this is a memory optimization, not a new loss. It is the **default** in [`SFTTrainer`]; to opt out, set `loss_type="nll"`: + +```python +from trl import SFTConfig + +training_args = SFTConfig(..., loss_type="nll") # opt out of the default chunked path +``` + +Expect **typically ~30 % less peak VRAM, up to ~50 %** on large-vocab models (measured on `Qwen3-1.7B`, vocab ≈ 151k — ~30 % on single-GPU, up to ~50 % under FSDP2 × 4 GPUs) with wall time typically neutral or slightly faster. See the [PR #5575](https://github.com/huggingface/trl/pull/5575) for the full benchmark across single-GPU, DDP, FSDP2, packing, long-context, and fp32 configurations. + +Not compatible with `use_liger_kernel=True`, PEFT, or VLM. + +## Padding-free + +Padding-free batching is an alternative approach for reducing memory usage. In this method, a batch is first sampled and then flattened into a single sequence, avoiding padding. Unlike packing, which can result in incomplete sequences by combining parts of different samples, padding-free batching ensures that all sequences remain complete and intact. + +![Padding-free](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/padding-free.png) + +> [!WARNING] +> It's highly recommended to use padding-free batching with **FlashAttention 2** or **FlashAttention 3**. Otherwise, you may encounter batch contamination issues. + + + + +```python +from trl import DPOConfig + +training_args = DPOConfig(..., padding_free=True, model_init_kwargs={"attn_implementation": "kernels-community/flash-attn2"}) +``` + + + + +```python +from trl import SFTConfig + +training_args = SFTConfig(..., padding_free=True, model_init_kwargs={"attn_implementation": "kernels-community/flash-attn2"}) +``` + + + + +## Activation offloading + +Activation offloading is a memory efficiency technique that reduces GPU VRAM usage by temporarily moving activation tensors to CPU RAM during the forward pass and bringing them back only when needed for the backward pass. This significantly reduces peak memory usage at the cost of slightly increased training time. + +To enable activation offloading in your SFT training configuration: + +```python +from trl import SFTConfig + +training_args = SFTConfig(..., activation_offloading=True) +``` + +Under the hood, activation offloading implements PyTorch's [`saved_tensors_hooks`](https://pytorch.org/tutorials/intermediate/autograd_saved_tensors_hooks_tutorial.html#hooks-for-autograd-saved-tensors) to intercept activations during the forward pass. It intelligently manages which tensors to offload based on size and context, avoiding offloading output tensors that would be inefficient. For performance optimization, it can, via a flag (which is true by default), use CUDA streams to overlap computation with CPU-GPU transfers. + +## Padding Sequences to a Multiple + +> [!TIP] +> This technique is supported for **SFT** and **Reward** trainers currently. + +When enabled, this option ensures that all sequences are **padded to a multiple** of the specified value. +This can improve computational efficiency on some hardware by aligning sequence lengths to memory-friendly boundaries. + + + + +```python +from trl import SFTConfig + +training_args = SFTConfig(..., pad_to_multiple_of=2048) +``` + + + + +```python +from trl import RewardConfig + +training_args = RewardConfig(..., pad_to_multiple_of=2048) +``` + + + + +## Disabling model gathering for generation in online methods + +When using DeepSpeed ZeRO-3, model weights are sharded across multiple GPUs. Online methods involve generating completions from the model as part of the training process. During this step, the model weights are temporarily gathered on a single GPU for generation. For very large models, this gathering can lead to OOM errors, as described in this issue: [#2250](https://github.com/huggingface/trl/issues/2250#issue-2598304204). + +If you encounter this issue, you can disable the gathering of model weights for generation by setting the following parameter: + + + + +```python +from trl import GRPOConfig + +training_args = GRPOConfig(..., ds3_gather_for_generation=False) +``` + + + + +```python +from trl.experimental.online_dpo import OnlineDPOConfig + +training_args = OnlineDPOConfig(..., ds3_gather_for_generation=False) +``` + + + + +```python +from trl.experimental.ppo import PPOConfig + +training_args = PPOConfig(..., ds3_gather_for_generation=False) +``` + + + + +```python +from trl import RLOOConfig + +training_args = RLOOConfig(..., ds3_gather_for_generation=False) +``` + + + + +This adjustment prevents model weights from being gathered, avoiding OOM errors, but it may result in slower generation speeds. + +## vLLM sleep mode + +When using **vLLM** as the generation backend for online training methods, you can enable _sleep mode_ to offload vLLM parameters and cache to CPU RAM during the optimization step and reload them back to GPU VRAM when needed for weight synchronization and generation. + + + + +```python +from trl import GRPOConfig + +training_args = GRPOConfig(..., vllm_enable_sleep_mode=True) +``` + + + + +```python +from trl import RLOOConfig + +training_args = RLOOConfig(..., vllm_enable_sleep_mode=True) +``` + + + + +Offloading the vLLM weights and cache helps keep GPU memory usage low, which can be particularly beneficial when training large models or using limited GPU resources. However, waking the vLLM engine from sleep mode introduces some host–device transfer latency, which may slightly impact training speed. + +## Gradient checkpointing + +Gradient checkpointing trades compute for memory by not storing all intermediate activations during the forward pass, recomputing them during the backward pass instead. + +```python +from trl import SFTConfig + +training_args = SFTConfig(..., gradient_checkpointing=True) +``` + +> [!NOTE] +> Gradient checkpointing is enabled by default in all trainers to optimize memory usage. You can disable it by setting `gradient_checkpointing=False` if needed. + +For more memory optimization techniques, see the [Transformers Performance Guide](https://huggingface.co/docs/transformers/perf_train_gpu_one#gradient-checkpointing). diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/reward_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/reward_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..d757cef046c5c4419b4dd72fca6150e37286ddd0 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/reward_trainer.md @@ -0,0 +1,234 @@ +# Reward Modeling + +[![model badge](https://img.shields.io/badge/All_models-Reward_Trainer-blue)](https://huggingface.co/models?other=reward-trainer,trl) + +## Overview + +TRL supports the Outcome-supervised Reward Modeling (ORM) Trainer for training reward models. + +This post-training method was contributed by [Younes Belkada](https://huggingface.co/ybelkada). + +## Quick start + +This example demonstrates how to train a reward model using the [`RewardTrainer`] from TRL. We train a [Qwen 3 0.6B](https://huggingface.co/Qwen/Qwen3-0.6B) model on the [UltraFeedback dataset](https://huggingface.co/datasets/trl-lib/ultrafeedback_binarized), large-scale, fine-grained, diverse preference dataset. + +```python +from trl import RewardTrainer +from datasets import load_dataset + +trainer = RewardTrainer( + model="Qwen/Qwen3-0.6B", + train_dataset=load_dataset("trl-lib/ultrafeedback_binarized", split="train"), +) +trainer.train() +``` + + + +## Expected dataset type and format + +[`RewardTrainer`] supports [preference](dataset_formats#preference) datasets type (both implicit and explicit prompt). The [`RewardTrainer`] is compatible with both [standard](dataset_formats#standard) and [conversational](dataset_formats#conversational) dataset formats. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset. + +```python +# Standard preference (implicit prompt) +{"chosen": "The sky is blue.", + "rejected": "The sky is green."} + +# Conversational preference (implicit prompt) +{"chosen": [{"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}], + "rejected": [{"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is green."}]} + +# Standard preference (explicit prompt) +{"prompt": "The sky is", + "chosen": " blue.", + "rejected": " green."} + +# Conversational preference (explicit prompt) +{"prompt": [{"role": "user", "content": "What color is the sky?"}], + "chosen": [{"role": "assistant", "content": "It is blue."}], + "rejected": [{"role": "assistant", "content": "It is green."}]} +``` + +If your dataset is not in one of these formats, you can preprocess it to convert it into the expected format. Here is an example with the [lmarena-ai/arena-human-preference-55k](https://huggingface.co/datasets/lmarena-ai/arena-human-preference-55k) dataset: + +```python +from datasets import load_dataset +import json + +dataset = load_dataset("lmarena-ai/arena-human-preference-55k") + +# Filter out ties +dataset = dataset.filter(lambda example: example["winner_tie"] == 0) + +# Create 'chosen' and 'rejected' fields based on the winner column +def response_a_b_to_chosen_rejected(example): + if example["winner_model_a"] == 1: + example["chosen"] = example["response_a"] + example["rejected"] = example["response_b"] + else: + example["chosen"] = example["response_b"] + example["rejected"] = example["response_a"] + return example + +dataset = dataset.map(response_a_b_to_chosen_rejected) + +# Convert to conversational format +def make_conversation(example): + prompt = json.loads(example["prompt"])[0] # '["What color is the sky?"]' -> "What color is the sky?" + chosen = json.loads(example["chosen"])[0] + rejected = json.loads(example["rejected"])[0] + return { + "chosen": [{"role": "user", "content": prompt}, {"role": "assistant", "content": chosen}], + "rejected": [{"role": "user", "content": prompt}, {"role": "assistant", "content": rejected}], + } + + +dataset = dataset.map(make_conversation) + +# Keep only necessary columns +dataset = dataset.select_columns(["chosen", "rejected"]) + +print(next(iter(dataset["train"]))) +``` + +```json +{ + "chosen": [ + {"role": "user", "content": "Is it morally right to try to have a certain percentage of females on managerial positions?"}, + {"role": "assistant", "content": "The question of whether it is morally right to aim for a certain percentage of females..."}, + ], + "rejected": [ + {"role": "user", "content": "Is it morally right to try to have a certain percentage of females on managerial positions?"}, + {"role": "assistant", "content": "As an AI, I don't have personal beliefs or opinions. However, ..."}, + ], +} +``` + +## Looking deeper into the training method + +Reward Models (RMs) are typically trained using supervised learning on datasets containing pairs of preferred and non-preferred responses. The goal is to learn a function that assigns higher scores to preferred responses, enabling the model to rank outputs based on preferences. + +This section breaks down how reward modeling works in practice, covering the key steps: **preprocessing** and **loss computation**. + +### Preprocessing and tokenization + +During training, each example is expected to contain a **chosen** and **rejected** field. For more details on the expected formats, see [Dataset formats - Preference](dataset_formats#preference). +The [`RewardTrainer`] tokenizes each input using the model's tokenizer. If prompts and completions (chosen and rejected) are provided separately (explicit prompt case), they are concatenated before tokenization. + +### Computing the loss + +Let \\( x \\) be the input sequence (prompt) and \\( y^+ \\) and \\( y^- \\) be the chosen and rejected sequences respectively. Under the Bradley-Terry model ([Bradley & Terry, 1952](https://www.jstor.org/stable/2334029)), the probability that \\( y^+ \\) is preferred over \\( y^- \\) given a reward function \\( r \\) is \\( p(y^+ ≻ y^- |x) = \sigma(r(x, y^+)−r(x, y^-)) \\), where \\( σ \\) is the sigmoid function. + +The reward model \\( r_\theta(x, y) \\) is trained to assign higher scores to preferred responses \\( y^+ \\) over non-preferred ones \\( y^- \\). The loss is then defined as the negative log-likelihood of the observed preferences: + +$$ +\mathcal{L}(\theta) = - \mathbb{E}_{(x,y^+,y^-) \sim \mathcal{D}} \left[ \log \sigma(r_\theta(x, y^+) - r_\theta(x, y^-)) \right]. +$$ + +> [!TIP] +> The Bradley-Terry model is underdetermined, meaning that adding a constant to all rewards does not change the preference probabilities. To address this, [Helping or Herding? Reward Model Ensembles Mitigate but do not Eliminate Reward Hacking](https://huggingface.co/papers/2312.09244) proposes adding an auxiliary loss term that encourages the rewards to be centered around zero. This is controlled by the `center_rewards_coefficient` parameter in the [`RewardConfig`]. The recommended value is `1e-2`. + +## Logged metrics + +While training and evaluating we record the following reward metrics: + +* `global_step`: The total number of optimizer steps taken so far. +* `epoch`: The current epoch number, based on dataset iteration. +* `num_tokens`: The total number of tokens processed so far. +* `loss`: The average loss over the last logging interval. +* `accuracy`: The proportion of correct predictions (i.e., the model assigned a higher score to the chosen response than to the rejected one) averaged over the last logging interval. +* `min_reward`: The minimum reward score assigned by the model. This value is averaged over the logging interval. +* `mean_reward`: The average reward score assigned by the model over the last logging interval. +* `max_reward`: The maximum reward score assigned by the model. This value is averaged over the logging interval. +* `margin`: The average margin (difference between chosen and rejected rewards) over the last logging interval. +* `learning_rate`: The current learning rate, which may change dynamically if a scheduler is used. +* `grad_norm`: The L2 norm of the gradients, computed before gradient clipping. + +## Customization + +### Model initialization + +You can directly pass the kwargs of the [`~transformers.AutoModelForSequenceClassification.from_pretrained()`] method to the [`RewardConfig`]. For example, if you want to load a model in a different precision, analogous to + +```python +model = AutoModelForSequenceClassification.from_pretrained("Qwen/Qwen3-0.6B", dtype=torch.bfloat16) +``` + +you can do so by passing the `model_init_kwargs={"dtype": torch.bfloat16}` argument to the [`RewardConfig`]. + +```python +from trl import RewardConfig + +training_args = RewardConfig( + model_init_kwargs={"dtype": torch.bfloat16}, +) +``` + +Note that all keyword arguments of [`~transformers.AutoModelForSequenceClassification.from_pretrained()`] are supported, except for `num_labels`, which is automatically set to 1. + +### Train adapters with PEFT + +We support tight integration with 🤗 PEFT library, allowing any user to conveniently train adapters and share them on the Hub, rather than training the entire model. + +```python +from datasets import load_dataset +from trl import RewardTrainer +from peft import LoraConfig + +dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") + +trainer = RewardTrainer( + "Qwen/Qwen3-4B", + train_dataset=dataset, + peft_config=LoraConfig(modules_to_save=["score"]) # important to include the score head when base model is not a sequence classification model +) + +trainer.train() +``` + +You can also continue training your [`~peft.PeftModel`]. For that, first load a `PeftModel` outside [`RewardTrainer`] and pass it directly to the trainer without the `peft_config` argument being passed. + +```python +from datasets import load_dataset +from trl import RewardTrainer +from peft import AutoPeftModelForCausalLM + +model = AutoPeftModelForCausalLM.from_pretrained("trl-lib/Qwen3-4B-Reward-LoRA", is_trainable=True) +dataset = load_dataset("trl-lib/Capybara", split="train") + +trainer = RewardTrainer( + model=model, + train_dataset=dataset, +) + +trainer.train() +``` + +> [!TIP] +> When training adapters, you typically use a higher learning rate (≈1e‑3) since only new parameters are being learned. +> +> ```python +> RewardConfig(learning_rate=1e-3, ...) +> ``` + +## Tool Calling with Reward Modeling + +The [`RewardTrainer`] fully supports fine-tuning models with _tool calling_ capabilities. In this case, each dataset example should include: + +* The conversation messages, including any tool calls (`tool_calls`) and tool responses (`tool` role messages) +* The list of available tools in the `tools` column, typically provided as JSON schemas + +For details on the expected dataset structure, see the [Dataset Format — Tool Calling](dataset_formats#tool-calling) section. + +## RewardTrainer + +[[autodoc]] RewardTrainer + - train + - save_model + - push_to_hub + +## RewardConfig + +[[autodoc]] RewardConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/rewards.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/rewards.md new file mode 100644 index 0000000000000000000000000000000000000000..0a3e74f09f7a441d697b747e876f63a8181629c6 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/rewards.md @@ -0,0 +1,27 @@ +# Reward Functions + +This module contains some useful reward functions, primarily intended for use with the [`GRPOTrainer`] and [`RLOOTrainer`]. + +## accuracy_reward + +[[autodoc]] rewards.accuracy_reward + +## reasoning_accuracy_reward + +[[autodoc]] rewards.reasoning_accuracy_reward + +## get_cosine_scaled_reward + +[[autodoc]] rewards.get_cosine_scaled_reward + +## think_format_reward + +[[autodoc]] rewards.think_format_reward + +## get_repetition_penalty_reward + +[[autodoc]] rewards.get_repetition_penalty_reward + +## get_soft_overlong_punishment + +[[autodoc]] rewards.get_soft_overlong_punishment diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/rloo_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/rloo_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..39c992449d444fb2017211f2d646335a18d2239f --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/rloo_trainer.md @@ -0,0 +1,645 @@ +# RLOO Trainer + +[![model badge](https://img.shields.io/badge/All_models-RLOO-blue)](https://huggingface.co/models?other=rloo,trl) + +## Overview + +TRL supports the RLOO Trainer for training language models, as described in the paper [Back to Basics: Revisiting REINFORCE Style +Optimization for Learning from Human Feedback in LLMs](https://huggingface.co/papers/2402.14740) by [Arash Ahmadian](https://huggingface.co/ArashAhmadian), Chris Cremer, [Matthias Gallé](https://huggingface.co/mgalle), [Marzieh Fadaee](https://huggingface.co/MarziehFadaee), [Julia Kreutzer](https://huggingface.co/JuliaKreutzerCohere), [Ahmet Üstün](https://huggingface.co/ahmetu) and [Sara Hooker](https://huggingface.co/sarahooker). + +The abstract from the paper is the following: + +> AI alignment in the shape of Reinforcement Learning from Human Feedback (RLHF) is increasingly treated as a crucial ingredient for high performance large language models. Proximal Policy Optimization (PPO) has been positioned by recent literature as the canonical method for the RL part of RLHF However, it involves both high computational cost and sensitive hyperparameter tuning. We posit that most of the motivational principles that led to the development of PPO are less of a practical concern in RLHF and advocate for a less computationally expensive method that preserves and even increases performance. We revisit the formulation of alignment from human preferences in the context of RL. Keeping simplicity as a guiding principle, we show that many components of PPO are unnecessary in an RLHF context and that far simpler REINFORCE-style optimization variants outperform both PPO and newly proposed “RL-free” methods such as DPO and RAFT. Our work suggests that careful adaptation to LLMs alignment characteristics enables benefiting from online RL optimization at low cost. + +This post-training method was contributed by [Costa Huang](https://github.com/vwxyzjn) and later refactored by [Shirin Yamani](https://huggingface.co/ShirinYamani). + +## Quick start + +This example demonstrates how to train a model using the RLOO method. We train a [Qwen 0.5B Instruct model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) with the prompts from the [DeepMath-103K dataset](https://huggingface.co/datasets/trl-lib/DeepMath-103K). You can view the data in the dataset here: + + + +Below is the script to train the model. + +```python +# train_rloo.py +from datasets import load_dataset +from trl import RLOOTrainer +from trl.rewards import accuracy_reward + +dataset = load_dataset("trl-lib/DeepMath-103K", split="train") + +trainer = RLOOTrainer( + model="Qwen/Qwen2-0.5B-Instruct", + reward_funcs=accuracy_reward, + train_dataset=dataset, +) +trainer.train() +``` + +Execute the script using the following command: + +```bash +accelerate launch train_rloo.py +``` + +## Looking deeper into the RLOO method + +RLOO is an online learning algorithm, meaning it improves iteratively by using the data generated by the trained model itself during training. The intuition behind RLOO objective is to maximize the advantage of the generated completions, while ensuring that the model remains close to the reference policy. To understand how RLOO works, it can be broken down into four main steps: **Generating completions**, **computing the advantage**, **estimating the KL divergence**, and **computing the loss**. + +![RLOO](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/rloo.png) + +### Generating completions + +At each training step, we sample a batch of prompts and generate a set of \\( G \\) completions for each prompt (denoted as \\( o_i \\)). + +### Computing the reward + +In RLOO, the reward consists of two components: the reward provided by the reward model (or reward function) and a KL penalty that discourages the policy from deviating too far from a fixed reference policy + +1. For each of the \\( G \\) generated sequences \\( o_i = (o_{i,1}, \dots, o_{i,T}) \\) conditioned on a query \\( q \\), we compute a scalar reward using a reward model \\( R(o_i, q) \\). +2. Concurrently, we estimate the KL divergence between the current policy \\( \pi_\theta \\) and the fixed reference policy \\( \pi_{\text{ref}} \\) over the sequence. The KL estimate for sequence \\( o_i \\) is: + +$$ +\mathbb{D}_{\mathrm{KL}}\!\left[\pi_\theta\|\pi_{\mathrm{ref}}\right] = \sum_{t=1}^T \log \frac{\pi_\theta(o_{i,t} \mid q, o_{i, 0 \\) controls the strength of the KL penalty. + +> [!TIP] +> In a purely online setting (`num_iterations = 1`, default), the data are generated by the current policy. In this case, the KL penalty is computed directly using the current policy. +> +> In the more general setting (e.g., multiple gradient steps per batch), the data are instead generated by an earlier snapshot \\( \pi_{\text{old}} \\). To keep the penalty consistent with the sampling distribution, the KL is defined with respect to this policy: +> +> \\( \mathbb{D}_{\mathrm{KL}}\!\left[\pi_{\text{old}} \,\|\, \pi_{\text{ref}}\right]. \\) +> +> Equivalently, for a sampled sequence \\( o \\), the Monte Carlo estimate is: +> +> \\( \mathbb{D}_{\mathrm{KL}}\!\left[\pi_{\text{old}} \|\pi_{\mathrm{ref}}\right] = \sum_{t=1}^T \log \frac{\pi_{\text{old}}(o_{i,t} \mid q, o_{i, [!NOTE] +> Unlike GRPO, RLOO does not backpropagate gradients through the KL term. Here the KL is purely used for reward shaping: it is computed under `no_grad` and folded into the scalar reward \\( r_i \\), which becomes the detached advantage \\( \hat{A}_i \\). +> +> In other words, the only path the gradient takes into the policy is the importance-ratio term \\( \frac{\pi_\theta(o_i \mid q)}{\pi_{\theta_\text{old}}(o_i \mid q)} \\), and the KL term does not backpropagate into the policy. +> +> In contrast, [GRPO](grpo_trainer) adds an explicit, differentiable KL term to its objective, computed on the fly with the current policy \\( \pi_\theta \\), so its gradient flows through both the ratio term and the KL penalty. + +## Logged metrics + +While training and evaluating, we record the following reward metrics: + +- `num_tokens`: The total number of tokens processed so far, including both prompts and completions. +- `step_time`: The average time (in seconds) taken per training step (including generation). +- `completions/mean_length`: The average length of generated completions. +- `completions/min_length`: The minimum length of generated completions. +- `completions/max_length`: The maximum length of generated completions. +- `completions/mean_terminated_length`: The average length of generated completions that terminate with EOS. +- `completions/min_terminated_length`: The minimum length of generated completions that terminate with EOS. +- `completions/max_terminated_length`: The maximum length of generated completions that terminate with EOS. +- `completions/clipped_ratio`: The ratio of truncated (clipped) completions. +- `reward/{reward_func_name}/mean`: The average reward from a specific reward function. +- `reward/{reward_func_name}/std`: The standard deviation of the reward from a specific reward function. +- `reward`: The overall average reward after summing rewards across functions (weighted by `reward_weights`). +- `reward_std`: The standard deviation of summed rewards across functions (weighted by `reward_weights`), computed over the full batch. +- `frac_reward_zero_std`: The fraction of samples in the generation batch with a reward std of zero, implying there is little diversity for that prompt (all answers are correct or incorrect). +- `entropy`: Average entropy of token predictions across generated completions. (If `mask_truncated_completions=True`, masked sequences tokens are excluded.) +- `kl`: The average KL divergence between the model and the reference model, calculated over generated completions. Logged only if `beta` is nonzero. +- `clip_ratio/region_mean`: The ratio of sequence probabilities where the RLOO objective is clipped to stay within the trust region: \\( \text{clip}\left( r_{i}(\theta), 1 - \epsilon_\mathrm{low}, 1 + \epsilon_\mathrm{high} \right)\,, \quad r_{i}(\theta) = \frac{\pi_\theta(o_{i} \mid q)}{\pi_{\theta_{\text{old}}}(o_{i} \mid q)} \\). A higher value means more samples are clipped, which constrains how much the policy $\pi_\theta$ can change. +- `clip_ratio/low_mean`: The average ratio of sequence probabilities that were clipped on the lower bound of the trust region: \\(r_{i,t}(\theta) < 1 - \epsilon_\mathrm{low}\\). +- `clip_ratio/low_min`: The minimum ratio of sequence probabilities that were clipped on the lower bound of the trust region: \\(r_{i,t}(\theta) < 1 - \epsilon_\mathrm{low}\\). +- `clip_ratio/high_mean`: The average ratio of sequence probabilities that were clipped on the upper bound of the trust region: \\(r_{i,t}(\theta) > 1 + \epsilon_\mathrm{high}\\). +- `clip_ratio/high_max`: The maximum ratio of sequence probabilities that were clipped on the upper bound of the trust region: \\(r_{i,t}(\theta) > 1 + \epsilon_\mathrm{high}\\). + +## Customization + +### Speed up training with vLLM-powered generation + +Generation is often the main bottleneck when training with online methods. To accelerate generation, you can use [vLLM](https://github.com/vllm-project/vllm), a high-throughput, low-latency inference engine for LLMs. To enable it, first install the package with + +```shell +pip install trl[vllm] +``` + +We support two ways of using vLLM during training: **server mode** and **colocate mode**. + +#### Option 1: Colocate mode + +In this mode, vLLM runs inside the trainer process and shares GPU memory with the training model. This avoids launching a separate server and can improve GPU utilization, but may lead to memory contention on the training GPUs. This is the default mode. + +```python +from trl import RLOOConfig + +training_args = RLOOConfig( + ..., + use_vllm=True, # vllm_mode="colocate" by default +) +``` + +#### Option 2: Server mode + +In this mode, vLLM runs in a separate process (and using separate GPUs) and communicates with the trainer via HTTP. This is ideal if you have dedicated GPUs for inference. + +1. **Start the vLLM server**: + + ```bash + trl vllm-serve --model + ``` + +2. **Enable server mode in your training script**: + + ```python + from trl import RLOOConfig + + training_args = RLOOConfig( + ..., + use_vllm=True, + vllm_mode="server", + ) + ``` + +> [!WARNING] +> Make sure that the server is using different GPUs than the trainer, otherwise you may run into NCCL errors. You can specify the GPUs to use with the `CUDA_VISIBLE_DEVICES` environment variable. + +> [!TIP] +> Depending on the model size and the overall GPU memory requirements for training, you may need to adjust the `vllm_gpu_memory_utilization` parameter in [`RLOOConfig`] to avoid underutilization or out-of-memory errors. +> +> We provide a [HF Space](https://huggingface.co/spaces/trl-lib/recommend-vllm-memory) to help estimate the recommended GPU memory utilization based on your model configuration and experiment settings. Simply use it as follows to get `vllm_gpu_memory_utilization` recommendation: +> +> +> +> If the recommended value does not work in your environment, we suggest adding a small buffer (e.g., +0.05 or +0.1) to the recommended value to ensure stability. +> +> If you still find you are getting out-of-memory errors set `vllm_enable_sleep_mode` to True and the vllm parameters and cache will be offloaded during the optimization step. For more information, see [Reducing Memory Usage with vLLM Sleep Mode](reducing_memory_usage#vllm-sleep-mode). + +> [!TIP] +> By default, RLOO uses `MASTER_ADDR=localhost` and `MASTER_PORT=12345` for vLLM, but you can override these values by setting the environment variables accordingly. + +For more information, see [Speeding up training with vLLM](speeding_up_training#vllm-for-fast-generation-in-online-methods). + +### RLOO at scale: train a 70B+ Model on multiple nodes + +When training large models like **Qwen2.5-72B**, you need several key optimizations to make the training efficient and scalable across multiple GPUs and nodes. These include: + +- **DeepSpeed ZeRO Stage 3**: ZeRO leverages data parallelism to distribute model states (weights, gradients, optimizer states) across multiple GPUs and CPUs, reducing memory and compute requirements on each device. Since large models cannot fit on a single GPU, using ZeRO Stage 3 is required for training such models. For more details, see [DeepSpeed Integration](deepspeed_integration). +- **Accelerate**: Accelerate is a library that simplifies distributed training across multiple GPUs and nodes. It provides a simple API to launch distributed training and handles the complexities of distributed training, such as data parallelism, gradient accumulation, and distributed data loading. For more details, see [Distributing Training](distributing_training). +- **vLLM**: See the previous section on how to use vLLM to speed up generation. + +Below is an example SLURM script to train a 70B model with RLOO on multiple nodes. This script trains a model on 4 nodes and uses the 5th node for vLLM-powered generation. + +```sh +#!/bin/bash +#SBATCH --nodes=5 +#SBATCH --gres=gpu:8 + +# Get the list of allocated nodes +NODELIST=($(scontrol show hostnames $SLURM_JOB_NODELIST)) + +# Assign the first 4 nodes for training and the 5th node for vLLM +TRAIN_NODES="${NODELIST[@]:0:4}" # Nodes 0, 1, 2, 3 for training +VLLM_NODE="${NODELIST[4]}" # Node 4 for vLLM + +# Run training on the first 4 nodes (Group 1) +srun --nodes=4 --ntasks=4 --nodelist="${NODELIST[@]:0:4}" accelerate launch \ + --config_file examples/accelerate_configs/deepspeed_zero3.yaml \ + --num_processes 32 \ + --num_machines 4 \ + --main_process_ip ${NODELIST[0]} \ + --machine_rank $SLURM_PROCID \ + --rdzv_backend c10d \ + train_rloo.py \ + --server_ip $VLLM_NODE & + +# Run vLLM server on the 5th node (Group 2) +srun --nodes=1 --ntasks=1 --nodelist="${NODELIST[4]}" trl vllm-serve --model Qwen/Qwen2.5-72B --tensor_parallel_size 8 & + +wait +``` + +```python +import argparse + +from datasets import load_dataset +from trl import RLOOTrainer, RLOOConfig + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--vllm_server_host", type=str, default="", help="The server IP") + args = parser.parse_args() + + # Example dataset from TLDR + dataset = load_dataset("trl-lib/tldr", split="train") + + # Dummy reward function: count the number of unique characters in the completions + def reward_num_unique_chars(completions, **kwargs): + return [len(set(c)) for c in completions] + + training_args = RLOOConfig( + output_dir="Qwen2.5-72B-RLOO", + per_device_train_batch_size=4, + bf16=True, + use_vllm=True, + vllm_mode="server", + vllm_server_host=args.vllm_server_host.replace("ip-", "").replace("-", "."), # from ip-X-X-X-X to X.X.X.X + ) + + trainer = RLOOTrainer(model="Qwen/Qwen2.5-72B", args=training_args, reward_funcs=reward_num_unique_chars, train_dataset=dataset) + trainer.train() + +if __name__=="__main__": + main() +``` + +### Using a custom reward function + +The [`RLOOTrainer`] supports using custom reward functions instead of dense reward models. To ensure compatibility, your reward function must satisfy the following requirements: + +Reward functions can be either synchronous Python callables or asynchronous `async def` coroutines. When you provide multiple asynchronous reward functions, they are awaited concurrently (run in parallel via `asyncio.gather`) so their latency overlaps. + +1. **Input arguments**: + - The function must accept the following as keyword arguments: + - `prompts` (contains the prompts), + - `completions` (contains the generated completions), + - `completion_ids` (contains the tokenized completions), + - `trainer_state` ([`~transformers.TrainerState`]): The current state of the trainer. This can be used to implement dynamic reward functions, such as curriculum learning, where the reward is adjusted based on the training progress. + - `log_extra`: a callable `log_extra(column: str, values: list)` to add extra columns to the completions table. See Example 6. In distributed training, it's important that all processes log the same set of keys. + - `log_metric`: a callable `log_metric(name: str, value: float)` to log scalar metrics as plots alongside `kl`, `entropy`, etc. See Example 6. In distributed training, it's important that all processes log the same set of keys. + - All column names (but `prompt`) that the dataset may have. For example, if the dataset contains a column named `ground_truth`, the function will be called with `ground_truth` as a keyword argument. + + The easiest way to comply with this requirement is to use `**kwargs` in the function signature. + - Depending on the dataset format, the input will vary: + - For [standard format](dataset_formats#standard), `prompts` and `completions` will be lists of strings. + - For [conversational format](dataset_formats#conversational), `prompts` and `completions` will be lists of message dictionaries. + +2. **Return value**: The function must return a list of floats. Each float represents the reward corresponding to a single completion. + +#### Example 1: Reward longer completions + +Below is an example of a reward function for a standard format that rewards longer completions: + +```python +def reward_func(completion_ids, **kwargs): + """Reward function that assigns higher scores to longer completions (in terms of token count).""" + return [float(len(ids)) for ids in completion_ids] +``` + +You can test it as follows: + +```python +>>> prompts = ["The sky is", "The sun is"] # not used in the reward function, but the trainer will pass it +>>> completions = [" blue.", " in the sky."] # not used in the reward function, but the trainer will pass it +>>> completion_ids = [[6303, 13], [304, 279, 12884, 13]] +>>> reward_func(prompts=prompts, completions=completions, completion_ids=completion_ids) +[2.0, 4.0] +``` + +#### Example 1.1: Reward longer completions (based on the number of characters) + +Same as the previous example, but this time the reward function is based on the number of characters instead of tokens. + +```python +def reward_func(completions, **kwargs): + """Reward function that assigns higher scores to longer completions (in terms of character count).""" + return [float(len(completion)) for completion in completions] +``` + +You can test it as follows: + +```python +>>> prompts = ["The sky is", "The sun is"] +>>> completions = [" blue.", " in the sky."] +>>> completion_ids = [[6303, 13], [304, 279, 12884, 13]] # not used in the reward function, but the trainer will pass it +>>> reward_func(prompts=prompts, completions=completions, completion_ids=completion_ids) +[6.0, 12.0] +``` + +#### Example 2: Reward completions with a specific format + +Below is an example of a reward function that checks if the completion has a specific format. This example is inspired by the _format reward_ function used in the paper [DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning](https://huggingface.co/papers/2501.12948). +It is designed for a conversational format, where prompts and completions consist of structured messages. + +```python +import re + +def format_reward_func(completions, **kwargs): + """Reward function that checks if the completion has a specific format.""" + pattern = r"^.*?.*?$" + completion_contents = [completion[0]["content"] for completion in completions] + matches = [re.match(pattern, content) for content in completion_contents] + return [1.0 if match else 0.0 for match in matches] +``` + +You can test this function as follows: + +```python +>>> prompts = [ +... [{"role": "assistant", "content": "What is the result of (1 + 2) * 4?"}], +... [{"role": "assistant", "content": "What is the result of (3 + 1) * 2?"}], +... ] +>>> completions = [ +... [{"role": "assistant", "content": "The sum of 1 and 2 is 3, which we multiply by 4 to get 12.(1 + 2) * 4 = 12"}], +... [{"role": "assistant", "content": "The sum of 3 and 1 is 4, which we multiply by 2 to get 8. So (3 + 1) * 2 = 8."}], +... ] +>>> format_reward_func(prompts=prompts, completions=completions) +[1.0, 0.0] +``` + +#### Example 3: Reward completions based on a reference + +Below is an example of a reward function that checks if the completion is correct. This example is inspired by the _accuracy reward_ function used in the paper [DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning](https://huggingface.co/papers/2501.12948). +This example is designed for [standard format](dataset_formats#standard), where the dataset contains a column named `ground_truth`. + +```python +import re + +def reward_func(completions, ground_truth, **kwargs): + # Regular expression to capture content inside \boxed{} + matches = [re.search(r"\\boxed\{(.*?)\}", completion) for completion in completions] + contents = [match.group(1) if match else "" for match in matches] + # Reward 1 if the content is the same as the ground truth, 0 otherwise + return [1.0 if c == gt else 0.0 for c, gt in zip(contents, ground_truth)] +``` + +You can test this function as follows: + +```python +>>> prompts = ["Problem: Solve the equation $2x + 3 = 7$. Solution:", "Problem: Solve the equation $3x - 5 = 10$."] +>>> completions = [r" The solution is \boxed{2}.", r" The solution is \boxed{6}."] +>>> ground_truth = ["2", "5"] +>>> reward_func(prompts=prompts, completions=completions, ground_truth=ground_truth) +[1.0, 0.0] +``` + +#### Example 4: Multi-task reward functions + +Below is an example of using multiple reward functions in the [`RLOOTrainer`]. In this example, we define two task-specific reward functions: `math_reward_func` and `coding_reward_func`. The `math_reward_func` rewards math problems based on their correctness, while the `coding_reward_func` rewards coding problems based on whether the solution works. + +```python +from datasets import Dataset +from trl import RLOOTrainer + +# Define a dataset that contains both math and coding problems +dataset = Dataset.from_list( + [ + {"prompt": "What is 2+2?", "task": "math"}, + {"prompt": "Write a function that returns the sum of two numbers.", "task": "code"}, + {"prompt": "What is 3*4?", "task": "math"}, + {"prompt": "Write a function that returns the product of two numbers.", "task": "code"}, + ] +) + +# Math-specific reward function +def math_reward_func(prompts, completions, task, **kwargs): + rewards = [] + for prompt, completion, t in zip(prompts, completions, task): + if t == "math": + # Calculate math-specific reward + correct = check_math_solution(prompt, completion) + reward = 1.0 if correct else -1.0 + rewards.append(reward) + else: + # Return None for non-math tasks + rewards.append(None) + return rewards + +# Coding-specific reward function +def coding_reward_func(prompts, completions, task, **kwargs): + rewards = [] + for prompt, completion, t in zip(prompts, completions, task): + if t == "coding": + # Calculate coding-specific reward + works = test_code_solution(prompt, completion) + reward = 1.0 if works else -1.0 + rewards.append(reward) + else: + # Return None for non-coding tasks + rewards.append(None) + return rewards + +# Use both task-specific reward functions +trainer = RLOOTrainer( + model="Qwen/Qwen2-0.5B-Instruct", + reward_funcs=[math_reward_func, coding_reward_func], + train_dataset=dataset, +) + +trainer.train() +``` + +In this example, the `math_reward_func` and `coding_reward_func` are designed to work with a mixed dataset that contains both math and coding problems. The `task` column in the dataset is used to determine which reward function to apply to each problem. If there is no relevant reward function for a sample in the dataset, the reward function will return `None`, and the [`RLOOTrainer`] will continue with the valid functions and tasks. This allows the [`RLOOTrainer`] to handle multiple reward functions with different applicability. + +Note that the [`RLOOTrainer`] will ignore the `None` rewards returned by the reward functions and only consider the rewards returned by the relevant functions. This ensures that the model is trained on the relevant tasks and ignores the tasks for which there is no relevant reward function. + +#### Example 5: Asynchronous reward functions + +Custom reward functions can also be defined as `async def` coroutines. This is useful if your reward depends on slow I/O (for example, calling a remote service). When you pass multiple async reward functions, [`RLOOTrainer`] executes them concurrently so their latency overlaps. + +Below is a minimal example of an async reward function that simulates an I/O-bound operation: + +```python +import asyncio + +async def async_reward_func(prompts, completions, **kwargs): + # Simulate an I/O-bound call (e.g., HTTP request, database lookup) + await asyncio.sleep(0.01) + # Simple toy reward: 1.0 if the completion is non-empty, else 0.0 + return [1.0 if completion else 0.0 for completion in completions] +``` + +#### Example 6: Logging extra columns and metrics + +Below is an example of a reward function that logs extra columns to the completions table and scalar metrics as plots. + +```python +import re + +def reward_func(completions, ground_truth, log_extra=None, log_metric=None, **kwargs): + extracted = [re.search(r"\\boxed\{(.*?)\}", c) for c in completions] + extracted = [m.group(1) if m else None for m in extracted] + rewards = [1.0 if e == gt else 0.0 for e, gt in zip(extracted, ground_truth)] + + if log_extra: + log_extra("golden_answer", list(ground_truth)) + log_extra("extracted_answer", [e or "[none]" for e in extracted]) + + if log_metric: + log_metric("accuracy", sum(rewards) / len(rewards)) + + return rewards +``` + +#### Passing the reward function to the trainer + +To use your custom reward function, pass it to the [`RLOOTrainer`] as follows: + +```python +from trl import RLOOTrainer + +trainer = RLOOTrainer( + reward_funcs=reward_func, + ..., +) +``` + +You can pass several reward functions as a list; this list may include both synchronous and asynchronous functions: + +```python +from trl import RLOOTrainer + +trainer = RLOOTrainer( + reward_funcs=[reward_func, async_reward_func1, async_reward_func2], + ..., +) +``` + +and the reward will be computed as the sum of the rewards from each function, or the weighted sum if `reward_weights` is provided in the config. + +Note that [`RLOOTrainer`] supports multiple reward functions of different types. See the parameters documentation for more details. + +## Vision-Language Model (VLM) Training + +RLOO supports training Vision-Language Models (VLMs) on multimodal datasets containing both text and images. + +### Supported Models + +Tested with: + +- **Gemma3** — e.g., `google/gemma-3-4b-it` +- **LLaVA-NeXT** — e.g., `llava-hf/llava-v1.6-mistral-7b-hf` +- **Qwen2-VL** — e.g., `Qwen/Qwen2-VL-2B-Instruct` +- **Qwen2.5-VL** — e.g., `Qwen/Qwen2.5-VL-3B-Instruct` +- **SmolVLM2** — e.g., `HuggingFaceTB/SmolVLM2-2.2B-Instruct` + +> [!TIP] +> Compatibility with all VLMs is not guaranteed. If you believe a model should be supported, feel free to open an issue on GitHub — or better yet, submit a pull request with the required changes. + +### Quick Start + +Use [rloo\_vlm.py](https://github.com/huggingface/trl/blob/main/examples/scripts/rloo_vlm.py) to fine-tune a VLM. Example command for training on [`lmms-lab/multimodal-open-r1-8k-verified`](https://huggingface.co/datasets/lmms-lab/multimodal-open-r1-8k-verified): + +```bash +accelerate launch \ + --config_file=examples/accelerate_configs/deepspeed_zero3.yaml \ + examples/scripts/rloo_vlm.py \ + --model_name_or_path Qwen/Qwen2.5-VL-3B-Instruct \ + --output_dir rloo-Qwen2.5-VL-3B-Instruct \ + --learning_rate 1e-5 \ + --dtype bfloat16 \ + --max_completion_length 1024 \ + --use_vllm \ + --vllm_mode colocate \ + --use_peft \ + --lora_target_modules "q_proj", "v_proj" \ + --log_completions +``` + +### Configuration Tips + +- Use LoRA on vision-language projection layers +- Enable 4-bit quantization to reduce memory usage +- VLMs are memory-intensive — start with smaller batch sizes +- Most models are compatible with vLLM (`server` and `colocate` modes) + +### Dataset Format + +Each training sample should include: + +- `prompt`: Text formatted via the processor's chat template +- `image`/`images`: PIL Image or list of PIL Images + +The trainer automatically handles image-to-tensor conversion via the model’s image processor. + +## RLOOTrainer + +[[autodoc]] RLOOTrainer + - train + - save_model + - push_to_hub + +## RLOOConfig + +[[autodoc]] RLOOConfig + +## References + +1. [RLOO Paper](https://openreview.net/pdf?id=r1lgTGL5DE) +2. [Paper Back to Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in LLMs](https://huggingface.co/papers/2402.14740) +3. [Paper - REINFORCE++: A Simple and Efficient Approach for Aligning Large Language Models](https://huggingface.co/papers/2501.03262) +4. [Blog Post - Putting RL back in RLHF](https://huggingface.co/blog/putting_rl_back_in_rlhf_with_rloo) +5. [Blog Post - Unraveling RLHF and Its Variants: Progress and Practical Engineering Insights](https://hijkzzz.notion.site/unraveling-rlhf-and-its-variants-engineering-insights#147d9a33ecc9806090f3d5c749d31f05) +6. [Youtube - RLOO: A Cost-Efficient Optimization for Learning from Human Feedback in LLMs](https://www.youtube.com/watch?v=86asXGPK6RU&ab_channel=BuzzRobot) + +## Migration Guide from the old implementation (0.21 and below) + +With the release of version 0.22.0, we have revamped the [`RLOOTrainer`] to be more aligned with other online trainers in the library, like [`GRPOTrainer`]. This new implementation introduces several changes to the configuration parameters and overall structure of the trainer. +Below is a summary of the key changes for [`RLOOConfig`]: + +| TRL ≤ 0.21.x | TRL ≥ 0.22.0 | +| --- | --- | +| `rloo_k` | renamed to `num_generations` | +| `cliprange` | renamed to `epsilon` | +| `kl_coef` | renamed to `beta` | +| `exp_name` | renamed to `run_name`. Use `run_name = f"{exp_name}__{seed}__{int(time.time())}"` to replicate old behavior | +| `normalize_reward` | renamed to `normalize_advantages`. Note: this always normalized advantages (despite the old name) | +| `num_ppo_epochs` | renamed to `num_iterations` (default: `1`) | +| `token_level_kl` | **removed** – KL is now computed only at the sequence level | +| `dataset_num_proc` | **removed** – it was unused | +| `num_mini_batches` | renamed to `steps_per_generation` | +| `total_episodes` | use `max_steps=total_episodes / gradient_accumulation_steps` instead | +| `local_rollout_forward_batch_size` | **removed** – now automatically set to `per_device_train_batch_size` (or `per_device_eval_batch_size` during evaluation) | +| `num_sample_generations` | **removed** – use `logging_steps` to control generation logging frequency | +| `response_length` | renamed to `max_completion_length` (default: `256`) | +| `stop_token` | **removed** | +| `stop_token_id` | **removed** – use `processing_class.eos_token_id` instead | +| `missing_eos_penalty` | **removed** – replicate with a custom reward function checking if `eos_token_id` is in `completion_ids` | + +Below is a summary of the key changes for [`RLOOTrainer`]: + +| TRL ≤ 0.21.x | TRL ≥ 0.22.0 | +| --- | --- | +| `config` | renamed to `args` | +| `reward_model` | renamed to `reward_funcs`, which now supports both reward models and custom reward functions | +| `policy` | renamed to `model` | +| `ref_policy` | **removed** – the reference model is now created automatically from `model` | +| `data_collator` | **removed** | diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/script_utils.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/script_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..1ecb73756530d0fcdd87f668dd8385ebfbce1536 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/script_utils.md @@ -0,0 +1,24 @@ +# Scripts Utilities + +## ScriptArguments + +[[autodoc]] ScriptArguments + +## TrlParser + +[[autodoc]] TrlParser + - parse_args_and_config + - parse_args_into_dataclasses + - set_defaults_with_config + +## get_dataset + +[[autodoc]] get_dataset + +## DatasetConfig + +[[autodoc]] scripts.utils.DatasetConfig + +## DatasetMixtureConfig + +[[autodoc]] DatasetMixtureConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/sdft_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/sdft_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..b9ca808a42a55c8669b53b4132adf1de03d875bf --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/sdft_trainer.md @@ -0,0 +1,128 @@ +# SDFT + +Self-Distilled Fine-Tuning (SDFT) is described in the paper [Self-Distillation Enables Continual Learning](https://huggingface.co/papers/2601.19897) by Idan Shenfeld, Mehul Damani, Jonas Hübotter, and Pulkit Agrawal. + +> Continual learning, enabling models to acquire new skills and knowledge without degrading existing capabilities, remains a fundamental challenge for foundation models. While on-policy reinforcement learning can reduce forgetting, it requires explicit reward functions that are often unavailable. Learning from expert demonstrations, the primary alternative, is dominated by supervised fine-tuning (SFT), which is inherently off-policy. We introduce Self-Distillation Fine-Tuning (SDFT), a simple method that enables on-policy learning directly from demonstrations. SDFT leverages in-context learning by using a demonstration-conditioned model as its own teacher, generating on-policy training signals that preserve prior capabilities while acquiring new skills. Across skill learning and knowledge acquisition tasks, SDFT consistently outperforms SFT, achieving higher new-task accuracy while substantially reducing catastrophic forgetting. In sequential learning experiments, SDFT enables a single model to accumulate multiple skills over time without performance regression, establishing on-policy distillation as a practical path to continual learning from demonstrations. + +## How it works + +Plain supervised fine-tuning trains on the demonstration text off-policy, which tends to overwrite prior capabilities. SDFT learns on-policy instead: the student generates from the plain `prompt`, a teacher — the same model shown the `prompt` plus the example's `privileged_context` — re-scores those tokens, and its demonstration-conditioned distribution is distilled back into the student. Teacher and student are one network differing only in what they see, creating a *self*-distillation loop. + +## Choosing the teacher + +`teacher_model_kind` selects which copy of the model acts as teacher. `"base"` (the default) freezes the initial weights as a fixed reference, matching the paper; `"live"` reuses the current student for a zero-lag self-teacher; `"ema"` maintains an exponential moving average, resynced every `teacher_sync_steps` steps at rate `teacher_update_rate`. Under PEFT, `"base"` is obtained by disabling the adapter during the teacher forward to recover the base weights, and `"ema"` with pure-LoRA training holds the moving average in a dedicated `"teacher"` adapter instead of a second model copy. `"ema"` with a non-pure-LoRA PEFT model (e.g. `modules_to_save` or `bias`) is not supported, since a separate EMA copy cannot be parameter-matched to the student. + +By default the student generates from the plain prompt; set `generate_from_teacher=True` to sample from the demonstration-conditioned prompt instead, trading on-policy fidelity for higher-quality rollouts. The distillation objective is set by `distillation_mode` (`"topk_logits"` by default, with `"full_logits"` and `"sampled_token"` alternatives), `distillation_alpha`, and `distillation_topk`; `num_loss_tokens_to_skip` drops leading completion tokens from the loss. Setting `use_liger_kernel=True` swaps in a memory-efficient fused JSD loss (Liger) that avoids materializing the full-vocabulary logits; it requires `distillation_mode="full_logits"` and is incompatible with `distillation_is_clip`. Training is text-only; generation runs through transformers by default, or vLLM (colocate or server mode) when `use_vllm=True`. + +## Usage + +```python +from datasets import Dataset + +from trl.experimental.sdft import SDFTConfig, SDFTTrainer + +dataset = Dataset.from_dict( + { + "prompt": [[{"role": "user", "content": "Solve 2+2."}]], + "privileged_context": ["Example answer: 4."], + } +) + +training_args = SDFTConfig( + output_dir="sdft-model", + distillation_alpha=0.5, + distillation_mode="topk_logits", + distillation_topk=5, + max_completion_length=64, +) + +trainer = SDFTTrainer( + model="Qwen/Qwen2.5-1.5B-Instruct", + args=training_args, + train_dataset=dataset, +) +trainer.train() +``` + +To generate from the teacher-conditioned prompt instead of the student prompt, set `generate_from_teacher=True`. +To customize how the teacher prompt is built, set `teacher_prompt_template` on [`SDFTConfig`]. + +## Serving the teacher from the vLLM server + +With `teacher_model_kind="live"` the teacher is the current student, whose weights the vLLM **server** already holds (they are synced for generation each step). Set `use_teacher_server=True` to score the teacher log-probabilities on that same server instead of running a separate local teacher forward, removing the teacher from the training step entirely: + +```python +training_args = SDFTConfig( + output_dir="sdft-model", + use_vllm=True, + vllm_mode="server", + teacher_model_kind="live", + use_teacher_server=True, + distillation_mode="sampled_token", +) +``` + +When using the teacher server: + +- `use_vllm=True` and `vllm_mode="server"` are required +- `teacher_model_kind` must be `"live"` (the server holds the current student weights) +- `distillation_mode` must be `"sampled_token"` (reverse KL on the realized token) or `"topk_logits"`. The server returns the teacher's own top-k log-probs, so `topk_logits` distills over the teacher's top-k support (it cannot use the student's, unlike the local objective); with a `"live"` teacher the two supports nearly coincide. `full_logits` is unavailable. +- `use_liger_kernel` is not supported + +## Expected dataset columns + +Each example must provide: + +- `prompt`: the student-facing prompt +- `privileged_context`: only the extra teacher-only information, such as a demonstration, hint, or privileged feedback + +Both standard text prompts and conversational prompts are supported by the trainer prompt handling. + +## Callbacks + +The trainer emits a small set of callback hooks that are useful for debugging, observability, and tests. These hooks are intended as practical integration points for experimental self-distillation workflows. + +Shared self-distillation hooks: + +- `on_self_distillation_batch_prepared`: fired when a self-distillation batch is ready. The payload includes `prompt_ids`, `completion_ids`, and `old_per_token_logps` when importance-sampling clipping inputs are available. +- `on_generation_batch_built`: fired when a new buffered generation batch is created. The payload includes `generate_every` and `steps_per_generation`. + +SDFT-specific hook: + +- `on_generation_prompts_selected`: fired when SDFT chooses the prompt source for on-policy generation. The payload includes the selected `generation_prompts` and the corresponding `generation_prompt_text`. + +## Example script + +Use [`examples/scripts/sdft.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/sdft.py) to launch SDFT training from the command line. The script supports any causal LM from the Hub, custom local datasets via `--dataset_path`, and PEFT/LoRA via the standard `ModelConfig` flags. + +```bash +python examples/scripts/sdft.py \ + --model_name_or_path Qwen/Qwen3.5-0.8B \ + --dataset_name your-org/your-dataset \ + --output_dir outputs/sdft-qwen3.5-0.8b \ + --per_device_train_batch_size 1 \ + --gradient_accumulation_steps 16 \ + --learning_rate 2e-5 \ + --max_prompt_length 1024 \ + --max_completion_length 512 \ + --generate_from_teacher \ + --teacher_model_kind ema \ + --teacher_sync_steps 1 \ + --teacher_update_rate 0.05 \ + --eval_strategy steps \ + --eval_steps 50 \ + --report_to wandb +``` + +The original implementation is available at [idanshen/Self-Distillation](https://github.com/idanshen/Self-Distillation). + +## SDFTConfig + +[[autodoc]] experimental.sdft.SDFTConfig + +## SDFTTrainer + +[[autodoc]] experimental.sdft.SDFTTrainer + - train + - save_model + - push_to_hub diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/sdpo_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/sdpo_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..68fb2593e2249e579c6e8c29c1d06f813a7fd59e --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/sdpo_trainer.md @@ -0,0 +1,131 @@ +# SDPO + +Self-Distillation Policy Optimization (SDPO) was introduced in [Reinforcement Learning via Self-Distillation](https://huggingface.co/papers/2601.20802) by [Jonas Hübotter](https://huggingface.co/jonhue), Frederike Lübeck, Lejs Behric, [Anton Baumann](https://huggingface.co/antonbaumann), Marco Bagatella, Daniel Marta, Ido Hakimi, Idan Shenfeld, Thomas Kleine Buening, Carlos Guestrin, and Andreas Krause. + +> Large language models are increasingly post-trained with reinforcement learning in verifiable domains such as code and math. Yet, current methods for reinforcement learning with verifiable rewards (RLVR) learn only from a scalar outcome reward per attempt, creating a severe credit-assignment bottleneck. Many verifiable environments actually provide rich textual feedback, such as runtime errors or judge evaluations, that explain why an attempt failed. We formalize this setting as reinforcement learning with rich feedback and introduce Self-Distillation Policy Optimization (SDPO), which converts tokenized feedback into a dense learning signal without any external teacher or explicit reward model. SDPO treats the current model conditioned on feedback as a self-teacher and distills its feedback-informed next-token predictions back into the policy. In this way, SDPO leverages the model's ability to retrospectively identify its own mistakes in-context. Across scientific reasoning, tool use, and competitive programming on LiveCodeBench v6, SDPO improves sample efficiency and final accuracy over strong RLVR baselines. Notably, SDPO also outperforms baselines in standard RLVR environments that only return scalar feedback by using successful rollouts as implicit feedback for failed attempts. Finally, applying SDPO to individual questions at test time accelerates discovery on difficult binary-reward tasks, achieving the same discovery probability as best-of-k sampling or multi-turn conversations with 3x fewer attempts. + +## How it works + +SDPO targets reinforcement learning with verifiable rewards (RLVR), where each attempt yields only a sparse scalar reward. It turns that into a dense, token-level signal: for each prompt the policy samples `num_generations` completions scored by `reward_funcs`, a successful rollout (plus optional `privileged_context` feedback) becomes a teacher reprompt, and the teacher's feedback-informed distribution over a completion is distilled back into the policy. Teacher and student are the same network, so no external teacher or reward model is needed beyond the verifier. + +## Loss modes and the teacher + +`distillation_weight` controls how the two signals combine as a convex combination: the loss is `(1 - distillation_weight) * policy_loss + distillation_weight * distillation_loss`. `1.0` (the default) trains purely on the self-distillation loss, `0.0` falls back to the standard GRPO-style policy gradient, and intermediate values blend both. The distillation objective itself is set by `distillation_mode` — `"sampled_token"` (the default) uses a token-level reverse KL and requires `distillation_alpha=1.0`, while `"full_logits"` and `"topk_logits"` distill over the full or top-`distillation_topk` vocabulary. Setting `use_liger_kernel=True` swaps in a memory-efficient fused JSD loss (Liger) for the distillation term; it requires `distillation_weight=1.0`, `distillation_mode="full_logits"`, and is incompatible with `distillation_is_clip`. + +`teacher_model_kind` chooses the teacher weights: `"ema"` (the default) tracks the student with an exponential moving average synced every `teacher_sync_steps` steps at rate `teacher_update_rate`, `"live"` reuses the current student directly, and `"base"` freezes the initial weights. Reprompting is governed by `use_successful_as_teacher`, `success_reward_threshold`, `dont_reprompt_on_self_success`, and the `reprompt_template` / `solution_template` / `feedback_template` strings. Generation runs through transformers by default, or vLLM (colocate or server mode) when `use_vllm=True`. + +## Expected dataset columns + +Each example must provide: + +- `prompt`: the student-facing prompt +- `privileged_context`: optional privileged text, such as environment feedback, used when `include_environment_feedback=True` + +## Usage + +```python +from datasets import Dataset + +from trl.experimental.sdpo import SDPOConfig, SDPOTrainer + +dataset = Dataset.from_dict( + { + "prompt": [[{"role": "user", "content": "Solve 2+2."}]], + "privileged_context": ["Your earlier answer used the wrong format."], + } +) + +training_args = SDPOConfig( + output_dir="sdpo-model", + distillation_mode="topk_logits", # Explicitly select top-K logit distillation + distillation_topk=100, # Required when using top-K logit distillation + include_environment_feedback=True, # Use dataset privileged_context for teacher reprompts +) + +trainer = SDPOTrainer( + model="Qwen/Qwen2.5-1.5B-Instruct", + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, +) +trainer.train() +``` + +SDPO always requires a `prompt` column. To use environment feedback, also include a `privileged_context` column and set `include_environment_feedback=True`. SDPO will use successful rollouts and, when enabled, that text to build teacher reprompts for self-distillation. + +## Serving the teacher from the vLLM server + +With `teacher_model_kind="live"` the teacher is the current student, whose weights the vLLM **server** already holds (they are synced for generation each step). Set `use_teacher_server=True` to score the teacher log-probabilities on that same server instead of running a separate local teacher forward, removing the teacher from the training step entirely: + +```python +training_args = SDPOConfig( + output_dir="sdpo-model", + use_vllm=True, + vllm_mode="server", + teacher_model_kind="live", + use_teacher_server=True, + distillation_weight=1.0, + distillation_mode="sampled_token", +) +``` + +When using the teacher server: + +- `use_vllm=True` and `vllm_mode="server"` are required +- `teacher_model_kind` must be `"live"` (the server holds the current student weights) +- `distillation_weight` must be `1.0` (pure distillation; a convex blend with the policy loss needs the full-vocabulary logits) +- `distillation_mode` must be `"sampled_token"` (reverse KL on the realized token) or `"topk_logits"`. The server returns the teacher's own top-k log-probs, so `topk_logits` distills over the teacher's top-k support (it cannot use the student's, unlike the local objective); with a `"live"` teacher the two supports nearly coincide. `full_logits` is unavailable. +- `use_liger_kernel` is not supported + +## Callbacks + +The trainer emits a small set of callback hooks that are useful for debugging, observability, and tests. These hooks are intended as practical integration points for experimental self-distillation workflows. + +Shared self-distillation hooks: + +- `on_self_distillation_batch_prepared`: fired when a self-distillation batch is ready. The payload includes `prompt_ids`, `completion_ids`, and `old_per_token_logps` when importance-sampling clipping inputs are available. +- `on_generation_batch_built`: fired when a new buffered generation batch is created. The payload includes `generate_every` and `steps_per_generation`. + +SDPO-specific hook: + +- `on_teacher_context_built`: fired after SDPO constructs the teacher-conditioned inputs. The payload includes `teacher_input_ids`, `teacher_attention_mask`, `completion_mask`, and `self_distillation_mask`. + +## Example script + +Use [`examples/scripts/sdpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/sdpo.py) to launch SDPO training from the command line. The script supports verifiable math rewards, environment feedback via `--feedback_column`, and PEFT/LoRA via the standard `ModelConfig` flags. + +```bash +python examples/scripts/sdpo.py \ + --model_name_or_path Qwen/Qwen2.5-Math-1.5B-Instruct \ + --dataset_name openai/gsm8k \ + --dataset_config main \ + --output_dir outputs/sdpo-qwen35-2b-gsm8k \ + --learning_rate 5e-5 \ + --dtype bfloat16 \ + --bf16 true \ + --max_completion_length 128 \ + --use_peft \ + --lora_target_modules q_proj k_proj v_proj o_proj gate_proj up_proj down_proj \ + --per_device_train_batch_size 1 \ + --gradient_accumulation_steps 2 \ + --num_generations 8 \ + --generation_batch_size 32 \ + --distillation_alpha 1.0 \ + --distillation_mode sampled_token \ + --distillation_weight 0.5 \ + --report_to none \ + --eval_strategy steps \ + --eval_steps 1000 \ + --save_strategy no +``` + +## SDPOConfig + +[[autodoc]] experimental.sdpo.SDPOConfig + +## SDPOTrainer + +[[autodoc]] experimental.sdpo.SDPOTrainer + - train + - save_model + - push_to_hub diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/sft_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/sft_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..72da68845e8696a693623c390b082348e69f25da --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/sft_trainer.md @@ -0,0 +1,349 @@ +# SFT Trainer + +[![All_models-SFT-blue](https://img.shields.io/badge/All_models-SFT-blue)](https://huggingface.co/models?other=sft,trl) [![smol_course-Chapter_1-yellow](https://img.shields.io/badge/smol_course-Chapter_1-yellow)](https://github.com/huggingface/smol-course/tree/main/1_instruction_tuning) + +## Overview + +TRL supports the Supervised Fine-Tuning (SFT) Trainer for training language models. + +This post-training method was contributed by [Younes Belkada](https://huggingface.co/ybelkada). + +## Quick start + +This example demonstrates how to train a language model using the [`SFTTrainer`] from TRL. We train a [Qwen 3 0.6B](https://huggingface.co/Qwen/Qwen3-0.6B) model on the [Capybara dataset](https://huggingface.co/datasets/trl-lib/Capybara), a compact, diverse multi-turn dataset to benchmark reasoning and generalization. + +```python +from trl import SFTTrainer +from datasets import load_dataset + +trainer = SFTTrainer( + model="Qwen/Qwen3-0.6B", + train_dataset=load_dataset("trl-lib/Capybara", split="train"), +) +trainer.train() +``` + + + +## Expected dataset type and format + +SFT supports both [language modeling](dataset_formats#language-modeling) and [prompt-completion](dataset_formats#prompt-completion) datasets. The [`SFTTrainer`] is compatible with both [standard](dataset_formats#standard) and [conversational](dataset_formats#conversational) dataset formats. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset. + +```python +# Standard language modeling +{"text": "The sky is blue."} + +# Conversational language modeling +{"messages": [{"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}]} + +# Standard prompt-completion +{"prompt": "The sky is", + "completion": " blue."} + +# Conversational prompt-completion +{"prompt": [{"role": "user", "content": "What color is the sky?"}], + "completion": [{"role": "assistant", "content": "It is blue."}]} +``` + +If your dataset is not in one of these formats, you can preprocess it to convert it into the expected format. Here is an example with the [FreedomIntelligence/medical-o1-reasoning-SFT](https://huggingface.co/datasets/FreedomIntelligence/medical-o1-reasoning-SFT) dataset: + +```python +from datasets import load_dataset + +dataset = load_dataset("FreedomIntelligence/medical-o1-reasoning-SFT", "en") + +def preprocess_function(example): + return { + "prompt": [{"role": "user", "content": example["Question"]}], + "completion": [ + {"role": "assistant", "content": f"{example['Complex_CoT']}{example['Response']}"} + ], + } + +dataset = dataset.map(preprocess_function, remove_columns=["Question", "Response", "Complex_CoT"]) +print(next(iter(dataset["train"]))) +``` + +```json +{ + "prompt": [ + { + "content": "Given the symptoms of sudden weakness in the left arm and leg, recent long-distance travel, and the presence of swollen and tender right lower leg, what specific cardiac abnormality is most likely to be found upon further evaluation that could explain these findings?", + "role": "user", + } + ], + "completion": [ + { + "content": "Okay, let's see what's going on here. We've got sudden weakness [...] clicks into place!The specific cardiac abnormality most likely to be found in [...] the presence of a PFO facilitating a paradoxical embolism.", + "role": "assistant", + } + ], +} +``` + +## Looking deeper into the SFT method + +Supervised Fine-Tuning (SFT) is the simplest and most commonly used method to adapt a language model to a target dataset. The model is trained in a fully supervised fashion using pairs of input and output sequences. The goal is to minimize the negative log-likelihood (NLL) of the target sequence, conditioning on the input. + +This section breaks down how SFT works in practice, covering the key steps: **preprocessing**, **tokenization** and **loss computation**. + +### Preprocessing and tokenization + +During training, each example is expected to contain a **text field** or a **(prompt, completion)** pair, depending on the dataset format. For more details on the expected formats, see [Dataset formats](dataset_formats). +The [`SFTTrainer`] tokenizes each input using the model's tokenizer. If both prompt and completion are provided separately, they are concatenated before tokenization. + +### Computing the loss + +![sft_figure](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/sft_figure.png) + +The loss used in SFT is the **token-level cross-entropy loss**, defined as: + +$$ +\mathcal{L}_{\text{SFT}}(\theta) = - \sum_{t=1}^{T} \log p_\theta(y_t \mid y_{ [!TIP] +> The paper [On the Generalization of SFT: A Reinforcement Learning Perspective with Reward Rectification](https://huggingface.co/papers/2508.05629) proposes an alternative loss function, called **Dynamic Fine-Tuning (DFT)**, which aims to improve generalization by rectifying the reward signal. This method can be enabled by setting `loss_type="dft"` in the [`SFTConfig`]. For more details, see [Paper Index - Dynamic Fine-Tuning](paper_index#on-the-generalization-of-sft-a-reinforcement-learning-perspective-with-reward-rectification). + +> [!TIP] +> By default, [`SFTTrainer`] uses `loss_type="chunked_nll"`: same math as `"nll"`, but the `lm_head` projection skips ignored-label tokens and the cross-entropy is processed in chunks, so peak activation memory does not scale with the full vocab × seq_len logits tensor. To fall back to the standard path, set `loss_type="nll"`. When `use_liger_kernel=True`, the default automatically resolves to `"nll"` (the two paths are not compatible). See [Chunked cross-entropy for reducing peak memory usage](reducing_memory_usage#chunked-cross-entropy-for-reducing-peak-memory-usage). + +### Label shifting and masking + +During training, the loss is computed using a **one-token shift**: the model is trained to predict each token in the sequence based on all previous tokens. Specifically, the input sequence is shifted right by one position to form the target labels. +Padding tokens (if present) are ignored in the loss computation by applying an ignore index (default: `-100`) to the corresponding positions. This ensures that the loss focuses only on meaningful, non-padding tokens. + +## Logged metrics + +While training and evaluating we record the following reward metrics: + +* `global_step`: The total number of optimizer steps taken so far. +* `epoch`: The current epoch number, based on dataset iteration. +* `num_tokens`: The total number of tokens processed so far. +* `loss`: The average cross-entropy loss computed over non-masked tokens in the current logging interval. +* `entropy`: The average entropy of the model's predicted token distribution over non-masked tokens. +* `mean_token_accuracy`: The proportion of non-masked tokens for which the model’s top-1 prediction matches the ground truth token. +* `learning_rate`: The current learning rate, which may change dynamically if a scheduler is used. +* `grad_norm`: The L2 norm of the gradients, computed before gradient clipping. + +## Customization + +### Model initialization + +You can directly pass the kwargs of the [`~transformers.AutoModelForCausalLM.from_pretrained()`] method to the [`SFTConfig`]. For example, if you want to load a model in a different precision, analogous to + +```python +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-0.6B", dtype=torch.bfloat16) +``` + +you can do so by passing the `model_init_kwargs={"dtype": torch.bfloat16}` argument to the [`SFTConfig`]. + +```python +from trl import SFTConfig + +training_args = SFTConfig( + model_init_kwargs={"dtype": torch.bfloat16}, +) +``` + +Note that all keyword arguments of [`~transformers.AutoModelForCausalLM.from_pretrained()`] are supported. + +### Packing + +[`SFTTrainer`] supports _example packing_, where multiple examples are packed in the same input sequence to increase training efficiency. To enable packing, simply pass `packing=True` to the [`SFTConfig`] constructor. + +```python +training_args = SFTConfig(packing=True) +``` + +For more details on packing, see [Packing](reducing_memory_usage#packing). + +### Train on assistant messages only + +To train on assistant messages only, use a [conversational](dataset_formats#conversational) dataset and set `assistant_only_loss=True` in the [`SFTConfig`]. This setting ensures that loss is computed **only** on the assistant responses, ignoring user or system messages. + +```python +training_args = SFTConfig(assistant_only_loss=True) +``` + +![train_on_assistant](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/train_on_assistant.png) + +> [!WARNING] +> This functionality requires the chat template to include `{% generation %}` and `{% endgeneration %}` keywords. For known model families (e.g. Qwen3), TRL automatically patches the template when `assistant_only_loss=True`. See [Chat Templates](chat_templates#training-templates) for the full list of bundled training templates. For other models, check that your chat template includes these keywords. See [HuggingFaceTB/SmolLM3-3B](https://huggingface.co/HuggingFaceTB/SmolLM3-3B/blob/main/chat_template.jinja#L76-L82) for an example. + +### Train on completion only + +To train on completion only, use a [prompt-completion](dataset_formats#prompt-completion) dataset. By default, the trainer computes the loss on the completion tokens only, ignoring the prompt tokens. If you want to train on the full sequence, set `completion_only_loss=False` in the [`SFTConfig`]. + +```python +from trl import SFTConfig, SFTTrainer +from datasets import load_dataset + +# Load a prompt-completion dataset; loss is computed on the completion only by default +dataset = load_dataset("trl-lib/kto-mix-14k", split="train") + +trainer = SFTTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", + args=SFTConfig(completion_only_loss=True), # True by default for prompt-completion datasets + train_dataset=dataset, +) +trainer.train() +``` + +![train_on_completion](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/train_on_completion.png) + +> [!TIP] +> Training on completion only is compatible with training on assistant messages only. In this case, use a [conversational](dataset_formats#conversational) [prompt-completion](dataset_formats#prompt-completion) dataset and set `assistant_only_loss=True` in the [`SFTConfig`]. + +### Train adapters with PEFT + +We support tight integration with 🤗 PEFT library, allowing any user to conveniently train adapters and share them on the Hub, rather than training the entire model. + +```python +from datasets import load_dataset +from trl import SFTTrainer +from peft import LoraConfig + +dataset = load_dataset("trl-lib/Capybara", split="train") + +trainer = SFTTrainer( + "Qwen/Qwen3-0.6B", + train_dataset=dataset, + peft_config=LoraConfig(), +) + +trainer.train() +``` + +You can also continue training your [`~peft.PeftModel`]. For that, first load a `PeftModel` outside [`SFTTrainer`] and pass it directly to the trainer without the `peft_config` argument being passed. + +```python +from datasets import load_dataset +from trl import SFTTrainer +from peft import AutoPeftModelForCausalLM + +model = AutoPeftModelForCausalLM.from_pretrained("trl-lib/Qwen3-4B-LoRA", is_trainable=True) +dataset = load_dataset("trl-lib/Capybara", split="train") + +trainer = SFTTrainer( + model=model, + train_dataset=dataset, +) + +trainer.train() +``` + +> [!TIP] +> When training adapters, you typically use a higher learning rate (≈1e‑4) since only new parameters are being learned. +> +> ```python +> SFTConfig(learning_rate=1e-4, ...) +> ``` + +### Train with Liger Kernel + +Liger Kernel is a collection of Triton kernels for LLM training that boosts multi-GPU throughput by 20%, cuts memory use by 60% (enabling up to 4× longer context), and works seamlessly with tools like FlashAttention, PyTorch FSDP, and DeepSpeed. For more information, see [Liger Kernel Integration](liger_kernel_integration). + +### Rapid Experimentation for SFT + +RapidFire AI is an open-source experimentation engine that sits on top of TRL and lets you launch multiple SFT configurations at once, even on a single GPU. Instead of trying configurations sequentially, RapidFire lets you **see all their learning curves earlier, stop underperforming runs, and clone promising ones with new settings in flight** without restarting. For more information, see [RapidFire AI Integration](rapidfire_integration). + +### Train with Unsloth + +Unsloth is an open‑source framework for fine‑tuning and reinforcement learning that trains LLMs (like Llama, Mistral, Gemma, DeepSeek, and more) up to 2× faster with up to 70% less VRAM, while providing a streamlined, Hugging Face–compatible workflow for training, evaluation, and deployment. For more information, see [Unsloth Integration](unsloth_integration). + +## Instruction tuning example + +**Instruction tuning** teaches a base language model to follow user instructions and engage in conversations. This requires: + +1. **Chat template**: Defines how to structure conversations into text sequences, including role markers (user/assistant), special tokens, and turn boundaries. Read more about chat templates in [Chat templates](https://huggingface.co/docs/transformers/chat_templating#templates). +2. **Conversational dataset**: Contains instruction-response pairs + +This example shows how to transform the [Qwen 3 0.6B Base](https://huggingface.co/Qwen/Qwen3-0.6B-Base) model into an instruction-following model using the [Capybara dataset](https://huggingface.co/datasets/trl-lib/Capybara) and a chat template from [HuggingFaceTB/SmolLM3-3B](https://huggingface.co/HuggingFaceTB/SmolLM3-3B). The SFT Trainer automatically handles tokenizer updates and special token configuration. + +```python +from trl import SFTConfig, SFTTrainer +from datasets import load_dataset + +trainer = SFTTrainer( + model="Qwen/Qwen3-0.6B-Base", + args=SFTConfig( + output_dir="Qwen3-0.6B-Instruct", + chat_template_path="HuggingFaceTB/SmolLM3-3B", + ), + train_dataset=load_dataset("trl-lib/Capybara", split="train"), +) +trainer.train() +``` + +> [!WARNING] +> Some base models, like those from Qwen, have a predefined chat template in the model's tokenizer. In these cases, it is not necessary to apply [`clone_chat_template()`], as the tokenizer already handles the formatting. However, it is necessary to align the EOS token with the chat template to ensure the model's responses terminate correctly. In these cases, specify `eos_token` in [`SFTConfig`]; for example, for `Qwen/Qwen2.5-1.5B`, one should set `eos_token="<|im_end|>"`. + +Once trained, your model can now follow instructions and engage in conversations using its new chat template. + +```python +>>> from transformers import pipeline +>>> pipe = pipeline("text-generation", model="Qwen3-0.6B-Instruct/checkpoint-5000") +>>> prompt = "<|im_start|>user\nWhat is the capital of France? Answer in one word.<|im_end|>\n<|im_start|>assistant\n" +>>> response = pipe(prompt) +>>> response[0]["generated_text"] +'<|im_start|>user\nWhat is the capital of France? Answer in one word.<|im_end|>\n<|im_start|>assistant\nThe capital of France is Paris.' +``` + +Alternatively, use the structured conversation format (recommended): + +```python +>>> prompt = [{"role": "user", "content": "What is the capital of France? Answer in one word."}] +>>> response = pipe(prompt) +>>> response[0]["generated_text"] +[{'role': 'user', 'content': 'What is the capital of France? Answer in one word.'}, {'role': 'assistant', 'content': 'The capital of France is Paris.'}] +``` + +## Tool Calling with SFT + +The [`SFTTrainer`] fully supports fine-tuning models with _tool calling_ capabilities. In this case, each dataset example should include: + +* The conversation messages, including any tool calls (`tool_calls`) and tool responses (`tool` role messages) +* The list of available tools in the `tools` column, typically provided as JSON schemas + +For details on the expected dataset structure, see the [Dataset Format — Tool Calling](dataset_formats#tool-calling) section. + +## Training Vision Language Models + +[`SFTTrainer`] fully supports training Vision-Language Models (VLMs). To train a VLM, provide a dataset with either an `image` column (single image per sample) or an `images` column (list of images per sample). For more information on the expected dataset structure, see the [Dataset Format — Vision Dataset](dataset_formats#vision-dataset) section. +An example of such a dataset is the [LLaVA Instruct Mix](https://huggingface.co/datasets/trl-lib/llava-instruct-mix). + +```python +from trl import SFTConfig, SFTTrainer +from datasets import load_dataset + +trainer = SFTTrainer( + model="Qwen/Qwen2.5-VL-3B-Instruct", + args=SFTConfig(max_length=None), + train_dataset=load_dataset("trl-lib/llava-instruct-mix", split="train"), +) +trainer.train() +``` + +> [!TIP] +> For VLMs, truncating may remove image tokens, leading to errors during training. To avoid this, set `max_length=None` in the [`SFTConfig`]. This allows the model to process the full sequence length without truncating image tokens. +> +> ```python +> SFTConfig(max_length=None, ...) +> ``` +> +> Only use `max_length` when you've verified that truncation won't remove image tokens for the entire dataset. + +## SFTTrainer + +[[autodoc]] SFTTrainer + - train + - save_model + - push_to_hub + +## SFTConfig + +[[autodoc]] SFTConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/speeding_up_training.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/speeding_up_training.md new file mode 100644 index 0000000000000000000000000000000000000000..c855cc06233a198e3e6967345b2b0984c5b90d93 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/speeding_up_training.md @@ -0,0 +1,204 @@ +# Speeding Up Training + +This guide covers various methods to accelerate training in TRL. Each technique includes minimal examples with links to more comprehensive documentation. + +## vLLM for fast generation in online methods + +[Online methods](index#online-methods) such as GRPO or Online DPO require the model to generate completions, which is often a slow process and can significantly impact training time. +To speed up generation, you can use [vLLM](https://github.com/vllm-project/vllm), a library that enables fast generation through, among other things, PagedAttention. TRL's online trainers support vLLM, greatly improving training speed. For more details, see [vLLM Integration](vllm_integration). + +To use [vLLM](https://github.com/vllm-project/vllm), first install it using: + +```bash +pip install trl[vllm] +``` + + + + +First, start a vLLM server by running: + +```bash +trl vllm-serve --model +``` + +Then, run the training script and pass `use_vllm=True` in the training arguments. + +```python +from trl.experimental.online_dpo import OnlineDPOConfig + +training_args = OnlineDPOConfig(..., use_vllm=True, vllm_mode="server") +``` + + + + +First, start a vLLM server by running: + +```bash +trl vllm-serve --model +``` + +Then, run the training script and pass `use_vllm=True` in the training arguments. + +```python +from trl import GRPOConfig + +training_args = GRPOConfig(..., use_vllm=True, vllm_mode="server") +``` + +You can customize the server configuration by passing additional arguments. For more information, see [vLLM integration](vllm_integration). + +> [!WARNING] +> When using vLLM, ensure that the GPUs assigned for training and generation are separate to avoid resource conflicts. For instance, if you plan to use 4 GPUs for training and another 4 for vLLM generation, you can specify GPU allocation using `CUDA_VISIBLE_DEVICES`. +> +> Set GPUs **0-3** for vLLM generation: +> +> ```sh +> CUDA_VISIBLE_DEVICES=0,1,2,3 trl vllm-serve --model +> ``` +> +> And GPUs **4-7** for training: +> +> ```sh +> CUDA_VISIBLE_DEVICES=4,5,6,7 accelerate launch train.py +> ``` + + + + +First, start a vLLM server by running: + +```bash +trl vllm-serve --model +``` + +Then, run the training script and pass `use_vllm=True` in the training arguments. + +```python +from trl import RLOOConfig + +training_args = RLOOConfig(..., use_vllm=True, vllm_mode="server") +``` + +You can customize the server configuration by passing additional arguments. For more information, see [vLLM integration](vllm_integration). + +> [!WARNING] +> When using vLLM, ensure that the GPUs assigned for training and generation are separate to avoid resource conflicts. For instance, if you plan to use 4 GPUs for training and another 4 for vLLM generation, you can specify GPU allocation using `CUDA_VISIBLE_DEVICES`. +> +> Set GPUs **0-3** for vLLM generation: +> +> ```sh +> CUDA_VISIBLE_DEVICES=0,1,2,3 trl vllm-serve --model +> ``` +> +> And GPUs **4-7** for training: +> +> ```sh +> CUDA_VISIBLE_DEVICES=4,5,6,7 accelerate launch train.py +> ``` + + + + +## Optimized attention implementations + +TRL supports various optimized attention implementations that can significantly speed up training while reducing memory usage. You can use either a pre-optimized kernels directly from the [Kernels Hub](kernels_hub) or a manually built attention backend. + + + + +You can use pre-optimized attention kernels from the Hub without manual compilation: + +```python +from trl import SFTConfig + +training_args = SFTConfig(..., model_init_kwargs={"attn_implementation": "kernels-community/flash-attn2"}) +``` + +Other options include `kernels-community/vllm-flash-attn3` and `kernels-community/paged-attention`. + +Optimized attention works across all TRL trainers. For more details, see [Kernels Hub Integration](kernels_hub). + + + + +> [!WARNING] +> Manually building optimized attention backends is complex and time-consuming. It's never recommended unless absolutely necessary. Consider using Kernels from the Hub instead, as described in the previous section. + +If you have manually installed an optimized attention backend like Flash Attention 2, you can specify it in the training arguments: + +```python +from trl import SFTConfig + +training_args = SFTConfig(..., model_init_kwargs={"attn_implementation": "flash_attention_2"}) +``` + + + + +## Liger Kernel for memory optimization + +Liger Kernel is a collection of Triton kernels designed for LLM training that can increase throughput by 20% and reduce memory usage by 60%. + + + + +```python +from trl import SFTConfig + +training_args = SFTConfig(..., use_liger_kernel=True) +``` + + + + +```python +from trl import DPOConfig + +training_args = DPOConfig(..., use_liger_kernel=True) +``` + + + + +```python +from trl import GRPOConfig + +training_args = GRPOConfig(..., use_liger_kernel=True) +``` + + + + +```python +from trl.experimental.kto import KTOConfig + +training_args = KTOConfig(..., use_liger_kernel=True) +``` + + + + +```python +from trl.experimental.gkd import GKDConfig + +training_args = GKDConfig(..., use_liger_kernel=True) +``` + + + + +For more information, see [Liger Kernel Integration](liger_kernel_integration). + +## Mixed precision training + +Mixed precision training using bf16 or fp16 can speed up training and reduce memory usage with minimal impact on model quality. + +```python +from trl import SFTConfig + +training_args = SFTConfig(..., bf16=True) # or fp16=True for older GPUs +``` + +Use `bf16=True` for Ampere GPUs (A100, RTX 30xx) or newer, and `fp16=True` for older GPUs. Mixed precision training is supported across all TRL trainers. diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/ssd_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/ssd_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..414221ba088feebc0dff99242bfd12f69c13e112 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/ssd_trainer.md @@ -0,0 +1,111 @@ +# SSD + +Simple Self-Distillation (SSD) is described in [Embarrassingly Simple Self-Distillation Improves Code Generation](https://huggingface.co/papers/2604.01193). + +SSD samples completions from the model at a training-time temperature and truncation configuration, then fine-tunes on those raw, unverified samples with standard cross-entropy loss. It requires no reward model, verifier, teacher model, or reinforcement learning — only a set of problem prompts and the model itself. + +In the current TRL implementation: + +- the model generates completions at a specified training-time temperature (`temperature`) and truncation (`top_k`, `top_p`) +- the dataset only requires a `prompt` column +- training uses standard cross-entropy loss on the generated completions +- empty or single-line stub completions are filtered by default (`filter_empty=True`) +- the evaluation-time temperature and truncation are set independently at inference time +- vLLM can be used for faster generation via `use_vllm=True` (see [vLLM integration](vllm_integration)) + +## Usage + +```python +from datasets import Dataset + +from trl.experimental.ssd import SSDConfig, SSDTrainer + +dataset = Dataset.from_dict( + { + "prompt": [ + [{"role": "user", "content": "Write a function to add two numbers."}], + [{"role": "user", "content": "Write a function to check if a number is prime."}], + ], + } +) + +training_args = SSDConfig( + output_dir="ssd-model", + temperature=0.6, # T_train from the paper + top_k=20, # training-time top-k truncation + top_p=0.95, # training-time top-p truncation + max_completion_length=65536, + learning_rate=5e-6, +) + +trainer = SSDTrainer( + model="Qwen/Qwen3-4B-Instruct", + args=training_args, + train_dataset=dataset, +) +trainer.train() +``` + +## Expected dataset columns + +Each example must provide: + +- `prompt`: the problem prompt (string or conversational format) + +No `privileged_context`, reward functions, or teacher model are needed. + +## Key hyperparameters + +The paper identifies the following key hyperparameters: + +- **`temperature`**: training-time sampling temperature (T_train). Higher values create more diverse samples but may include more noise. The paper uses T_train=0.6 with truncation. +- **`top_k`** and **`top_p`**: training-time truncation parameters (rho_train). These suppress low-probability distractor tails during data synthesis. +- **T_eval**: the evaluation-time decoding temperature is set independently at inference time. The paper shows that T_train and T_eval compose through an effective temperature T_eff = T_train * T_eval, with a broad optimal band. + +## Example script + +Use [`examples/scripts/ssd.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/ssd.py) to launch SSD training from the command line. The script supports any causal LM from the Hub, custom local datasets via `--dataset_path`, and PEFT/LoRA via the standard `ModelConfig` flags. + +```bash +python examples/scripts/ssd.py \ + --model_name_or_path Qwen/Qwen3-4B-Instruct-2507 \ + --dataset_name microsoft/rStar-Coder \ + --dataset_config seed_sft \ + --prompt_column question \ + --output_dir outputs/ssd-qwen3-4b \ + --per_device_train_batch_size 1 \ + --gradient_accumulation_steps 32 \ + --learning_rate 5e-6 \ + --lr_scheduler_type cosine \ + --max_prompt_length 1024 \ + --max_completion_length 65536 \ + --temperature 1.6 \ + --top_k 20 \ + --top_p 0.8 \ + --num_train_epochs 1 \ + --bf16 \ + --report_to trackio +``` + +## Evaluation on LiveCodeBench + +Use [`examples/scripts/ssd_eval.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/ssd_eval.py) to evaluate a base model or an SSD-trained checkpoint on LiveCodeBench v6. The script uses vLLM for generation and LiveCodeBench's official `codegen_metrics` for sandboxed `pass@k` scoring; default decoding parameters match Table 3 of the paper. + +```bash +python examples/scripts/ssd_eval.py \ + --model_name_or_path \ + --temperature 1.1 --top_k 20 --top_p 0.8 \ + --n 1 \ + --output_file outputs/lcb_v6.json +``` + +## SSDConfig + +[[autodoc]] experimental.ssd.SSDConfig + +## SSDTrainer + +[[autodoc]] experimental.ssd.SSDTrainer + - train + - save_model + - push_to_hub diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/tpo_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/tpo_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..9946c3dd5ce049da24da90a89cfe00e715a75a34 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/tpo_trainer.md @@ -0,0 +1,135 @@ +# TPO Trainer + +[![All_models-TPO-blue](https://img.shields.io/badge/All_models-TPO-blue)](https://huggingface.co/models?other=tpo,trl) + +## Overview + +Triple Preference Optimization (TPO) was introduced in the paper [Triple Preference Optimization: Achieving Better Alignment using a Single Step Optimization](https://huggingface.co/papers/2405.16681) by Amir Saeidi, Shivanshu Verma, Aswin RRV, and Chitta Baral. TPO enhances the instruction-following and reasoning capabilities of large language models in a single training step, starting from a pre-trained or instruction-tuned model. + +The abstract from the paper is the following: + +> Reinforcement Learning with Human Feedback (RLHF) enhances the alignment of Large Language Models (LLMs). However, its limitations have led to the development of Direct Preference Optimization (DPO), an RL-free approach designed to overcome these shortcomings. While studies have shown that DPO improves instruction-following capabilities, it negatively impacts the reasoning ability of LLMs. Additionally, DPO is highly sensitive to judgment noise in preference datasets and the size of the training set. Although several modifications to DPO have been proposed, they still fail to fully resolve these issues. To address these limitations, we propose Triple Preference Optimization (TPO), a new preference learning method designed to enhance both reasoning and instruction-following abilities through one-step optimization. We compare TPO against DPO and its recent variants using state-of-the-art training setups, including both base and instructiontuned models such as Mistral and Llama 3. Our evaluation covers a comprehensive range of chat-based and reasoning benchmarks. The results demonstrate that TPO achieves significant improvements over existing methods without substantially increasing response length across different dataset sizes. Specifically, TPO outperforms DPO and SimPO by up to 7.0% and 7.3% points on Arena-Hard, 12.2% and 13.3% points on MixEval-Hard, 10.4% and 10.1% points on MMLU-Pro, and 19.0% and 19.2% points on GSM8K, respectively. Furthermore, TPO achieves these improvements while requiring less data than DPO. + +This post-training method was contributed by [Kashif Rasul](https://huggingface.co/kashif). + +## Quick start + +This example demonstrates how to train a model using the TPO method. We use the [Qwen 3 0.6B model](https://huggingface.co/Qwen/Qwen3-0.6B) as the base model. TPO requires a *triple-preference* dataset (`prompt`, `chosen`, `rejected`, `reference`) — see [Expected dataset type](#expected-dataset-type-and-format) below. + +Below is the script to train the model: + +```python +# train_tpo.py +from datasets import load_dataset +from trl.experimental.tpo import TPOConfig, TPOTrainer +from transformers import AutoModelForCausalLM, AutoTokenizer + +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-0.6B") +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B") +train_dataset = load_dataset("tpo-alignment/triple-preference-ultrafeedback-40K", split="train") + +training_args = TPOConfig(output_dir="Qwen3-0.6B-TPO") +trainer = TPOTrainer(model=model, args=training_args, processing_class=tokenizer, train_dataset=train_dataset) +trainer.train() +``` + +Execute the script using the following command: + +```bash +accelerate launch train_tpo.py +``` + +## Expected dataset type and format + +TPO requires a *triple-preference* dataset: each example must contain a `prompt`, a `chosen` (preferred) completion, a `rejected` (dispreferred) completion **and** a `reference` (gold) completion. The [`experimental.tpo.TPOTrainer`] supports both [conversational](dataset_formats#conversational) and [standard](dataset_formats#standard) dataset formats. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset. + +```python +# Standard format +triple_preference_example = { + "prompt": "The sky is", + "reference": " a beautiful shade of blue.", # gold response (used for the NLL term) + "chosen": " blue.", + "rejected": " green.", +} + +# Conversational format +triple_preference_example = { + "prompt": [{"role": "user", "content": "What color is the sky?"}], + "reference": [{"role": "assistant", "content": "It is a beautiful shade of blue."}], + "chosen": [{"role": "assistant", "content": "It is blue."}], + "rejected": [{"role": "assistant", "content": "It is green."}], +} +``` + +The reference response is typically the highest-quality completion available for the prompt; in the original TPO paper it is taken from the response with the highest score in [UltraFeedback](https://huggingface.co/datasets/openbmb/UltraFeedback), with the second-highest used as the chosen completion and the lowest as the rejected completion. + +## Example script + +We provide an example script to train a model using the TPO method. The script is available at [`examples/scripts/tpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/tpo.py). + +To test the TPO script with the [Qwen 3 0.6B model](https://huggingface.co/Qwen/Qwen3-0.6B) on a triple-preference dataset, run the following command: + +```bash +accelerate launch examples/scripts/tpo.py \ + --model_name_or_path Qwen/Qwen3-0.6B \ + --dataset_name tpo-alignment/triple-preference-ultrafeedback-40K \ + --beta 0.01 \ + --tpo_alpha 1.0 \ + --learning_rate 5e-7 \ + --num_train_epochs 1 \ + --output_dir Qwen3-0.6B-TPO +``` + +## Looking deeper into the TPO method + +Triple Preference Optimization (TPO) extends preference-based alignment from pairs to *triples* `(y_gold, y_chosen, y_rejected)`. The model is jointly optimized with two objectives in a single step: + +1. A **contrastive loss** between the chosen and rejected completions, similar in spirit to DPO/SimPO but computed directly from the policy log-probabilities (no separate reference policy is required). +2. A **supervised negative log-likelihood (NLL) loss** on the gold (`reference`) completion, weighted by `tpo_alpha`. This term replaces the standalone SFT stage typically required before DPO. + +The total TPO loss is: + +$$ +\mathcal{L}_{\mathrm{TPO}}(\theta) = \mathcal{L}_{\mathrm{contrast}}(\theta) + \alpha \cdot \mathcal{L}_{\mathrm{NLL}}(\theta; y_{\text{gold}}) +$$ + +where \\( \alpha \\) is `tpo_alpha` and \\( \mathcal{L}_{\mathrm{contrast}} \\) is selected via `loss_type`. + +### Loss types + +| `loss_type=` | Description | +| --- | --- | +| `"sigmoid"` (default) | Sigmoid loss on the (sum) log-probability difference between the chosen and rejected completions, as in the original [TPO](https://huggingface.co/papers/2405.16681) paper. | +| `"hinge"` | Hinge loss on the normalized likelihood from the [SLiC](https://huggingface.co/papers/2305.10425) paper. In this case, `beta` is the reciprocal of the margin. | +| `"ipo"` | IPO loss from the [IPO](https://huggingface.co/papers/2310.12036) paper, computed on length-normalized log-probabilities. | +| `"tpo-l"` | Length-normalized TPO variant: uses average per-token log-probabilities and adds a target reward margin `tpo_l_gamma` to the Bradley-Terry objective, in the spirit of [SimPO](https://huggingface.co/papers/2405.14734). | + +Setting `tpo_alpha=0.0` disables the NLL term entirely (the reference response is then unused, and the corresponding cross-entropy is skipped to save compute). + +## Logged metrics + +While training and evaluating we record the following metrics: + +* `loss`: The total TPO loss (contrastive + `tpo_alpha` × NLL) averaged over the current logging interval. +* `entropy`: The average entropy of the model's predicted token distribution over completion tokens. +* `mean_token_accuracy`: The proportion of completion tokens for which the model's top-1 prediction matches the chosen completion. +* `num_tokens`: The total number of tokens processed so far. +* `logits/chosen`: The average logit values assigned by the model to the tokens in the chosen completion. +* `logits/rejected`: The average logit values assigned by the model to the tokens in the rejected completion. +* `logps/chosen`: The average log-probability assigned by the model to the chosen completion. +* `logps/rejected`: The average log-probability assigned by the model to the rejected completion. +* `rewards/chosen`: The average implicit reward computed for the chosen completion, defined as \\( \beta \log \pi_{\theta}(y^{+}\!\mid x) \\). +* `rewards/rejected`: The average implicit reward computed for the rejected completion, defined as \\( \beta \log \pi_{\theta}(y^{-}\!\mid x) \\). +* `rewards/margins`: The average implicit reward margin between the chosen and rejected completions. +* `rewards/accuracies`: The proportion of examples where the implicit reward for the chosen completion is higher than that for the rejected completion. + +## TPOTrainer + +[[autodoc]] experimental.tpo.TPOTrainer + - train + - save_model + - push_to_hub + +## TPOConfig + +[[autodoc]] experimental.tpo.TPOConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/trackio_integration.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/trackio_integration.md new file mode 100644 index 0000000000000000000000000000000000000000..4e93120fe19a8dfe3443e791bff8d60350908b8b --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/trackio_integration.md @@ -0,0 +1,67 @@ +# Trackio Integration + +[Trackio](https://huggingface.co/docs/trackio) is a lightweight, free experiment tracking library built on top of **🤗 Datasets** and **🤗 Spaces**. It is the **recommended tracking solution for TRL** and comes natively integrated with all trainers. + +To enable logging, simply set `report_to="trackio"` in your training config: + +```python +from trl import SFTConfig # works with any trainer config (e.g. DPOConfig, GRPOConfig, etc.) + +training_args = SFTConfig( + ..., + report_to="trackio", # enable Trackio logging +) +``` + +## Organizing Your Experiments with Run Names and Projects + +By default, Trackio will generate a name to identify each run. However, we highly recommend setting a descriptive `run_name` to make it easier to organize experiments. For example: + +```python +from trl import SFTConfig + +training_args = SFTConfig( + ..., + report_to="trackio", + run_name="sft_qwen3-4b_lr2e-5_bs128", # descriptive run name +) +``` + +You can also group related experiments by project by setting the following environment variable: + +```bash +export TRACKIO_PROJECT="my_project" +``` + +## Hosting Your Logs on 🤗 Spaces + +Trackio has local-first design, meaning your logs stay on your machine. If you’d like to host them and deploy a dashboard on **🤗 Spaces**, set: + +```bash +export TRACKIO_SPACE_ID="username/space_id" +``` + +Running the following example: + +```python +import os +from trl import SFTConfig, SFTTrainer +from datasets import load_dataset + +os.environ["TRACKIO_SPACE_ID"] = "trl-lib/trackio" +os.environ["TRACKIO_PROJECT"] = "trl-documentation" + +trainer = SFTTrainer( + model="Qwen/Qwen3-0.6B", + train_dataset=load_dataset("trl-lib/Capybara", split="train"), + args=SFTConfig( + report_to="trackio", + run_name="sft_qwen3-0.6b_capybara", + ), +) +trainer.train() +``` + +will give you a hosted dashboard at https://huggingface.co/spaces/trl-lib/trackio. + + diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/unsloth_integration.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/unsloth_integration.md new file mode 100644 index 0000000000000000000000000000000000000000..0350bc21612580f6d333860872289e8f1b4b201c --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/unsloth_integration.md @@ -0,0 +1,125 @@ +# Unsloth Integration + +Unsloth is an open‑source framework for fine‑tuning and reinforcement learning that trains LLMs (like Llama, OpenAI gpt-oss, Mistral, Gemma, DeepSeek, and more) up to 2× faster with up to 80% less VRAM. Unsloth allows [training](https://huggingface.co/docs/trl/en/unsloth_integration#Training), evaluation, running and [deployment](https://huggingface.co/docs/trl/en/unsloth_integration#Saving-the-model) with other inference engines like llama.cpp, Ollama and vLLM. + +The library provides a streamlined, Hugging Face compatible workflow for training, evaluation, inference and deployment and is fully compatible with [`SFTTrainer`]. + +## Key Features + +- Training support for all transformer compatible models: Text-to-speech (TTS), multimodal, BERT, RL and more +- Supports full fine-tuning, pretraining, LoRA, QLoRA, 8-bit training & more +- Works on Linux, Windows, Colab, Kaggle; NVIDIA GPUs, soon AMD & Intel setups +- Supports most features TRL supports, including RLHF (GSPO, GRPO, DPO etc.) +- Hand-written Triton kernels and a manual backprop engine ensure no accuracy degradation (0% approximation error) + +## Installation + +### pip install + +Local Installation (Linux recommended): + +```sh +pip install unsloth +``` + +You can also install `unsloth` according to the [official documentation](https://docs.unsloth.ai/get-started/installing-+-updating). Once installed, you can incorporate unsloth into your workflow in a very simple manner; instead of loading [`~transformers.AutoModelForCausalLM`], you just need to load a `FastLanguageModel` as follows: + +```python +import torch +from trl import SFTConfig, SFTTrainer +from unsloth import FastLanguageModel + +max_length = 2048 # Supports automatic RoPE Scaling, so choose any number + +# Load model +model, tokenizer = FastLanguageModel.from_pretrained( + model_name="unsloth/mistral-7b", + max_seq_length=max_length, + dtype="auto", # For auto-detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+ + load_in_4bit=True, # Use 4bit quantization to reduce memory usage. Can be False +) + +# Do model patching and add fast LoRA weights +model = FastLanguageModel.get_peft_model( + model, + r=16, + target_modules=[ + "q_proj", + "k_proj", + "v_proj", + "o_proj", + "gate_proj", + "up_proj", + "down_proj", + ], + lora_alpha=16, + lora_dropout=0, # Dropout = 0 is currently optimized + bias="none", # Bias = "none" is currently optimized + use_gradient_checkpointing=True, + random_state=3407, +) + +training_args = SFTConfig(output_dir="./output", max_length=max_length) + +trainer = SFTTrainer( + model=model, + args=training_args, + train_dataset=dataset, +) +trainer.train() +``` + +The saved model is fully compatible with Hugging Face's transformers library. Learn more about unsloth in their [official repository](https://github.com/unslothai/unsloth). + +### Docker Install + +```sh +docker run -d -e JUPYTER_PASSWORD="mypassword" \ + -p 8888:8888 -p 2222:22 \ + -v $(pwd)/work:/workspace/work \ + --gpus all \ + unsloth/unsloth +``` + +Access Jupyter Lab at ```http://localhost:8888``` and start fine-tuning! + +## Training + +These are some core settings you can toggle before training: + +- ```max_seq_length = 2048``` – Controls context length. While Llama-3 supports 8192, we recommend 2048 for testing. Unsloth enables 4× longer context fine-tuning. +- ```dtype = "auto"``` – For auto-detection; use torch.float16 or torch.bfloat16 for newer GPUs. +- ```load_in_4bit = True``` – Enables 4-bit quantization, reducing memory use 4× for fine-tuning. Disabling it allows for LoRA 16-bit fine-tuning to be enabled. +- To enable full fine-tuning (FFT), set ```full_finetuning = True```. For 8-bit fine-tuning, set ```load_in_8bit = True```. Note: Only one training method can be set to True at a time. + +For more information on configuring Unsloth's hyperparameters and features, read their [documentation guide here](https://docs.unsloth.ai/get-started/fine-tuning-llms-guide). + +## Saving the model + +Unsloth allows you to directly save the finetuned model as a small file called a LoRA adapter. You can instead push to the Hugging Face hub as well if you want to upload your model! Remember to get a [Hugging Face token](https://huggingface.co/settings/tokens) and add your token! + +### Saving to GGUF + +To save to GGUF, Unsloth uses llama.cpp. To save locally: + +```python +model.save_pretrained_gguf("directory", tokenizer, quantization_method = "q4_k_m") +model.save_pretrained_gguf("directory", tokenizer, quantization_method = "q8_0") +model.save_pretrained_gguf("directory", tokenizer, quantization_method = "f16") +``` + +To push to the hub: + +```python +model.push_to_hub_gguf("hf_username/directory", tokenizer, quantization_method = "q4_k_m") +model.push_to_hub_gguf("hf_username/directory", tokenizer, quantization_method = "q8_0") +``` + +### Saving to vLLM + +To save to 16-bit for vLLM, use: + +```python +model.save_pretrained_merged("model", tokenizer, save_method = "merged_16bit",) +model.push_to_hub_merged("hf/model", tokenizer, save_method = "merged_16bit", token = "") +``` diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/usage_stats.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/usage_stats.md new file mode 100644 index 0000000000000000000000000000000000000000..6c297f6cbafe02592b172cf088b12a871946f62a --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/usage_stats.md @@ -0,0 +1,39 @@ +# Usage Stats Collection + +TRL collects anonymous usage statistics to help the maintainers understand which trainers, model architectures, and hardware configurations are used in the wild. This data informs prioritization decisions about which features to invest in and which to deprecate. + +## What is collected + +A single ping is sent each time a trainer is instantiated. The payload contains: + +- TRL version (e.g. `1.5.0`) +- Trainer class name, reported only if it is a TRL-defined trainer (e.g. `SFTTrainer`, `GRPOTrainer`). Custom user subclasses are reported as `other`. +- Model architecture, reported only if it is a model type known to [`transformers`](https://github.com/huggingface/transformers) (e.g. `llama`, `qwen3`). Custom or private architectures are reported as `other`. +- Whether [PEFT](https://github.com/huggingface/peft) is in use +- Distributed backend (`deepspeed`, `fsdp`, `ddp`, or `none`) +- World size, bucketed (`1`, `2-8`, `9-64`, `65+`) +- Accelerator type (`cuda`, `xpu`, `npu`, `mlu`, `mps`, `cpu`) +- GPU model name (e.g. `NVIDIA H100 80GB HBM3`), when available + +No dataset names, file paths, model identifiers, hyperparameter values, or any other user-provided data are collected. As with any HTTP request, the source IP and standard HTTP headers are visible to the server. + +Telemetry is not sent in CI environments (i.e. when the `CI` environment variable is set), nor in offline mode. + +## How to opt out + +Set either of the following environment variables to disable telemetry: + +```bash +export HF_HUB_DISABLE_TELEMETRY=1 # disables telemetry for all HF libraries +export HF_HUB_OFFLINE=1 # disables all network calls to the Hub +``` + +## Why this helps + +Without usage data, the maintainers have no way to know which parts of the library matter to users. Telemetry lets us answer questions like: + +- Which trainers are widely adopted, and which can be deprecated safely? +- Which model architectures are most often fine-tuned with TRL, so we can prioritize their support? +- What hardware configurations are users running on, so we can test and optimize for them? + +If you find TRL useful, leaving telemetry enabled is a low-cost way to help us make it better. diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/use_model.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/use_model.md new file mode 100644 index 0000000000000000000000000000000000000000..fb12e4df92a637326b04a409edd0930c4d57df38 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/use_model.md @@ -0,0 +1,58 @@ +# Use model after training + +Once you have trained a model using either the SFTTrainer, PPOTrainer, or DPOTrainer, you will have a fine-tuned model that can be used for text generation. In this section, we'll walk through the process of loading the fine-tuned model and generating text. If you need to run an inference server with the trained model, you can explore libraries such as [`text-generation-inference`](https://github.com/huggingface/text-generation-inference). + +## Load and Generate + +If you have fine-tuned a model fully, meaning without the use of PEFT you can simply load it like any other language model in transformers. E.g. the value head that was trained during the PPO training is no longer needed and if you load the model with the original transformer class it will be ignored: + +```python +from transformers import AutoTokenizer, AutoModelForCausalLM + +model_name_or_path = "Qwen/Qwen3-0.6B" #path/to/your/model/or/name/on/hub +device = "cpu" # or "cuda" if you have a GPU + +model = AutoModelForCausalLM.from_pretrained(model_name_or_path).to(device) +tokenizer = AutoTokenizer.from_pretrained(model_name_or_path) + +inputs = tokenizer.encode("This movie was really", return_tensors="pt").to(device) +outputs = model.generate(inputs) +print(tokenizer.decode(outputs[0])) +``` + +Alternatively you can also use the pipeline: + +```python +from transformers import pipeline + +model_name_or_path = "Qwen/Qwen3-0.6B" #path/to/your/model/or/name/on/hub +pipe = pipeline("text-generation", model=model_name_or_path) +print(pipe("This movie was really")[0]["generated_text"]) +``` + +## Use Adapters PEFT + +```python +from peft import PeftConfig, PeftModel +from transformers import AutoModelForCausalLM, AutoTokenizer + +base_model_name = "Qwen/Qwen3-0.6B" #path/to/your/model/or/name/on/hub +adapter_model_name = "path/to/my/adapter" + +model = AutoModelForCausalLM.from_pretrained(base_model_name) +model = PeftModel.from_pretrained(model, adapter_model_name) + +tokenizer = AutoTokenizer.from_pretrained(base_model_name) +``` + +You can also merge the adapters into the base model so you can use the model like a normal transformers model, however the checkpoint will be significantly bigger: + +```python +model = AutoModelForCausalLM.from_pretrained(base_model_name) +model = PeftModel.from_pretrained(model, adapter_model_name) + +model = model.merge_and_unload() +model.save_pretrained("merged_adapters") +``` + +Once you have the model loaded and either merged the adapters or keep them separately on top you can run generation as with a normal model outlined above. diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/vllm_integration.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/vllm_integration.md new file mode 100644 index 0000000000000000000000000000000000000000..7d3aa5f6de95a20fa1749ea86c01ed910235da76 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/vllm_integration.md @@ -0,0 +1,430 @@ +# vLLM Integration + +This document will guide you through the process of using vLLM with TRL for faster generation in online methods like GRPO and Online DPO. We first summarize a tl;dr on how to use vLLM with TRL, and then we will go into the details of how it works under the hood. + +> [!WARNING] +> TRL currently only supports vLLM versions from `0.13.0` to `0.23.0`. Please ensure you have a version in this range installed to avoid compatibility issues. + +> [!TIP] +> The following trainers currently support generation with vLLM: +> +> - [`GRPOTrainer`] +> - [`RLOOTrainer`] +> - [`experimental.nash_md.NashMDTrainer`] +> - [`experimental.online_dpo.OnlineDPOTrainer`] +> - [`experimental.xpo.XPOTrainer`] + +## 🚀 How can I use vLLM with TRL to speed up training? + +💡 **Note**: Resources required for this specific example: a single node with 8 GPUs. + +> [!WARNING] +> When using vLLM with TRL, the **vLLM server** and the **trainer** must run on **separate CUDA devices** to prevent conflicts. +> For guidance on configuring this properly, see [Modes of using vLLM during training](#modes-of-using-vllm-during-training). + +First, install vLLM using the following command: + +```bash +pip install "trl[vllm]" +``` + +Then run the server on specific GPUs (e.g., GPUs 0-3): + +```sh +CUDA_VISIBLE_DEVICES=0,1,2,3 trl vllm-serve --model Qwen/Qwen2.5-7B --tensor-parallel-size 4 +``` + +Once the server is running, you can use it to generate completions for training. In the example below, we are using the different supported trainers using the vLLM server for generation. The `--tensor-parallel-size` and `--data-parallel-size` arguments control how the model and data are sharded across GPUs. + +In this example, we shard one model across 4 GPUs with tensor parallelism. Then, run the training script on different GPUs (e.g., GPUs 4-7) by passing `use_vllm=True` in the training arguments as follows: + +Sample of a simple `train.py` script: + + + + +```python +from datasets import load_dataset +from trl import GRPOTrainer, GRPOConfig +from trl.rewards import accuracy_reward + +dataset = load_dataset("trl-lib/DeepMath-103K", split="train") + +trainer = GRPOTrainer( + model="Qwen/Qwen2.5-7B", + args=GRPOConfig(use_vllm=True, vllm_mode="server"), + reward_funcs=accuracy_reward, + train_dataset=dataset, +) + +trainer.train() +``` + + + + +```python +from datasets import load_dataset +from trl.experimental.online_dpo import OnlineDPOConfig, OnlineDPOTrainer +from trl.rewards import accuracy_reward + +dataset = load_dataset("trl-lib/DeepMath-103K", split="train") + +trainer = OnlineDPOTrainer( + model="Qwen/Qwen2.5-7B", + args=OnlineDPOConfig(use_vllm=True, vllm_mode="server"), + reward_funcs=accuracy_reward, + train_dataset=dataset, +) + +trainer.train() +``` + + + + +```python +from datasets import load_dataset +from trl.experimental.nash_md import NashMDConfig, NashMDTrainer +from trl.rewards import accuracy_reward + +dataset = load_dataset("trl-lib/DeepMath-103K", split="train") + +trainer = NashMDTrainer( + model="Qwen/Qwen2.5-7B", + args=NashMDConfig(use_vllm=True, vllm_mode="server"), + reward_funcs=accuracy_reward, + train_dataset=dataset, +) + +trainer.train() +``` + + + + +```python +from datasets import load_dataset +from trl.experimental.xpo import XPOTrainer, XPOConfig +from trl.rewards import accuracy_reward + +dataset = load_dataset("trl-lib/DeepMath-103K", split="train") + +trainer = XPOTrainer( + model="Qwen/Qwen2.5-7B", + args=XPOConfig(use_vllm=True, vllm_mode="server"), + reward_funcs=accuracy_reward, + train_dataset=dataset, +) + +trainer.train() +``` + + + + +```python +from datasets import load_dataset +from trl import RLOOTrainer, RLOOConfig +from trl.rewards import accuracy_reward + +dataset = load_dataset("trl-lib/DeepMath-103K", split="train") + +trainer = RLOOTrainer( + model="Qwen/Qwen2.5-7B", + args=RLOOConfig(use_vllm=True, vllm_mode="server"), + reward_funcs=accuracy_reward, + train_dataset=dataset, +) + +trainer.train() +``` + + + + +And the train command on separate GPUs from the server: + +```sh +CUDA_VISIBLE_DEVICES=4,5,6,7 accelerate launch train.py +``` + +## Why using vLLM? + +### 🎬 Flashback: Why do we need to use vLLM in online methods? + +Online methods like GRPO or Online DPO require the model to generate completions during training, which are then used to compute reward signals. However, generation can be extremely time-consuming, especially with large or reasoning models. In the default setup (without vLLM), completions are generated using the [(unwrapped) model's `generate` method](https://github.com/huggingface/trl/blob/f3e8c2304428ef16e9ae5de9e5741ed84d533b7b/trl/trainer/grpo_trainer.py#L965C39-L965C66). This approach quickly becomes a major bottleneck — generation is slow and inefficient, particularly for large batches or models. As a result, training times increase significantly, and overall efficiency drops. To address this, we turn to vLLM, which enables much faster and more scalable generation, helping eliminate this bottleneck in online methods. + +### 🤔 How does vLLM solve the slow generation issue? + +If you've ever done autoregressive decoder training, you know all the input tokens to the LLM produce their attention key and value tensors, and these tensors are kept in GPU memory to later generate subsequent tokens based on them. These cached key and value tensors are often referred to as the KV cache. However, storing the KV cache occupies a lot of memory, so vLLM uses a technique called **PagedAttention** to solve this problem. PagedAttention, which is inspired by the OS’s virtual memory concept, stores continuous keys and values in **non-contiguous memory space**, which is much more efficient. The details of this are beyond the scope of this document, but in short, it allows the model to store the keys and values in a more efficient way, reducing the memory footprint and speeding up the generation process. If you are interested, make sure to check out the [vLLM PagedAttention](https://blog.vllm.ai/2023/06/20/vllm.html) for more details. + +## How vLLM Works (Under the Hood) 🔍 + +### 🤔 What exactly happens when you run `trl vllm-serve --model `? + +When you run for example + +```sh +CUDA_VISIBLE_DEVICES=0,1,2,3 trl vllm-serve --model Qwen/Qwen2.5-7B --tensor-parallel-size 4 +``` + +1. vLLM first spawns multiple workers to handle incoming requests in parallel. The number of workers is determined by multiplying the `--tensor-parallel-size` and `--data-parallel-size` values. In this example, it spawns 4 workers (4 × 1). +Each worker operates independently and processes a chunk of the incoming requests — which are basically the prompts sent to the server for generation. + +2. Once the incoming requests (prompts) are distributed across the workers, the model starts generating completions. Internally, the model’s weights are split across multiple GPUs based on the `--tensor-parallel-size` argument — this is how tensor parallelism is handled. + +3. Although the GPUs process requests independently and in parallel, they still need to communicate with each other. Remember that each GPU handles only a slice of the incoming prompts (for example, with 4 GPUs and 8 prompts using `--tensor-parallel-size=4`, each GPU participates in serving the full model). +This GPU-to-GPU communication is managed efficiently by NVIDIA’s NCCL library. The communication mainly ensures that each GPU gets its correct portion of the incoming requests — it’s lightweight and doesn’t interfere with generation itself. +Separately, the number of completions to generate per prompt is controlled by the `num_generations` setting in the GRPO config. For instance, if you set `num_generations=2` (like in the picture above), each prompt will have 2 completions. So, with 8 prompts and `num_generations=2`, you would end up with 16 completions total — regardless of the number of GPUs or parallelism settings. + +### 🥸 More detail on what happens under the hood when running the server + +- The vLLM server starts by running the command: `trl vllm-serve --model Qwen/Qwen2.5-7B`. +- Once the server is running, it generates completions based on requests from the client (trainer) using `vllm_client.generate` [these lines](https://github.com/huggingface/trl/blob/cc044e35b285be7dc062764b3364e1e684db4c7c/trl/trainer/grpo_trainer.py#L1025-L1035). +- The client (trainer) then requests these completions from the server. +- These completions are used to compute the reward signal. +- Based on the reward signal and the model’s output, the loss is computed, and the backward pass is performed to update the model’s weights. +- **Note**: The server only handles completion generation — it doesn’t train the model. Therefore, the model’s weights aren’t updated on the server. Once the backward pass is complete, the client sends the updated weights to the server using `vllm_client.update_named_param(name, param.data)`. + +When using vLLM, ensure the GPUs assigned for training and generation are separate to avoid NCCL communication conflicts. If you do not set the `CUDA_VISIBLE_DEVICES` environment variable, the training script will use all available GPUs by default, which may lead to device conflicts. Starting from TRL next release after v0.19.1, the code automatically detects and prevents same-device usage, raising a error at the vllm server process: + +```log +RuntimeError: Attempting to use the same CUDA device for multiple distinct roles/ranks within the same communicator. +Ensure that trainer is using different devices than vLLM server. +``` + +For example, if you want to use GPUs 4–7 for training while the server runs on GPUs 0-3, set: + +```sh +CUDA_VISIBLE_DEVICES=4,5,6,7 accelerate launch train.py +``` + +## Advanced usage + +### 🍷 More customization options with vLLM? + +You can customize the server configuration by passing additional arguments. + +```txt +$ trl vllm-serve --help +usage: trl vllm-serve [-h] --model MODEL [--revision REVISION] [--tensor_parallel_size TENSOR_PARALLEL_SIZE] [--data_parallel_size DATA_PARALLEL_SIZE] [--host HOST] + [--port PORT] [--gpu_memory_utilization GPU_MEMORY_UTILIZATION] [--dtype DTYPE] [--max_model_len MAX_MODEL_LEN] + [--enable_prefix_caching ENABLE_PREFIX_CACHING] [--enforce_eager [ENFORCE_EAGER]] [--kv_cache_dtype KV_CACHE_DTYPE] + [--trust_remote_code [TRUST_REMOTE_CODE]] [--log_level LOG_LEVEL] [--vllm_model_impl VLLM_MODEL_IMPL] + +options: + -h, --help show this help message and exit + --model MODEL Model name or path to load the model from. (default: None) + --revision REVISION Revision to use for the model. If not specified, the default branch will be used. (default: None) + --tensor_parallel_size TENSOR_PARALLEL_SIZE, --tensor-parallel-size TENSOR_PARALLEL_SIZE + Number of tensor parallel workers to use. (default: 1) + --data_parallel_size DATA_PARALLEL_SIZE, --data-parallel-size DATA_PARALLEL_SIZE + Number of data parallel workers to use. For dense models, keep this at 1. Starting from vLLM `0.14.0`, setting + this above `1` for dense models is no longer supported/useful and will error out (see vLLM PR #30739). + (default: 1) + --host HOST Host address to run the server on. (default: 0.0.0.0) + --port PORT Port to run the server on. (default: 8000) + --gpu_memory_utilization GPU_MEMORY_UTILIZATION, --gpu-memory-utilization GPU_MEMORY_UTILIZATION + Ratio (between 0 and 1) of GPU memory to reserve for the model weights, activations, and KV cache on the device dedicated to generation + powered by vLLM. Higher values will increase the KV cache size and thus improve the model's throughput. However, if the value is too high, + it may cause out-of-memory (OOM) errors during initialization. (default: 0.9) + --dtype DTYPE Data type to use for vLLM generation. If set to 'auto', the data type will be automatically determined based on the model configuration. + Find the supported values in the vLLM documentation. (default: auto) + --max_model_len MAX_MODEL_LEN, --max-model-len MAX_MODEL_LEN + If set, the `max_model_len` to use for vLLM. This can be useful when running with reduced `vllm_gpu_memory_utilization`, leading to a + reduced KV cache size. If not set, vLLM will use the model context size, which might be much larger than the KV cache, leading to + inefficiencies. (default: None) + --enable_prefix_caching ENABLE_PREFIX_CACHING, --enable-prefix-caching ENABLE_PREFIX_CACHING + Whether to enable prefix caching in vLLM. If set to `True`, ensure that the model and the hardware support this feature. (default: None) + --enforce_eager [ENFORCE_EAGER], --enforce-eager [ENFORCE_EAGER] + Whether to enforce eager execution. If set to `True`, we will disable CUDA graph and always execute the model in eager mode. If `False` + (default behavior), we will use CUDA graph and eager execution in hybrid. (default: False) + --kv_cache_dtype KV_CACHE_DTYPE, --kv-cache-dtype KV_CACHE_DTYPE + Data type to use for KV cache. If set to 'auto', the dtype will default to the model data type. (default: auto) + --trust_remote_code [TRUST_REMOTE_CODE], --trust-remote-code [TRUST_REMOTE_CODE] + Whether to trust remote code when loading models. Set to True to allow executing code from model repositories. This is required for some + custom models but introduces security risks. (default: False) + --log_level LOG_LEVEL, --log-level LOG_LEVEL + Log level for uvicorn. Possible choices: 'critical', 'error', 'warning', 'info', 'debug', 'trace'. (default: info) + --vllm_model_impl VLLM_MODEL_IMPL, --vllm-model-impl VLLM_MODEL_IMPL + Model implementation to use for vLLM. Must be one of `transformers` or `vllm`. `transformers`: Use the `transformers` backend for model + implementation. `vllm`: Use the `vllm` library for model implementation. (default: vllm) +``` + +### 💆🏻‍♀️ What's the best distributed setup? + +![tp dp throughput 8 gpus](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/tp_dp_throughput_8_gpus.png) +![tp dp throughput 4 gpus](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/tp_dp_throughput_4_gpus.png) + +> [!WARNING] +> The benchmark plots above were collected with older vLLM versions. Starting with [vLLM PR #30739](https://github.com/vllm-project/vllm/pull/30739) (released in `0.14.0`), offline data parallel scaling for non-MoE (dense) models is no longer supported. To follow the latest recommendations, do not scale DP for non-MoE models. + +### vLLM with Transformers Backend + +vLLM can use the **Transformers backend** for model implementations, which works for both LLMs and VLMs. +To enable this, set `vllm_model_impl="transformers"` in your configuration or pass it via the command-line argument. + +For more details, check out [vLLM Transformers Backend](https://blog.vllm.ai/2025/04/11/transformers-backend.html). + +Example: + +```sh +CUDA_DEVICE_ORDER=PCI_BUS_ID CUDA_VISIBLE_DEVICES=0 trl vllm-serve --model Qwen/Qwen +2.5-VL-3B-Instruct --tensor-parallel-size 1 --port 8000 --enforce_eager --vllm_model_impl transformers +``` + +### Modes of Using vLLM During Training + +TRL supports **two modes** for integrating vLLM during training: **colocate mode** (default) and **server mode**. + +#### Colocate Mode + +In **colocate mode**, vLLM runs inside the trainer process and shares GPU memory with the training model. +This avoids launching a separate server and can improve GPU utilization, but may lead to memory contention on the training GPUs. This is the default mode. + +Example configuration: + + + + +```python +from trl import GRPOConfig + +training_args = GRPOConfig( + ..., + use_vllm=True, # vllm_mode="colocate" by default +) +``` + + + + +```python +from trl.experimental.online_dpo import OnlineDPOConfig + +training_args = OnlineDPOConfig( + ..., + use_vllm=True, # vllm_mode="colocate" by default +) +``` + + + + +```python +from trl.experimental.nash_md import NashMDConfig + +training_args = NashMDConfig( + ..., + use_vllm=True, # vllm_mode="colocate" by default +) +``` + + + + +```python +from trl.experimental.xpo import XPOConfig + +training_args = XPOConfig( + ..., + use_vllm=True, # vllm_mode="colocate" by default +) +``` + + + + +```python +from trl import RLOOConfig + +training_args = RLOOConfig( + ..., + use_vllm=True, # vllm_mode="colocate" by default +) +``` + + + + +#### Server Mode + +In **server mode**, vLLM runs as a separate process on dedicated GPUs and communicates with the trainer via HTTP. +This setup is ideal if you have GPUs dedicated to inference. + +Example configuration: + + + + +```python +from trl import GRPOConfig + +training_args = GRPOConfig( + ..., + use_vllm=True, + vllm_mode="server", +) +``` + + + + +```python +from trl.experimental.online_dpo import OnlineDPOConfig + +training_args = OnlineDPOConfig( + ..., + use_vllm=True, + vllm_mode="server", +) +``` + + + + +```python +from trl.experimental.nash_md import NashMDConfig + +training_args = NashMDConfig( + ..., + use_vllm=True, + vllm_mode="server", +) +``` + + + + +```python +from trl.experimental.xpo import XPOConfig + +training_args = XPOConfig( + ..., + use_vllm=True, + vllm_mode="server", +) +``` + + + + +```python +from trl import RLOOConfig + +training_args = RLOOConfig( + ..., + use_vllm=True, + vllm_mode="server", +) +``` + + + + +> [!WARNING] +> Check the documentation of the trainer you are using for specific details on vLLM usage and parameters. + +> [!WARNING] +> To reduce GPU memory usage when running vLLM, consider [enabling vLLM sleep mode](reducing_memory_usage#vllm-sleep-mode). diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/xpo_trainer.md b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/xpo_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..428c4432ea0642150e9a399fc444cd0b55129298 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/docs/source/xpo_trainer.md @@ -0,0 +1,145 @@ +# XPO Trainer + +[![model badge](https://img.shields.io/badge/All_models-XPO-blue)](https://huggingface.co/models?other=xpo,trl) + +## Overview + +Exploratory Preference Optimization (XPO) was proposed in the paper [Exploratory Preference Optimization: Harnessing Implicit Q*-Approximation for Sample-Efficient RLHF](https://huggingface.co/papers/2405.21046) by Tengyang Xie, Dylan J. Foster, Akshay Krishnamurthy, [Corby Rosset](https://huggingface.co/corbyrosset), [Ahmed Awadallah](https://huggingface.co/AhmedAwadallah), and Alexander Rakhlin. It is a simple online preference tuning method based on the DPO loss together with a reward model (RM). XPO augments the DPO objective with an exploration bonus allowing the method to explore outside the support of the initial model and human feedback data. + +The abstract from the paper is the following: + +> Reinforcement learning from human feedback (RLHF) has emerged as a central tool for language model alignment. We consider online exploration in RLHF, which exploits interactive access to human or AI feedback by deliberately encouraging the model to produce diverse, maximally informative responses. By allowing RLHF to confidently stray from the pre-trained model, online exploration offers the possibility of novel, potentially super-human capabilities, but its full potential as a paradigm for language model training has yet to be realized, owing to computational and statistical bottlenecks in directly adapting existing reinforcement learning techniques. We propose a new algorithm for online exploration in RLHF, Exploratory Preference Optimization (XPO), which is simple and practical -- a one-line change to (online) Direct Preference Optimization (DPO; Rafailov et al., 2023) -- yet enjoys the strongest known provable guarantees and promising empirical performance. XPO augments the DPO objective with a novel and principled exploration bonus, empowering the algorithm to explore outside the support of the initial model and human feedback data. In theory, we show that XPO is provably sample-efficient and converges to a near-optimal language model policy under natural exploration conditions, irrespective of whether the initial model has good coverage. Our analysis, which builds on the observation that DPO implicitly performs a form of Q*-approximation (or, Bellman error minimization), combines previously disparate techniques from language modeling and theoretical reinforcement learning in a serendipitous fashion through the perspective of KL-regularized Markov decision processes. Empirically, we find that XPO is more sample-efficient than non-exploratory DPO variants in a preliminary evaluation. + +This post-training method was contributed by [Kashif Rasul](https://huggingface.co/kashif), [Quentin Gallouédec](https://huggingface.co/qgallouedec) and [Lewis Tunstall](https://huggingface.co/lewtun). + +> [!NOTE] +> XPO is currently experimental. The API may change without notice while the feature is iterated on. + +## Quick start + +This example demonstrates how to train a model using the XPO method. We use the [Qwen 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) as the base model and the [trl-lib/Qwen2-0.5B-Reward](https://huggingface.co/trl-lib/Qwen2-0.5B-Reward) reward model. We use the prompts from the [UltraFeedback dataset](https://huggingface.co/datasets/openbmb/UltraFeedback). You can view the prompts in the dataset here: + + +Below is the script to train the model: + +```python +# train_xpo.py +from datasets import load_dataset +from trl.experimental.xpo import XPOConfig, XPOTrainer +from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer + +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +reward_model = AutoModelForSequenceClassification.from_pretrained("trl-lib/Qwen2-0.5B-Reward", num_labels=1) +train_dataset = load_dataset("trl-lib/ultrafeedback-prompt", split="train") + +training_args = XPOConfig(output_dir="Qwen2-0.5B-XPO") +trainer = XPOTrainer( + model=model, reward_funcs=reward_model, args=training_args, processing_class=tokenizer, train_dataset=train_dataset +) +trainer.train() +``` + +Execute the script using the following command: + +```bash +accelerate launch train_xpo.py +``` + +Distributed across 8 GPUs, the training takes approximately 1 hour. + +To see how the [trained model](https://huggingface.co/trl-lib/Qwen2-0.5B-XPO) performs, you can use the [Transformers Chat CLI](https://huggingface.co/docs/transformers/quicktour#chat-with-text-generation-models). + +
$ transformers chat trl-lib/Qwen2-0.5B-XPO
+<quentin_gallouedec>:
+What is the best programming language?
+
+<trl-lib/Qwen2-0.5B-XPO>:
+The best programming language depends on individual preferences and familiarity with coding concepts. Some popular languages include Python, Java, C++, and JavaScript.
+
+ +## Expected dataset type + +XPO requires a [prompt-only dataset](dataset_formats#prompt-only). The [`experimental.xpo.XPOTrainer`] supports both [conversational](dataset_formats#conversational) and [standard](dataset_formats#standard) dataset format. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset. + +## Usage tips + +### Encourage EOS token generation + +When using a reward model, we may want the model to generate completions within a given length. During training, the model will generate completions up to the maximum length specified in the `max_new_tokens` argument of [`experimental.xpo.XPOConfig`]. If you want to penalize the model for not generating an EOS token before reaching the maximum length, you can use the `missing_eos_penalty` argument of [`experimental.xpo.XPOConfig`]: + +```python +training_args = XPOConfig(..., max_new_tokens=128, missing_eos_penalty=1.0) +``` + +> [!WARNING] +> Make sure that the SFT model and reward model use the _same_ chat template and the same tokenizer. Otherwise, you may find the model completions are scored incorrectly during training. + +### Logging Completions + +To better understand your model's behavior during training, you can log sample completions periodically using the [`LogCompletionsCallback`]. + +```python +trainer = XPOTrainer(..., eval_dataset=eval_dataset) +completions_callback = LogCompletionsCallback(trainer, num_prompts=8) +trainer.add_callback(completions_callback) +``` + +This callback logs the model's generated completions directly to Weights & Biases. + +![Logged Completions](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/wandb_completions.png) + +## Example script + +We provide an example script to train a model using the XPO method. The script is available in [`examples/scripts/xpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/xpo.py) + +To test the XPO script with the [Qwen2.5 0.5B model](https://huggingface.co/trl-lib/Qwen/Qwen2.5-0.5B-Instruct) on the [UltraFeedback dataset](https://huggingface.co/datasets/openbmb/UltraFeedback), run the following command: + +```bash +python examples/scripts/xpo.py \ + --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ + --reward_model_path trl-lib/Qwen2-0.5B-Reward \ + --dataset_name trl-lib/ultrafeedback-prompt \ + --learning_rate 5.0e-7 \ + --output_dir Qwen2.5-0.5B-XPO \ + --warmup_steps 0.1 \ + --push_to_hub +``` + +## Logged metrics + +While training and evaluating we record the following reward metrics: + +* `loss/xpo`: The mean xpo part of the full loss. +* `loss/dpo`: The mean dpo part of the full loss. +* `objective/kl`: The mean KL divergence between the model and reference data. +* `objective/entropy`: The mean entropy of the model and reference data. +* `objective/model_scores`: The mean scores (according to the reward model) of the model completions. +* `objective/ref_scores`: The mean scores (according to the reward model) of the reference completions. +* `objective/scores_margin`: The mean score margin (according to the external reward model) between the chosen and rejected completions. +* `rewards/chosen`: The mean reward (according to XPO's DPO implicit reward model) of the chosen completions. +* `rewards/rejected`: The mean reward (according to XPO's DPO implicit reward model) of the rejected completions. +* `rewards/accuracies`: The accuracies of the XPO's implicit reward model. +* `rewards/margins`: The mean reward margin (according to online DPO's implicit reward model) between the chosen and rejected completions. +* `logps/chosen`: The mean log probabilities of the chosen completions. +* `logps/rejected`: The mean log probabilities of the rejected completions. +* `val/model_contain_eos_token`: The amount of times the model's output contains the eos token. +* `val/ref_contain_eos_token`: The amount of times the reference's output contains the eos token. +* `alpha`: The weight of the XPO loss term. Typically fixed, but can be made dynamic by passing a list to [`experimental.xpo.XPOConfig`]. +* `beta`: The parameter that controls the weight of the loss term representing the deviation from the reference model. Typically fixed, but can be made dynamic by passing a list to [`experimental.xpo.XPOConfig`]. + +## XPOTrainer + +[[autodoc]] experimental.xpo.XPOTrainer + - train + - save_model + - push_to_hub + +## XPOConfig + +[[autodoc]] experimental.xpo.XPOConfig diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/examples/README.md b/tasks/tasksmith-b3c12843c3fb/tests/source/examples/README.md new file mode 100644 index 0000000000000000000000000000000000000000..785826dfd3741f30857f85109e95995679a2b581 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/examples/README.md @@ -0,0 +1,3 @@ +# Examples + +Please check out https://huggingface.co/docs/trl/example_overview for documentation on our examples. diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/alst_ulysses_4gpu.yaml b/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/alst_ulysses_4gpu.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e6c7cfa8125e78cfdbb45c6a260be7a03b4bd057 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/alst_ulysses_4gpu.yaml @@ -0,0 +1,45 @@ +# ALST/Ulysses Sequence Parallelism with 2D Parallelism (DP + SP) for 4 GPUs +# +# This configuration enables 2D parallelism: +# - Sequence Parallelism (sp_size=2): Sequences split across 2 GPUs using ALST/Ulysses +# - Data Parallelism (dp_shard_size=2): Model/optimizer sharded across 2 GPUs +# - Total: 4 GPUs (2 × 2) +# +# Set parallelism_config in your training script: +# parallelism_config = ParallelismConfig( +# sp_backend="deepspeed", +# sp_size=2, +# dp_shard_size=2, # Calculated as: num_gpus // sp_size +# sp_handler=DeepSpeedSequenceParallelConfig(...) +# ) + +compute_environment: LOCAL_MACHINE +debug: false +deepspeed_config: + zero_stage: 3 + seq_parallel_communication_data_type: bf16 + offload_optimizer_device: none + offload_param_device: none + zero3_init_flag: true + zero3_save_16bit_model: true +distributed_type: DEEPSPEED +downcast_bf16: 'no' +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 4 # Total number of GPUs +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false +parallelism_config: + parallelism_config_dp_replicate_size: 1 + parallelism_config_dp_shard_size: 2 # Enables 2D parallelism with SP + parallelism_config_tp_size: 1 + parallelism_config_sp_size: 2 # Sequence parallel size + parallelism_config_sp_backend: deepspeed + parallelism_config_sp_seq_length_is_variable: true + parallelism_config_sp_attn_implementation: flash_attention_2 diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/context_parallel_2gpu.yaml b/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/context_parallel_2gpu.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e45a62ba2edde9633350260b01ff71cca2a89d3e --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/context_parallel_2gpu.yaml @@ -0,0 +1,30 @@ +# Context Parallelism with FSDP for 2 GPUs +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: FSDP +downcast_bf16: 'no' +enable_cpu_affinity: false +fsdp_config: + fsdp_activation_checkpointing: true # Enable activation checkpointing for memory efficiency + fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP + fsdp_cpu_ram_efficient_loading: true + fsdp_offload_params: false + fsdp_reshard_after_forward: true + fsdp_state_dict_type: FULL_STATE_DICT + fsdp_version: 2 +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 2 # Number of GPUs +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false +parallelism_config: + parallelism_config_dp_replicate_size: 1 + parallelism_config_dp_shard_size: 1 + parallelism_config_tp_size: 1 + parallelism_config_cp_size: 2 # Context parallel size diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/deepspeed_zero1.yaml b/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/deepspeed_zero1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d5b5f782fb30f9fcbcc8fc58262f09eaf2e10368 --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/deepspeed_zero1.yaml @@ -0,0 +1,20 @@ +compute_environment: LOCAL_MACHINE +debug: false +deepspeed_config: + deepspeed_multinode_launcher: standard + gradient_accumulation_steps: 1 + zero3_init_flag: false + zero_stage: 1 +distributed_type: DEEPSPEED +downcast_bf16: 'no' +machine_rank: 0 +main_training_function: main +mixed_precision: 'bf16' +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/deepspeed_zero2.yaml b/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/deepspeed_zero2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..239b14ac3a9ae8de73122d1154bf0d71903dc15f --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/deepspeed_zero2.yaml @@ -0,0 +1,21 @@ +compute_environment: LOCAL_MACHINE +debug: false +deepspeed_config: + deepspeed_multinode_launcher: standard + offload_optimizer_device: none + offload_param_device: none + zero3_init_flag: false + zero_stage: 2 +distributed_type: DEEPSPEED +downcast_bf16: 'no' +machine_rank: 0 +main_training_function: main +mixed_precision: 'bf16' +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/deepspeed_zero3.yaml b/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/deepspeed_zero3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b5a1201f8a2ee8706b63f0f80c664a1fc61a7d9d --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/deepspeed_zero3.yaml @@ -0,0 +1,22 @@ +compute_environment: LOCAL_MACHINE +debug: false +deepspeed_config: + deepspeed_multinode_launcher: standard + offload_optimizer_device: none + offload_param_device: none + zero3_init_flag: true + zero3_save_16bit_model: true + zero_stage: 3 +distributed_type: DEEPSPEED +downcast_bf16: 'no' +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/fsdp1.yaml b/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/fsdp1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c01b0b567bc93bf87ec136ea975b3793d273a45c --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/fsdp1.yaml @@ -0,0 +1,28 @@ +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: FSDP +downcast_bf16: 'no' +enable_cpu_affinity: false +fsdp_config: + fsdp_activation_checkpointing: false + fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP + fsdp_backward_prefetch: BACKWARD_PRE + fsdp_cpu_ram_efficient_loading: true + fsdp_forward_prefetch: true + fsdp_offload_params: false + fsdp_reshard_after_forward: FULL_SHARD + fsdp_state_dict_type: FULL_STATE_DICT + fsdp_sync_module_states: true + fsdp_use_orig_params: true + fsdp_version: 1 +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/fsdp2.yaml b/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/fsdp2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..af498f3eced9c2434b80113f2f22d40395e0ab8a --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/fsdp2.yaml @@ -0,0 +1,25 @@ +# Requires accelerate 1.7.0 or higher +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: FSDP +downcast_bf16: 'no' +enable_cpu_affinity: false +fsdp_config: + fsdp_activation_checkpointing: false + fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP + fsdp_cpu_ram_efficient_loading: true + fsdp_offload_params: false + fsdp_reshard_after_forward: true + fsdp_state_dict_type: FULL_STATE_DICT + fsdp_version: 2 +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/multi_gpu.yaml b/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/multi_gpu.yaml new file mode 100644 index 0000000000000000000000000000000000000000..15dad9be3ba44f7c934e1ecab98a93cb83cbc79a --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/multi_gpu.yaml @@ -0,0 +1,16 @@ +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: MULTI_GPU +downcast_bf16: 'no' +gpu_ids: all +machine_rank: 0 +main_training_function: main +mixed_precision: 'bf16' +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/single_gpu.yaml b/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/single_gpu.yaml new file mode 100644 index 0000000000000000000000000000000000000000..200fcc18dde040e6c35708d18927ce9bc522079d --- /dev/null +++ b/tasks/tasksmith-b3c12843c3fb/tests/source/examples/accelerate_configs/single_gpu.yaml @@ -0,0 +1,16 @@ +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: "NO" +downcast_bf16: 'no' +gpu_ids: all +machine_rank: 0 +main_training_function: main +mixed_precision: 'bf16' +num_machines: 1 +num_processes: 1 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false