Skip to content

feat: add DFT loss and refactor SFT losses into submodule#1153

Open
kryvokhyzha wants to merge 1 commit intogoogle:mainfrom
kryvokhyzha:feature/add-dft-loss
Open

feat: add DFT loss and refactor SFT losses into submodule#1153
kryvokhyzha wants to merge 1 commit intogoogle:mainfrom
kryvokhyzha:feature/add-dft-loss

Conversation

@kryvokhyzha
Copy link

PR: Add Dynamic Fine-Tuning (DFT) loss and refactor SFT losses into submodule

Description

This PR introduces Dynamic Fine-Tuning (DFT) loss support.

Refactor: tunix/sft/losses/ submodule

The existing _default_loss_fn is moved into a proper losses/ package with shared building blocks:

  • per_token_cross_entropy(model, ...) - runs the forward pass and returns raw per-token cross-entropy values with the target mask.
  • aggregate_loss(per_token_loss, mask) - masks and averages per-token losses over valid tokens.
  • cross_entropy_loss_fn(model, ...) - standard next-token prediction NLL (drop-in replacement for the old _default_loss_fn).

New: DFT loss

Based on the paper On the Generalization of Supervised Fine-Tuning: A Reinforcement Learning Perspective with Reward Rectification, DFT rescales the per-token cross-entropy loss by the model's own predicted probability (with stop-gradient):

dft_loss_t = stop_gradient(p(y_t)) * (-log p(y_t))

The implementation composes on top of the standard cross-entropy building blocks:

  • dft_rescale(per_token_loss) - applies the per-token rescaling, usable with any per-token loss computation.
  • dft_loss_fn(model, ...) - drop-in replacement for cross_entropy_loss_fn:

Reference

Checklist

  • I have added all the necessary unit tests for my change.
  • I have verified that my change does not break existing code and all unit tests pass.
  • I have added all appropriate doc-strings/documentation.
  • My PR is based on the latest changes of the main branch (if unsure, rebase the code).
  • I have signed the Contributor License Agreement.
  • I have followed Contribution Guidelines.

@gemini-code-assist
Copy link

Summary of Changes

Hello @kryvokhyzha, 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 tunix library by integrating Dynamic Fine-Tuning (DFT) loss, a method designed to improve generalization in supervised fine-tuning. Concurrently, it undertakes a substantial refactoring of the existing loss function infrastructure, moving common components into a new, modular losses submodule. This reorganization promotes code reusability and clarity, making it easier to introduce and manage various loss functions within the framework.

Highlights

  • Dynamic Fine-Tuning (DFT) Loss Introduction: Introduced support for Dynamic Fine-Tuning (DFT) loss, a novel loss function that rescales per-token cross-entropy by the model's own predicted probability with a stop-gradient mechanism, as described in the paper 'On the Generalization of Supervised Fine-Tuning: A Reinforcement Learning Perspective with Reward Rectification'.
  • SFT Loss Refactoring: Refactored existing Supervised Fine-Tuning (SFT) loss functions into a new tunix/sft/losses/ submodule, enhancing modularity and organization.
  • Reusable Loss Building Blocks: Created shared building blocks for loss computation, including per_token_cross_entropy to calculate raw per-token losses and aggregate_loss for masking and averaging losses over valid tokens.
  • Comprehensive Unit Testing: Added extensive unit tests for the new DFT loss components (dft_rescale, dft_loss_fn) and the refactored cross-entropy loss (cross_entropy_loss_fn) to ensure correctness, proper gradient behavior, and integration with the PeftTrainer.

🧠 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
  • tests/sft/losses_test.py
    • Added a new test file to cover the cross_entropy_loss_fn, dft_rescale, and dft_loss_fn.
    • Included tests for scalar return, parameter updates during training, non-negativity, input bounds, zero input, uniform distribution ratio, stop-gradient behavior, gradient differences, and batched input for DFT rescaling.
    • Verified that DFT loss is less than or equal to cross-entropy and differs from it.
  • tunix/sft/losses/init.py
    • Created an empty __init__.py file to establish tunix/sft/losses as a Python package.
  • tunix/sft/losses/cross_entropy.py
    • Implemented per_token_cross_entropy to compute raw per-token cross-entropy and target masks.
    • Implemented aggregate_loss to mask and average per-token losses.
    • Implemented cross_entropy_loss_fn as the standard next-token prediction NLL loss, utilizing the new building blocks.
  • tunix/sft/losses/dft.py
    • Implemented dft_rescale function to apply Dynamic Fine-Tuning rescaling to per-token losses.
    • Implemented dft_loss_fn which integrates dft_rescale with the common cross-entropy building blocks.
  • tunix/sft/peft_trainer.py
    • Imported the new tunix.sft.losses module.
    • Updated the self.loss_fn and self.eval_loss_fn initialization to use losses.cross_entropy_loss_fn.
    • Removed the _default_loss_fn as its logic was moved to tunix/sft/losses/cross_entropy.py.
Activity
  • No human activity (comments, reviews, etc.) has been recorded for 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

@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 significant and valuable refactoring by moving the SFT loss functions into a dedicated tunix/sft/losses submodule. This greatly improves modularity and prepares the ground for adding new loss functions like the newly introduced DFT loss. The implementation of DFT loss is clear and well-tested. I have a couple of suggestions: one to ensure the new losses module is correctly exposed, and another to optimize the cross-entropy calculation for better performance and numerical stability.

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