# 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](/docs/trl/v0.26.2/en/gkd_trainer#trl.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](/docs/trl/v0.26.2/en/sft_trainer#trl.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](/docs/trl/v0.26.2/en/gkd_trainer#trl.GKDConfig), controlling the generalized JSD interpolation and on-policy
  sampling ratio.

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 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=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()
```

### 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.

## GOLDTrainer[[trl.experimental.gold.GOLDTrainer]]

#### trl.experimental.gold.GOLDTrainer[[trl.experimental.gold.GOLDTrainer]]

[Source](https://github.com/huggingface/trl/blob/v0.26.2/trl/experimental/gold/gold_trainer.py#L724)

traintrl.experimental.gold.GOLDTrainer.trainhttps://github.com/huggingface/trl/blob/v0.26.2/transformers/trainer.py#L2213[{"name": "resume_from_checkpoint", "val": ": typing.Union[str, bool, NoneType] = None"}, {"name": "trial", "val": ": typing.Union[ForwardRef('optuna.Trial'), dict[str, typing.Any], NoneType] = None"}, {"name": "ignore_keys_for_eval", "val": ": typing.Optional[list[str]] = None"}, {"name": "**kwargs", "val": ": typing.Any"}]- **resume_from_checkpoint** (`str` or `bool`, *optional*) --
  If a `str`, local path to a saved checkpoint as saved by a previous instance of `Trainer`. If a
  `bool` and equals `True`, load the last checkpoint in *args.output_dir* as saved by a previous instance
  of `Trainer`. If present, training will resume from the model/optimizer/scheduler states loaded here.
- **trial** (`optuna.Trial` or `dict[str, Any]`, *optional*) --
  The trial run or the hyperparameter dictionary for hyperparameter search.
- **ignore_keys_for_eval** (`list[str]`, *optional*) --
  A list of keys in the output of your model (if it is a dictionary) that should be ignored when
  gathering predictions for evaluation during the training.
- **kwargs** (`dict[str, Any]`, *optional*) --
  Additional keyword arguments used to hide deprecated arguments0

Main training entry point.

**Parameters:**

resume_from_checkpoint (`str` or `bool`, *optional*) : If a `str`, local path to a saved checkpoint as saved by a previous instance of `Trainer`. If a `bool` and equals `True`, load the last checkpoint in *args.output_dir* as saved by a previous instance of `Trainer`. If present, training will resume from the model/optimizer/scheduler states loaded here.

trial (`optuna.Trial` or `dict[str, Any]`, *optional*) : The trial run or the hyperparameter dictionary for hyperparameter search.

ignore_keys_for_eval (`list[str]`, *optional*) : A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions for evaluation during the training.

kwargs (`dict[str, Any]`, *optional*) : Additional keyword arguments used to hide deprecated arguments
#### generate_on_policy_outputs[[trl.experimental.gold.GOLDTrainer.generate_on_policy_outputs]]

[Source](https://github.com/huggingface/trl/blob/v0.26.2/trl/experimental/gold/gold_trainer.py#L1542)
#### save_model[[trl.experimental.gold.GOLDTrainer.save_model]]

[Source](https://github.com/huggingface/trl/blob/v0.26.2/transformers/trainer.py#L4177)

Will save the model, so you can reload it using `from_pretrained()`.

Will only save from the main process.
#### push_to_hub[[trl.experimental.gold.GOLDTrainer.push_to_hub]]

[Source](https://github.com/huggingface/trl/blob/v0.26.2/transformers/trainer.py#L5117)

Upload `self.model` and `self.processing_class` to the 🤗 model hub on the repo `self.args.hub_model_id`.

**Parameters:**

commit_message (`str`, *optional*, defaults to `"End of training"`) : Message to commit while pushing.

blocking (`bool`, *optional*, defaults to `True`) : Whether the function should return only when the `git push` has finished.

token (`str`, *optional*, defaults to `None`) : Token with write permission to overwrite Trainer's original args.

revision (`str`, *optional*) : The git revision to commit from. Defaults to the head of the "main" branch.

kwargs (`dict[str, Any]`, *optional*) : Additional keyword arguments passed along to `~Trainer.create_model_card`.

**Returns:**

The URL of the repository where the model was pushed if `blocking=False`, or a `Future` object tracking the
progress of the commit if `blocking=True`.

## GOLDConfig[[trl.experimental.gold.GOLDConfig]]

#### trl.experimental.gold.GOLDConfig[[trl.experimental.gold.GOLDConfig]]

[Source](https://github.com/huggingface/trl/blob/v0.26.2/trl/experimental/gold/gold_config.py#L24)

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 [TrainingArguments](https://huggingface.co/docs/transformers/v5.0.0rc1/en/main_classes/trainer#transformers.TrainingArguments) and [SFTConfig](/docs/trl/v0.26.2/en/sft_trainer#trl.SFTConfig) documentation.

**Parameters:**

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_completion_length (`int`, *optional*, defaults to `128`) : Maximum number of tokens to generate per completion.

teacher_model_name_or_path (`str` or `None`, *optional*, defaults to `None`) : 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]]` or `None`, *optional*, defaults to `None`) : Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the teacher model from a string.

teacher_tokenizer_name_or_path (`str` or `None`, *optional*, defaults to `None`) : 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).

use_uld_loss (`bool`, *optional*, defaults to `False`) : Whether to use Universal Logit Distillation (ULD) loss instead of Generalized Jensen-Shannon Divergence loss.

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.

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 `"server"`) : 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_guided_decoding_regex (`str` or `None`, *optional*, defaults to `None`) : Regex for vLLM guided decoding for the student model.

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.

