Skip to content

[v1] add deepspeed zero3 trigger for low memory usage weight loading#10300

Open
jiaqiw09 wants to merge 2 commits intohiyouga:mainfrom
jiaqiw09:ds3_fix
Open

[v1] add deepspeed zero3 trigger for low memory usage weight loading#10300
jiaqiw09 wants to merge 2 commits intohiyouga:mainfrom
jiaqiw09:ds3_fix

Conversation

@jiaqiw09
Copy link
Copy Markdown
Collaborator

@jiaqiw09 jiaqiw09 commented Mar 19, 2026

What does this PR do?

  1. Trigger DS3 early in ModelEngine, and reuse the optimized loading method from transformers / accelerate / deepspeed.

  2. Refine precision behavior for DeepSpeed (bf16 / fp16)

  • When fp16=True in config.yaml, it raises an error (DeepSpeed does not support fp16 in current backend)

  • When bf16=True:

    Precision debug: dist=deepspeed,
    parameter_storage_dtype=torch.bfloat16,
    forward_logits_dtype=torch.bfloat16
    
  • When bf16=False:

    mixed_precision=no
    Precision debug: dist=deepspeed,
    parameter_storage_dtype=torch.float32,
    forward_logits_dtype=torch.float32
    
  • When both bf16 and fp16 are set to auto, it defaults to bf16


  1. Default bf16 behavior for FSDP2 backend
  • When bf16=True:

    • forward/backward: bf16
    • parameter storage: fp32
    Precision debug: dist=fsdp2,
    parameter_storage_dtype=torch.float32,
    forward_logits_dtype=torch.bfloat16
    
  • When bf16=False:

    • forward/backward: fp32
    • parameter storage: fp32
    Precision debug: dist=fsdp2,
    parameter_storage_dtype=torch.float32,
    forward_logits_dtype=torch.float32
    

FSDP2 uses mixed_precision policy (so it works with model.to(float32) in BaseTrainer),
while DeepSpeed relies on transformers/deepspeed configs, so compute dtype and parameter storage dtype are always consistent.

Currently, the bf16 argument only applies to FSDP2. DeepSpeed precision is controlled by YAML config.

Before submitting

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, 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 memory efficiency during model training, particularly for large language models. It integrates DeepSpeed Zero3, a state-of-the-art memory optimization technique, to facilitate low-memory weight loading. Additionally, activation checkpointing is now enabled by default, providing another layer of memory reduction. These changes aim to make training larger models more accessible and stable by optimizing resource utilization.

Highlights

  • DeepSpeed Zero3 Integration: Implemented logic to enable DeepSpeed Zero3 for low memory weight loading during training, leveraging a new utility for configuration.
  • Activation Checkpointing Default: Changed the default setting for activation checkpointing to 'True' to further reduce memory consumption.
  • Distributed Configuration Access: Stored the distributed configuration within the accelerator interface for broader access and use in model initialization.
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.

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
Copy Markdown
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 support for DeepSpeed ZeRO stage 3 during model weight loading to reduce memory usage. The changes involve adding a new utility module for DeepSpeed configuration, modifying the model initialization logic to trigger DeepSpeed, and updating some configuration defaults.

My main concern is a potential issue in distributed initialization. The new logic calls deepspeed.init_distributed() after DistributedInterface has likely already initialized the process group, which would cause a runtime error. I've left a critical comment with details on this.

I've also added a medium-severity comment to improve the readability of a new helper function in deepspeed_utils.py. Other changes, like updating dtype to torch_dtype and changing the default for enable_activation_checkpointing, are appropriate.


from ..utils.deepspeed_utils import init_hf_deepspeed_config

deepspeed.init_distributed(dist_backend=get_process_group_backend(), auto_mpi_discovery=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.

critical

Calling deepspeed.init_distributed() here will likely cause a RuntimeError because the distributed process group has probably already been initialized. The DistributedInterface is a singleton, and its __init__ method calls init_process_group(). Since ModelEngine is instantiated after DistributedInterface is first used (e.g., on line 98), this will result in an attempt to initialize the process group twice.

All distributed initialization logic, including the special handling for DeepSpeed, should be consolidated within the DistributedInterface class. This would involve moving this DeepSpeed-specific block into DistributedInterface.__init__ and making the standard init_process_group() call conditional based on whether DeepSpeed is being used.

Comment on lines +21 to +38
def _resolve_mixed_precision(ds_config: dict[str, Any]) -> tuple[bool, bool]:
bf16_enabled = ds_config.get("bf16", {}).get("enabled", "auto")
fp16_enabled = ds_config.get("fp16", {}).get("enabled", "auto")

if bf16_enabled == "auto" and fp16_enabled == "auto":
return True, False
if bf16_enabled == "auto":
return not bool(fp16_enabled), bool(fp16_enabled)
if fp16_enabled == "auto":
return bool(bf16_enabled), not bool(bf16_enabled)

bf16_enabled = bool(bf16_enabled)
fp16_enabled = bool(fp16_enabled)
if bf16_enabled and fp16_enabled:
fp16_enabled = False
if not bf16_enabled and not fp16_enabled:
bf16_enabled = True
return bf16_enabled, fp16_enabled
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.

medium

This function's logic for resolving mixed precision settings is correct but quite dense and can be difficult to parse. To improve readability and maintainability, consider refactoring it to be more explicit about the decision-making process, as shown in the suggestion.

def _resolve_mixed_precision(ds_config: dict[str, Any]) -> tuple[bool, bool]:
    bf16_enabled_in = ds_config.get("bf16", {}).get("enabled", "auto")
    fp16_enabled_in = ds_config.get("fp16", {}).get("enabled", "auto")

    # Case 1: Both are "auto", default to bf16.
    if bf16_enabled_in == "auto" and fp16_enabled_in == "auto":
        return True, False

    # Case 2: One is "auto", infer from the other.
    if bf16_enabled_in == "auto":
        fp16_enabled = bool(fp16_enabled_in)
        return not fp16_enabled, fp16_enabled
    if fp16_enabled_in == "auto":
        bf16_enabled = bool(bf16_enabled_in)
        return bf16_enabled, not bf16_enabled

    # Case 3: Both are explicitly set, convert to bool.
    bf16_enabled = bool(bf16_enabled_in)
    fp16_enabled = bool(fp16_enabled_in)

    if bf16_enabled and fp16_enabled:
        # bf16 has priority over fp16.
        return True, False

    if not bf16_enabled and not fp16_enabled:
        # If both are disabled, default to bf16.
        return True, False

    return bf16_enabled, fp16_enabled

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