Skip to content

Guard TRL estimate_tokens warnings_issued writes in patched RL trainers#4034

Open
danielhanchen wants to merge 1 commit intomainfrom
fix-trl-warnings-issued-estimate-tokens
Open

Guard TRL estimate_tokens warnings_issued writes in patched RL trainers#4034
danielhanchen wants to merge 1 commit intomainfrom
fix-trl-warnings-issued-estimate-tokens

Conversation

@danielhanchen
Copy link
Contributor

Summary

  • adds a defensive warnings_issued initializer in the generated Unsloth RL trainer init path
  • runs before TRL writes model.warnings_issued["estimate_tokens"] = True
  • normalizes non-dict warnings_issued values into a dict fallback

Root Cause

On Transformers 5.1.0 with some PEFT/model wrappers, model.warnings_issued may be missing or not a dict during trainer initialization. TRL later writes the estimate_tokens key unconditionally, which can raise AttributeError.

Changes

  • unsloth/models/rl.py
    • in _patch_trl_rl_trainers, after logits checks, inject:
      • getattr(model, "warnings_issued", None) guard
      • create {} when missing
      • coerce/fallback to dict when non-dict

Validation

  • python -m compileall unsloth/models/rl.py
  • regenerate patched RL trainers and verify compiled GRPO trainer contains the new guard
    • output log: temp/validate_unsloth_warnings_patch.log

Notes

  • this keeps behavior unchanged when warnings_issued is already valid
  • the fix is centralized in the shared RL trainer generation path, so it applies consistently to patched RL trainers

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @danielhanchen, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a potential runtime error in TRL trainers when model.warnings_issued is either absent or not a dictionary during initialization. By injecting a robust check and initialization logic into the shared RL trainer generation path, it guarantees that model.warnings_issued is always a valid dictionary before TRL attempts to modify it, thereby enhancing the stability and compatibility of patched RL trainers with various model and PEFT configurations.

Highlights

  • Defensive Initialization: Added a defensive initializer for model.warnings_issued within the generated Unsloth RL trainer initialization path.
  • Pre-emptive Patching: Ensured this initialization runs before TRL attempts to write to model.warnings_issued["estimate_tokens"] = True.
  • Type Normalization: Implemented logic to normalize warnings_issued values that are not dictionaries into a dictionary fallback, preventing potential AttributeError.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • unsloth/models/rl.py
    • Injected code into the _patch_trl_rl_trainers function to check for the existence and type of model.warnings_issued.
    • Added logic to initialize model.warnings_issued as an empty dictionary if it is None.
    • Included a mechanism to convert model.warnings_issued to a dictionary if it exists but is not already a dictionary, falling back to an empty dictionary on conversion failure.
Activity
  • No human activity has been recorded on this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a defensive guard to initialize model.warnings_issued in patched TRL RL trainers. This prevents potential AttributeError exceptions when TRL attempts to write to this attribute, which may be missing or not a dictionary in some environments. The implementation is robust, handling cases where the attribute is missing or has an unexpected non-dictionary type. I have one suggestion to make the exception handling more specific, which is a minor improvement to an already solid patch.

" elif not isinstance(_warnings_issued, dict):\n"
" try:\n"
" model.warnings_issued = dict(_warnings_issued)\n"
" except Exception:\n"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

While using a broad except Exception: is very defensive, it's generally better to catch more specific exceptions to avoid masking unrelated errors. The dict() constructor on an invalid input will typically raise TypeError (if the object is not iterable) or ValueError (if items are not key-value pairs). Catching these specific exceptions would make the code's intent clearer.

Suggested change
" except Exception:\n"
" except (TypeError, ValueError):\n"

@Datta0
Copy link
Collaborator

Datta0 commented Feb 16, 2026

Ref: #4032 (comment)

Copy link
Collaborator

@Datta0 Datta0 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants