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

[Fix] Fix dtype error in StableDiffusion and DreamBooth training #1879

Merged
merged 2 commits into from
May 29, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
10 changes: 6 additions & 4 deletions mmagic/models/editors/dreambooth/dreambooth.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,10 +287,12 @@ def train_step(self, data, optim_wrapper):
f'{self.scheduler.config.prediction_type}')

# NOTE: we train unet in fp32, convert to float manually
model_output = self.unet(
noisy_latents.float(),
timesteps,
encoder_hidden_states=encoder_hidden_states.float())
device_type = 'cuda' if torch.cuda.is_available() else 'cpu'
with torch.autocast(device_type=device_type, dtype=torch.float32):
model_output = self.unet(
noisy_latents.float(),
timesteps,
encoder_hidden_states=encoder_hidden_states.float())
model_pred = model_output['sample']

loss_dict = dict()
Expand Down
24 changes: 18 additions & 6 deletions mmagic/models/editors/stable_diffusion/stable_diffusion.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,17 @@ def __init__(self,
default_args = dict()
if dtype is not None:
default_args['dtype'] = dtype
self.dtype = dtype

self.dtype = torch.float32
if dtype in ['float16', 'fp16', 'half']:
self.dtype = torch.float16
elif dtype == 'bf16':
self.dtype = torch.bfloat16
else:
assert dtype in [
'fp32', None
], ('dtype must be one of \'fp32\', \'fp16\', \'bf16\' or None.')

self.vae = build_module(vae, MODELS, default_args=default_args)
self.unet = build_module(unet, MODELS, default_args=default_args)
self.scheduler = build_module(scheduler, DIFFUSION_SCHEDULERS)
Expand Down Expand Up @@ -627,11 +637,13 @@ def train_step(self, data, optim_wrapper_dict):
raise ValueError('Unknown prediction type '
f'{self.scheduler.config.prediction_type}')

# NOTE: convert to float manually
model_output = self.unet(
noisy_latents.float(),
timesteps,
encoder_hidden_states=encoder_hidden_states.float())
# NOTE: we train unet in fp32, convert to float manually
device_type = 'cuda' if torch.cuda.is_available() else 'cpu'
with torch.autocast(device_type=device_type, dtype=torch.float32):
model_output = self.unet(
noisy_latents.float(),
timesteps,
encoder_hidden_states=encoder_hidden_states.float())
model_pred = model_output['sample']

loss_dict = dict()
Expand Down