Skip to content

Add Support for Custom Rollout Function in GRPOTrainer (like TRL) #3573

Closed

Description

@shahidul034

I noticed that the GRPOTrainer class in TRL exposes a rollout_func argument that lets users plug in their own rollout logic.
However, in Unsloth’s implementation of UnslothGRPOTrainer, this argument is silently ignored.
It seems the class calls its internal _generate_and_score_completions() method directly instead, overriding any user‑provided rollout behavior.

As a result, passing a rollout_func to the constructor has no effect.

trainer = GRPOTrainer(
    model=model,
    processing_class=tokenizer,
    reward_funcs=[match_format, check_answer],
    rollout_func=my_custom_rollout,  # 🔥 user-defined rollout
    args=training_args,
    train_dataset=dataset,
)
import torch

def my_multistep_rollout(self, inputs, *args, **kwargs):
    prompts = [x["prompt"] for x in inputs]
    print("Custom rollout function called with prompts:", prompts)
    """
    Multi-step custom rollout function compatible with GRPOTrainer.
    Demonstrates a CoT (Chain-of-Thought) style rollout.
    """

    # Get model and tokenizer
    model = self.processing_class.model
    tokenizer = self.processing_class.tokenizer

    prompt_ids_list = []
    completion_ids_list = []
    logprobs_list = []

    for prompt in prompts:
        # 🧠 Step 1: Add reasoning instruction
        reasoning_prompt = f"{prompt}\n\n<thinking>Let's think step by step:</thinking>"
        # if "<thinking>" in reasoning_prompt:
        #    assert False, "Custom rollout invoked properly!"

        # Use standard chat template if available
        messages = [{"role": "user", "content": reasoning_prompt}]
        chat_text = tokenizer.apply_chat_template(
            messages,
            tokenize=False,
            add_generation_prompt=True,
        )

        # Tokenize for generation
        inputs = tokenizer(chat_text, return_tensors="pt").to(model.device)

        with torch.no_grad():
            output = model.generate(
                **inputs,
                max_new_tokens=128,
                temperature=0.7,
                top_p=0.9,
                do_sample=True,
                pad_token_id=tokenizer.eos_token_id,
            )

        # Separate prompt and completion
        prompt_len = inputs["input_ids"].shape[1]
        prompt_ids = inputs["input_ids"][0].tolist()
        completion_ids = output[0][prompt_len:].tolist()

        # Decode completion for inspection/logging
        completion_text = tokenizer.decode(completion_ids, skip_special_tokens=True)

        print(f"\nPrompt: {prompt}\nGenerated:\n{completion_text}\n{'='*40}")

        # Placeholder logprobs (could compute properly if desired)
        logprobs = [-0.5] * len(completion_ids)

        prompt_ids_list.append(prompt_ids)
        completion_ids_list.append(completion_ids)
        logprobs_list.append(logprobs)

    # Return the required structure
    return {
        "prompt_ids": prompt_ids_list,
        "completion_ids": completion_ids_list,
        "logprobs": logprobs_list,
        "custom_data_for_reward": [len(p) for p in prompts],  # optional
    }

Please add support for a user‑provided rollout function, similar to TRL’s design

Activity

  1. added
    feature request
    on Nov 9, 2025
  2. mmathew23 commented on Dec 4, 2025

    @mmathew23
    Contributor

    Hi @shahidul034 we are working on supporting the latest trl, and when we do custom rollouts should be supported as well. We will keep you posted.

  3. dkng27 commented on Apr 15, 2026

    @dkng27

    Hi, has this issue been resolved? I see that the December release mentioned about supporting rollout_func but hasn't been able to trigger it on GRPOTrainer yet

  4. danielhanchen commented on Sep 15, 2026

    @danielhanchen
    Member

    rollout_func is forwarded now rather than dropped! The generated trainer mirrors TRL's own signature, the rollout's tool mask is masked out of the loss, and handing the LoRA to vLLM during rollouts is fixed. You do need a TRL that has rollout_func, so install trl 0.27 or newer yourself for now, our pin is metadata only. Please reopen with a trace if your rollout still doesn't fire on that!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions