Skip to content

Auto-enable padding-free SFT - #3702

Closed
djsaunde wants to merge 4 commits into
unslothai:mainfrom
djsaunde:auto-padding
Closed

djsaunde wants to merge 4 commits into
unslothai:mainfrom
djsaunde:auto-padding

Conversation

@djsaunde

Copy link
Copy Markdown
Contributor

See #3672 for details.

@djsaunde djsaunde self-assigned this Dec 10, 2025
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @djsaunde, 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 integrates automatic padding-free Supervised Fine-Tuning (SFT) into Unsloth's SFTTrainer, aiming to boost training performance by default. It includes a crucial safeguard that intelligently disables this feature for Gemma 2 models, addressing potential compatibility conflicts. The changes also involve a cleanup and reorganization of the underlying code responsible for managing various training optimizations.

Highlights

  • Auto-enable Padding-Free SFT: The SFTTrainer now automatically enables padding-free batching by default, which can lead to more efficient training by optimizing memory usage and computation.
  • Gemma 2 Model Compatibility: Specific logic has been added to detect Gemma 2 models and prevent auto-enabling padding-free batching for them, as it requires flash attention to avoid compatibility issues.
  • Refactored Training Configuration: The internal logic for configuring and enabling training optimizations like sample packing and padding-free batching has been updated and streamlined for better maintainability.
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. ↩

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread unsloth/utils/__init__.py
Comment on lines +16 to +22
from .packing import (
configure_padding_free,
configure_sample_packing,
enable_padding_free_metadata,
enable_sample_packing,
mark_allow_overlength,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P0 Badge Imported padding-free helpers undefined

The new exports in unsloth.utils.__init__ import configure_padding_free, enable_padding_free_metadata, and mark_allow_overlength from .packing, but those symbols do not exist in unsloth/utils/packing.py (repo-wide rg configure_padding_free only finds these import statements). As soon as unsloth.utils or any module that depends on it (e.g., unsloth.trainer) is imported, Python raises ImportError: cannot import name 'configure_padding_free', preventing the package from loading.

Useful? React with 👍 / 👎.

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

Copy link
Copy Markdown
Contributor

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 refactors the training module to automatically enable padding-free SFT, replacing the previous auto-packing logic. The changes are generally well-structured, especially the explicit handling for Gemma 2 models. My main feedback is to re-introduce the robust error-handling mechanism that was present for auto-packing. This involves a try-except block to gracefully handle potential SFTTrainer initialization failures when padding-free is auto-enabled, ensuring the trainer can fall back to a safe configuration instead of crashing.

Comment thread unsloth/trainer.py
Comment on lines +56 to +61
def _should_auto_padding_free(config) -> bool:
if config is None or _AUTO_PADDING_FREE_ENV_DISABLED:
return False
if not getattr(config, "packing", False):
if getattr(config, "packing", False):
return False
return not getattr(config, "_unsloth_disable_auto_packing", False)


def _disable_sample_packing(config):
if config is None:
return
for attr, value in (("packing", False), ("padding_free", False)):
if hasattr(config, attr):
setattr(config, attr, value)
if hasattr(config, "remove_unused_columns"):
setattr(config, "remove_unused_columns", True)
setattr(config, "_unsloth_disable_auto_packing", True)


_AUTO_PACK_SKIP_MESSAGES = (
"packing is not supported",
"padding-free training",
"passing a custom data collator",
)


def _should_skip_auto_packing_error(exc: Exception) -> bool:
message = str(exc).lower()
return any(msg in message for msg in _AUTO_PACK_SKIP_MESSAGES)
return not getattr(config, "padding_free", False)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

To support robust error handling for auto-enabled padding-free training, _should_auto_padding_free should be updated to prevent re-enabling the feature after it has failed once. This can be done by checking for a _unsloth_disable_auto_padding_free flag on the config. I'll provide more context on the full error handling pattern in another comment.

Suggested change
def _should_auto_padding_free(config) -> bool:
if config is None or _AUTO_PADDING_FREE_ENV_DISABLED:
return False
if not getattr(config, "packing", False):
if getattr(config, "packing", False):
return False
return not getattr(config, "_unsloth_disable_auto_packing", False)
def _disable_sample_packing(config):
if config is None:
return
for attr, value in (("packing", False), ("padding_free", False)):
if hasattr(config, attr):
setattr(config, attr, value)
if hasattr(config, "remove_unused_columns"):
setattr(config, "remove_unused_columns", True)
setattr(config, "_unsloth_disable_auto_packing", True)
_AUTO_PACK_SKIP_MESSAGES = (
"packing is not supported",
"padding-free training",
"passing a custom data collator",
)
def _should_skip_auto_packing_error(exc: Exception) -> bool:
message = str(exc).lower()
return any(msg in message for msg in _AUTO_PACK_SKIP_MESSAGES)
return not getattr(config, "padding_free", False)
def _should_auto_padding_free(config) -> bool:
if config is None or _AUTO_PADDING_FREE_ENV_DISABLED:
return False
if getattr(config, "packing", False):
return False
if getattr(config, "_unsloth_disable_auto_padding_free", False):
return False
return not getattr(config, "padding_free", False)

Comment thread unsloth/trainer.py
Comment on lines +286 to +302
auto_padding_free_active = False
padding_free_requested = getattr(config_arg, "padding_free", None) is True
if not blocked:
if padding_free_requested:
configure_padding_free(config_arg)
elif not is_unsupported_gemma and _should_auto_padding_free(config_arg):
configure_padding_free(config_arg)
auto_padding_free_active = True
logger.info(
"Unsloth: Auto sample packing failed because trainer reported an incompatible setup (%s).",
exc,
"Unsloth: Padding-free batching auto-enabled for SFTTrainer instance."
)
elif is_unsupported_gemma and _should_auto_padding_free(config_arg):
logger.info(
"Unsloth: Padding-free batching auto-disabled for Gemma 2 (requires flash attention)."
)
_disable_sample_packing(config_arg)
auto_pack_active = False
original_init(self, *args, **kwargs)
else:
raise

original_init(self, *args, **kwargs)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The previous implementation for auto-packing included a robust try...except block to handle SFTTrainer initialization failures. This was a great defensive pattern that seems to have been lost in this refactoring.

Auto-enabling padding_free can also cause SFTTrainer to raise a ValueError. To make this feature more robust, I suggest re-introducing a similar error handling mechanism. This would wrap the original_init call and, upon specific failures, disable padding-free and retry.

To support this, you'll need to add the following helper functions somewhere in the file's scope (e.g., after _should_auto_padding_free):

def _disable_padding_free(config):
    if config is None:
        return
    if hasattr(config, "padding_free"):
        setattr(config, "padding_free", False)
    setattr(config, "_unsloth_disable_auto_padding_free", True)

_PADDING_FREE_SKIP_MESSAGES = (
    "padding-free training is not supported",
    "passing a custom data collator",
)

def _should_skip_padding_free_error(exc: Exception) -> bool:
    message = str(exc).lower()
    return any(msg in message for msg in _PADDING_FREE_SKIP_MESSAGES)

With these helpers (and the change to _should_auto_padding_free from my other comment), you can then add the try-except block as suggested.

        auto_padding_free_active = False
        padding_free_requested = getattr(config_arg, "padding_free", None) is True
        if not blocked:
            if padding_free_requested:
                configure_padding_free(config_arg)
            elif not is_unsupported_gemma and _should_auto_padding_free(config_arg):
                configure_padding_free(config_arg)
                auto_padding_free_active = True
                logger.info(
                    "Unsloth: Padding-free batching auto-enabled for SFTTrainer instance."
                )
            elif is_unsupported_gemma and _should_auto_padding_free(config_arg):
                logger.info(
                    "Unsloth: Padding-free batching auto-disabled for Gemma 2 (requires flash attention)."
                )

        try:
            original_init(self, *args, **kwargs)
        except ValueError as exc:
            if auto_padding_free_active and _should_skip_padding_free_error(exc):
                logger.warning(
                    "Unsloth: Auto padding-free failed, falling back to padding. Reason: %s.",
                    exc,
                )
                _disable_padding_free(config_arg)
                auto_padding_free_active = False
                original_init(self, *args, **kwargs)
            else:
                raise

@djsaunde djsaunde closed this Dec 10, 2025
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.

1 participant