Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixup Zero3 + save_model #3146

Merged
merged 3 commits into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/accelerate/accelerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2838,8 +2838,6 @@ def save_model(
logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
return

os.makedirs(save_directory, exist_ok=True)

# get the state_dict of the model
if any(
[
Expand All @@ -2854,6 +2852,11 @@ def save_model(
raise RuntimeError("You can't save the model since some parameters are on the meta device.")
state_dict = self.get_state_dict(model)

# Case: DeepSpeed zero3 gets gathered and `state_dict` is empty
if state_dict is None:
return
Comment on lines +2855 to +2857
Copy link
Member

Choose a reason for hiding this comment

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

We can maybe make it more specific to deepspeed ?
In their code, this is how they do this: https://github.com/microsoft/DeepSpeed/blob/f3943cf9109226ed3ecf2d5dbb639a11cd925555/deepspeed/runtime/engine.py#L3414
Seems like the model only gets saved on rank 0

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I went more generic just in case somehow this happens in other places that we don't know yet (so we enable and don't block them)

os.makedirs(save_directory, exist_ok=True)

if safe_serialization:
state_dict = clean_state_dict_for_safetensors(state_dict)
weights_name = SAFE_WEIGHTS_NAME if safe_serialization else WEIGHTS_NAME
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import argparse
import json
import os
from pathlib import Path

import evaluate
import torch
Expand Down Expand Up @@ -205,6 +206,13 @@ def training_function(config, args):
if accelerator.is_main_process:
with open(os.path.join(args.output_dir, "all_results.json"), "w") as f:
json.dump(performance_metric, f)

# Finally try saving the model
accelerator.save_model(model, args.output_dir)
accelerator.wait_for_everyone()
assert Path(
args.output_dir, "model.safetensors"
).exists(), "Model was not saved when calling `Accelerator.save_model`"
accelerator.end_training()


Expand Down
Loading