Here’s a minimal working example of how you can extend the TRL’s GRPOTrainer to also compute a supervised‐classification loss from an extra head and sum it with the RL loss. Feel free to adapt the details (e.g. how you build your model, which inputs you expect, loss‐weighting, etc.).
python
import torch
from torch import nn
from trl import GRPOTrainer, default_gradient_accumulation_fns
from transformers import PreTrainedModel
class GRPOWithClassificationTrainer(GRPOTrainer):
def __init__(
self,
model: PreTrainedModel,
train_dataset,
eval_dataset=None,
classification_loss_weight: float = 1.0,
**trainer_kwargs,
):
"""
Args:
model: your model must implement a `classification_head` and return its logits
train_dataset, eval_dataset: as usual for TRL
classification_loss_weight: how much to scale the CE‐loss
trainer_kwargs: all the usual GRPOTrainer args
"""
super().__init__(model=model, train_dataset=train_dataset,
eval_dataset=eval_dataset, **trainer_kwargs)
# Use CrossEntropy for classification
self.classification_loss_fn = nn.CrossEntropyLoss()
self.classification_loss_weight = classification_loss_weight
def compute_loss(self, model, inputs, return_outputs=False):
"""
overrides GRPOTrainer.compute_loss to
1) get the RL‐loss via super()
2) compute classification loss
3) sum them
"""
# 1) RL loss (and cache outputs if requested)
rl_outputs = super().compute_loss(model, inputs, return_outputs=True)
if isinstance(rl_outputs, tuple):
# (loss, { … })
rl_loss, rl_info = rl_outputs
else:
rl_loss = rl_outputs
rl_info = {}
# 2) Classification head forward + loss
# we assume your `inputs` has:
# - "cls_input_ids" (LongTensor[b, seq_len])
# - "cls_attention_mask" (optional)
# - "cls_labels" (LongTensor[b] or [b, seq_len] if token‐level)
cls_inputs = {
"input_ids": inputs["cls_input_ids"],
"attention_mask": inputs.get("cls_attention_mask", None),
}
cls_labels = inputs["cls_labels"]
cls_logits = model.classification_head(**cls_inputs)
# shape [batch_size, n_classes] or [batch_size, seq_len, n_classes]
# flatten if needed
if cls_logits.dim() > 2:
# token‐level classification
loss_cls = self.classification_loss_fn(
cls_logits.view(-1, cls_logits.size(-1)),
cls_labels.view(-1),
)
else:
# sequence‐level classification
loss_cls = self.classification_loss_fn(cls_logits, cls_labels)
# 3) Combine
total_loss = rl_loss + self.classification_loss_weight * loss_cls
# package the metrics if return_outputs
if return_outputs:
rl_info["classification_loss"] = loss_cls.detach()
rl_info["total_loss"] = total_loss.detach()
return total_loss, rl_info
return total_loss
How to wire this up end-to-end:
Build a model that has both
the usual causal‐LM head (for GRPO)
a classification_head method which takes input_ids, returns logits of shape [batch, n_classes] (or token‐level).