Skip to content

Conversation

@metascroy
Copy link
Contributor

This updates unsloth_save_pretrained_torchao.

With this change, after QAT, we can do this to save the model:

# Save locally
model.save_pretrained_torchao(save_to, tokenizer=tokenizer)

# Or push to hub
from huggingface_hub import get_token, whoami
def _get_username():
    token = get_token()
    username = whoami(token=token)["name"]
    return username
username = _get_username()
model.save_pretrained_torchao(f"{username}/{save_to}", tokenizer=tokenizer, push_to_hub=True)

Previously we had to manually convert with something like this:

from unsloth.models._utils import _convert_torchao_model
_convert_torchao_model(model)

# Save locally
model.save_pretrained(save_to, safe_serialization=False)
tokenizer.save_pretrained(save_to)

# Or save to hub
from huggingface_hub import get_token, whoami
def _get_username():
    token = get_token()
    username = whoami(token=token)["name"]
    return username
username = _get_username()
model.push_to_hub(f"{username}/{save_to}", safe_serialization=False)
tokenizer.push_to_hub(f"{username}/{save_to}")

unsloth_save_pretrained_torchao now either calls _unsloth_save_torchao_with_given_config (previous behavior) or _unsloth_save_torchao_with_attached_config.

As the name suggests, _unsloth_save_torchao_with_given_config requires a torchao config is provided and starts from a floating point model.

_unsloth_save_torchao_with_given_config uses the config on the model (_torchao_config) that gets attached when a qat_scheme is provided to FastLanguageModel.

The save_directory is always appended with "-torchao" to preserve the previous behavior, but from an API perspective I think this is a bit odd. cc @danielhanchen for thoughts

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @metascroy, 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 significantly enhances the unsloth_save_pretrained_torchao functionality by streamlining the model saving process for TorchAO quantized models. It introduces a more robust and user-friendly API that intelligently distinguishes between Quantization-Aware Training (QAT) and Post-Training Quantization (PTQ) workflows. This change simplifies the developer experience by automating the conversion and saving of QAT models and providing clear guidance for applying PTQ, ultimately making it easier to persist and share quantized models.

Highlights

  • API Simplification for TorchAO Saving: The unsloth_save_pretrained_torchao function has been refactored to simplify the saving process for both Quantization-Aware Training (QAT) and Post-Training Quantization (PTQ) models.
  • Automated QAT Model Saving: For QAT models (those trained with qat_scheme), the saving process now automatically converts fake-quantized weights to real quantized weights, eliminating the need for manual conversion steps.
  • Clearer PTQ Workflow: For PTQ, users must now explicitly provide a torchao_config, and the system prevents accidental use of torchao_config with QAT-trained models.
  • Internal Function Refactoring: The core logic has been split into _unsloth_save_torchao_with_attached_config (for QAT) and _unsloth_save_torchao_with_given_config (for PTQ), with the main unsloth_save_pretrained_torchao acting as a dispatcher.
  • Improved Error Handling: Assertions are added to guide users on the correct usage of torchao_config based on whether the model is QAT-trained or requires PTQ.
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.

@metascroy
Copy link
Contributor Author

@danielhanchen can you have a look.

cc @jerryzh168 @andrewor14 as FYI

Copy link

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

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

unsloth/save.py Outdated
Comment on lines 2791 to 2792
arguments = dict(locals())
arguments["model"] = self

Choose a reason for hiding this comment

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

P1 Badge Avoid NameError when preparing PTQ save arguments

_unsloth_save_torchao_with_given_config now builds arguments using self, but the function signature only accepts model, so any PTQ call (i.e., when torchao_config is provided) will raise a NameError before merging or saving the model. This blocks the post-training quantization workflow entirely because the helper cannot run past the first few lines.

Useful? React with 👍 / 👎.

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

The pull request refactors the unsloth_save_pretrained_torchao function into two internal helper functions, _unsloth_save_torchao_with_attached_config and _unsloth_save_torchao_with_given_config, to handle saving QAT (Quantization-Aware Training) models and applying PTQ (Post-Training Quantization) with a provided configuration, respectively. The main function now acts as a dispatcher, including new assertions for correct usage (e.g., requiring a token for push_to_hub and a torchao_config for PTQ, while disallowing torchao_config for QAT models). The changes also involve updating model and tokenizer loading/saving logic, removing default torchao_config behavior, and adjusting variable names from self to model in the refactored parts. Review comments suggest improving type hints for the token parameter in the new helper functions to Optional[Union[str, bool]] for consistency, and changing a bare except: block to except Exception: for more robust error handling.

unsloth/save.py Outdated
tokenizer,
push_to_hub: bool = False,
token: Optional[Union[str, bool]] = None,
token: Optional[str] = None,
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The type hint for token here is Optional[str], but the calling function unsloth_save_pretrained_torchao can pass a boolean value. While this will likely work at runtime due to dynamic typing, it's good practice to have consistent type hints. Consider changing the type hint to Optional[Union[str, bool]] to match the caller and the underlying push_to_hub API.

Suggested change
token: Optional[str] = None,
token: Optional[Union[str, bool]] = None,

@metascroy metascroy force-pushed the update-torchao-save branch from 3923abc to ab6b22c Compare December 5, 2025 02:22
@metascroy metascroy force-pushed the update-torchao-save branch from ac4f21a to c4f9e5c Compare December 5, 2025 21:00
unsloth/save.py Outdated
token: Optional[Union[str, bool]] = None,
):
"""Save a QAT-trained model by converting fake-quantized weights to real quantized weights."""
from unsloth.models._utils import _convert_torchao_model
Copy link
Contributor

Choose a reason for hiding this comment

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

Probs move this out and do a relative import ie from .models

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Changed to relative import

unsloth/save.py Outdated
# TorchAO does not support safe_serialization reliably
safe_serialization = False

torchao_save_directory = save_directory + "-torchao"
Copy link
Contributor

Choose a reason for hiding this comment

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

Yes we can remove -torchao it's probs unncessary

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Removed

@metascroy metascroy force-pushed the update-torchao-save branch from 8397e56 to 82cd10d Compare December 8, 2025 18:25
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