TRL documentation

BCO Trainer

You are viewing v0.12.1 version. A newer version v0.15.1 is available.
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

BCO Trainer

TRL supports the Binary Classifier Optimization (BCO). The BCO 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.

Expected dataset type

The BCOTrainer requires an unpaired preference dataset. The BCOTrainer supports both conversational and standard dataset format. 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).

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:

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:

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 defined how many prompts are selected to train the UDM classifier and start the training with the provided embedding function:

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

class trl.BCOTrainer

< >

( model: Union = Noneref_model: Union = Noneargs: BCOConfig = Nonetrain_dataset: Optional = Noneeval_dataset: Union = Noneprocessing_class: Union = Nonedata_collator: Optional = Nonemodel_init: Optional = Nonecallbacks: Optional = Noneoptimizers: Tuple = (None, None)preprocess_logits_for_metrics: Optional = Nonepeft_config: Optional = Nonecompute_metrics: Optional = Nonemodel_adapter_name: Optional = Noneref_adapter_name: Optional = Noneembedding_func: Optional = Noneembedding_tokenizer: Optional = None )

Parameters

  • model (transformers.PreTrainedModel) β€” The model to train, preferably an AutoModelForSequenceClassification.
  • ref_model (PreTrainedModelWrapper) β€” 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 (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 (PreTrainedTokenizerBase or BaseImageProcessor or FeatureExtractionMixin or 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, defaults to None) β€” The data collator to use for training. If None is specified, the default data collator (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 (Dict, defaults to None) β€” The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model.
  • disable_dropout (bool, defaults to True) β€” Whether or not to disable dropouts in model and ref_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.

Initialize BCOTrainer from BCO paper.

bco_loss

< >

( policy_chosen_logps: FloatTensorpolicy_rejected_logps: FloatTensorreference_chosen_logps: FloatTensorreference_rejected_logps: FloatTensorchosen_embeddings: Optionalrejected_embeddings: Optional ) β†’ A tuple of four tensors

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.

Compute the BCO loss for a batch of policy and reference model log probabilities.

compute_reference_log_probs

< >

( padded_batch: Dict )

Computes log probabilities of the reference model for a single padded batch of a BCO specific dataset.

create_model_card

< >

( model_name: Optional = Nonedataset_name: Optional = Nonetags: Union = None )

Parameters

  • model_name (str, optional, defaults to None) β€” The name of the model.
  • dataset_name (str, optional, defaults to None) β€” The name of the dataset used for training.
  • tags (str, List[str] or None, optional, defaults to None) β€” Tags to be associated with the model card.

Creates a draft of a model card using the information available to the Trainer.

evaluation_loop

< >

( dataloader: DataLoaderdescription: strprediction_loss_only: Optional = Noneignore_keys: Optional = Nonemetric_key_prefix: str = 'eval' )

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.

generate_from_model_and_ref

< >

( modelbatch: Dict )

Generate samples from the model and reference model for the given batch of inputs.

get_batch_logps

< >

( logits: FloatTensorlabels: LongTensoraverage_log_prob: bool = Falselabel_pad_token_id: int = -100is_encoder_decoder: bool = False )

Compute the log probabilities of the given labels under the given logits.

get_batch_loss_metrics

< >

( modelbatch: Dict )

Compute the BCO loss and other metrics for the given batch of inputs for train or test.

get_eval_dataloader

< >

( eval_dataset: Optional = None )

Parameters

  • eval_dataset (torch.utils.data.Dataset, optional) β€” If provided, will override self.eval_dataset. If it is a Dataset, columns not accepted by the model.forward() method are automatically removed. It must implement __len__.

Returns the evaluation ~torch.utils.data.DataLoader.

Subclass of transformers.src.transformers.trainer.get_eval_dataloader to precompute ref_log_probs.

get_train_dataloader

< >

( )

Returns the training ~torch.utils.data.DataLoader.

Subclass of transformers.src.transformers.trainer.get_train_dataloader to precompute ref_log_probs.

log

< >

( logs: Dict )

Parameters

  • logs (Dict[str, float]) β€” The values to log.

Log logs on the various objects watching training, including stored metrics.

null_ref_context

< >

( )

Context manager for handling null reference model (that is, peft adapter manipulation).

BCOConfig

class trl.BCOConfig

< >

( output_dir: stroverwrite_output_dir: bool = Falsedo_train: bool = Falsedo_eval: bool = Falsedo_predict: bool = Falseeval_strategy: Union = 'no'prediction_loss_only: bool = Falseper_device_train_batch_size: int = 8per_device_eval_batch_size: int = 8per_gpu_train_batch_size: Optional = Noneper_gpu_eval_batch_size: Optional = Nonegradient_accumulation_steps: int = 1eval_accumulation_steps: Optional = Noneeval_delay: Optional = 0torch_empty_cache_steps: Optional = Nonelearning_rate: float = 5e-05weight_decay: float = 0.0adam_beta1: float = 0.9adam_beta2: float = 0.999adam_epsilon: float = 1e-08max_grad_norm: float = 1.0num_train_epochs: float = 3.0max_steps: int = -1lr_scheduler_type: Union = 'linear'lr_scheduler_kwargs: Union = <factory>warmup_ratio: float = 0.0warmup_steps: int = 0log_level: Optional = 'passive'log_level_replica: Optional = 'warning'log_on_each_node: bool = Truelogging_dir: Optional = Nonelogging_strategy: Union = 'steps'logging_first_step: bool = Falselogging_steps: float = 500logging_nan_inf_filter: bool = Truesave_strategy: Union = 'steps'save_steps: float = 500save_total_limit: Optional = Nonesave_safetensors: Optional = Truesave_on_each_node: bool = Falsesave_only_model: bool = Falserestore_callback_states_from_checkpoint: bool = Falseno_cuda: bool = Falseuse_cpu: bool = Falseuse_mps_device: bool = Falseseed: int = 42data_seed: Optional = Nonejit_mode_eval: bool = Falseuse_ipex: bool = Falsebf16: bool = Falsefp16: bool = Falsefp16_opt_level: str = 'O1'half_precision_backend: str = 'auto'bf16_full_eval: bool = Falsefp16_full_eval: bool = Falsetf32: Optional = Nonelocal_rank: int = -1ddp_backend: Optional = Nonetpu_num_cores: Optional = Nonetpu_metrics_debug: bool = Falsedebug: Union = ''dataloader_drop_last: bool = Falseeval_steps: Optional = Nonedataloader_num_workers: int = 0dataloader_prefetch_factor: Optional = Nonepast_index: int = -1run_name: Optional = Nonedisable_tqdm: Optional = Noneremove_unused_columns: Optional = Truelabel_names: Optional = Noneload_best_model_at_end: Optional = Falsemetric_for_best_model: Optional = Nonegreater_is_better: Optional = Noneignore_data_skip: bool = Falsefsdp: Union = ''fsdp_min_num_params: int = 0fsdp_config: Union = Nonefsdp_transformer_layer_cls_to_wrap: Optional = Noneaccelerator_config: Union = Nonedeepspeed: Union = Nonelabel_smoothing_factor: float = 0.0optim: Union = 'adamw_torch'optim_args: Optional = Noneadafactor: bool = Falsegroup_by_length: bool = Falselength_column_name: Optional = 'length'report_to: Union = Noneddp_find_unused_parameters: Optional = Noneddp_bucket_cap_mb: Optional = Noneddp_broadcast_buffers: Optional = Nonedataloader_pin_memory: bool = Truedataloader_persistent_workers: bool = Falseskip_memory_metrics: bool = Trueuse_legacy_prediction_loop: bool = Falsepush_to_hub: bool = Falseresume_from_checkpoint: Optional = Nonehub_model_id: Optional = Nonehub_strategy: Union = 'every_save'hub_token: Optional = Nonehub_private_repo: bool = Falsehub_always_push: bool = Falsegradient_checkpointing: bool = Falsegradient_checkpointing_kwargs: Union = Noneinclude_inputs_for_metrics: bool = Falseinclude_for_metrics: List = <factory>eval_do_concat_batches: bool = Truefp16_backend: str = 'auto'evaluation_strategy: Union = Nonepush_to_hub_model_id: Optional = Nonepush_to_hub_organization: Optional = Nonepush_to_hub_token: Optional = Nonemp_parameters: str = ''auto_find_batch_size: bool = Falsefull_determinism: bool = Falsetorchdynamo: Optional = Noneray_scope: Optional = 'last'ddp_timeout: Optional = 1800torch_compile: bool = Falsetorch_compile_backend: Optional = Nonetorch_compile_mode: Optional = Nonedispatch_batches: Optional = Nonesplit_batches: Optional = Noneinclude_tokens_per_second: Optional = Falseinclude_num_input_tokens_seen: Optional = Falseneftune_noise_alpha: Optional = Noneoptim_target_modules: Union = Nonebatch_eval_metrics: bool = Falseeval_on_start: bool = Falseuse_liger_kernel: Optional = Falseeval_use_gather_object: Optional = Falseaverage_tokens_across_devices: Optional = Falsemax_length: Optional = Nonemax_prompt_length: Optional = Nonemax_completion_length: Optional = Nonebeta: float = 0.1label_pad_token_id: int = -100padding_value: Optional = Nonetruncation_mode: str = 'keep_end'generate_during_eval: bool = Falseis_encoder_decoder: Optional = Noneprecompute_ref_log_probs: bool = Falsemodel_init_kwargs: Optional = Noneref_model_init_kwargs: Optional = Nonedataset_num_proc: Optional = Noneprompt_sample_size: int = 1024min_density_ratio: float = 0.5max_density_ratio: float = 10.0 )

Parameters

  • max_length (Optional[int], optional, defaults to None) β€” Maximum length of the sequences (prompt + completion) in the batch. This argument is required if you want to use the default data collator.
  • max_prompt_length (Optional[int], optional, defaults to None) β€” Maximum length of the prompt. This argument is required if you want to use the default data collator.
  • max_completion_length (Optional[int], optional, defaults to None) β€” 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.
  • label_pad_token_id (int, optional, defaults to -100) β€” Label pad token id. This argument is required if you want to use the default data collator.
  • padding_value (Optional[int], optional, defaults to None) β€” Padding value to use. If None, the padding value of the tokenizer is used.
  • truncation_mode (str, optional, defaults to "keep_end") β€” Truncation mode to use when the prompt is too long. Possible values are "keep_end" or "keep_start". This argument is required if you want to use the default data collator.
  • 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 during evaluation.
  • is_encoder_decoder (Optional[bool], optional, defaults to None) β€” 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 (Optional[Dict[str, Any]], optional, defaults to None) β€” Keyword arguments to pass to AutoModelForCausalLM.from_pretrained when instantiating the model from a string.
  • ref_model_init_kwargs (Optional[Dict[str, Any]], optional, defaults to None) β€” Keyword arguments to pass to AutoModelForCausalLM.from_pretrained when instantiating the reference model from a string.
  • dataset_num_proc (Optional[int], optional, defaults to None) β€” 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.

Configuration class for the BCOTrainer.

Using HfArgumentParser we can turn this class into argparse arguments that can be specified on the command line.

< > Update on GitHub