Massive speed increases and ram optimizations

This commit is contained in:
Jaret Burkett committed 2023-10-10 06:07:55 -06:00
1 parent f4c90bb589
commit 63ceffae24
7 files changed
+118 -9

No files matched your search

@@ -94,14 +94,17 @@ class SDTrainer(BaseSDTrainProcess):
def hook_train_loop(self, batch): def hook_train_loop(self, batch):
self.timer.start('preprocess_batch')
dtype = get_torch_dtype(self.train_config.dtype) dtype = get_torch_dtype(self.train_config.dtype)
noisy_latents, noise, timesteps, conditioned_prompts, imgs = self.process_general_training_batch(batch) noisy_latents, noise, timesteps, conditioned_prompts, imgs = self.process_general_training_batch(batch)
network_weight_list = batch.get_network_weight_list() network_weight_list = batch.get_network_weight_list()
self.timer.stop('preprocess_batch')
with torch.no_grad(): with torch.no_grad():
adapter_images = None adapter_images = None
sigmas = None sigmas = None
if self.adapter: if self.adapter:
with self.timer('get_adapter_images'):
# todo move this to data loader # todo move this to data loader
if batch.control_tensor is not None: if batch.control_tensor is not None:
adapter_images = batch.control_tensor.to(self.device_torch, dtype=dtype).detach() adapter_images = batch.control_tensor.to(self.device_torch, dtype=dtype).detach()
@@ -114,6 +117,7 @@ class SDTrainer(BaseSDTrainProcess):
mask_multiplier = 1.0 mask_multiplier = 1.0
if batch.mask_tensor is not None: if batch.mask_tensor is not None:
with self.timer('get_mask_multiplier'):
# upsampling no supported for bfloat16 # upsampling no supported for bfloat16
mask_multiplier = batch.mask_tensor.to(self.device_torch, dtype=torch.float16).detach() mask_multiplier = batch.mask_tensor.to(self.device_torch, dtype=torch.float16).detach()
# scale down to the size of the latents, mask multiplier shape(bs, 1, width, height), noisy_latents shape(bs, channels, width, height) # scale down to the size of the latents, mask multiplier shape(bs, 1, width, height), noisy_latents shape(bs, channels, width, height)
@@ -125,6 +129,7 @@ class SDTrainer(BaseSDTrainProcess):
mask_multiplier = mask_multiplier.to(self.device_torch, dtype=dtype).detach() mask_multiplier = mask_multiplier.to(self.device_torch, dtype=dtype).detach()
# flush() # flush()
with self.timer('grad_setup'):
self.optimizer.zero_grad() self.optimizer.zero_grad()
# text encoding # text encoding
@@ -146,6 +151,7 @@ class SDTrainer(BaseSDTrainProcess):
# activate network if it exits # activate network if it exits
with network: with network:
with self.timer('encode_prompt'):
with torch.set_grad_enabled(grad_on_text_encoder): with torch.set_grad_enabled(grad_on_text_encoder):
conditional_embeds = self.sd.encode_prompt(conditioned_prompts).to(self.device_torch, dtype=dtype) conditional_embeds = self.sd.encode_prompt(conditioned_prompts).to(self.device_torch, dtype=dtype)
if not grad_on_text_encoder: if not grad_on_text_encoder:
@@ -154,6 +160,7 @@ class SDTrainer(BaseSDTrainProcess):
# flush() # flush()
pred_kwargs = {} pred_kwargs = {}
if self.adapter and isinstance(self.adapter, T2IAdapter): if self.adapter and isinstance(self.adapter, T2IAdapter):
with self.timer('encode_adapter'):
down_block_additional_residuals = self.adapter(adapter_images) down_block_additional_residuals = self.adapter(adapter_images)
down_block_additional_residuals = [ down_block_additional_residuals = [
sample.to(dtype=dtype) for sample in down_block_additional_residuals sample.to(dtype=dtype) for sample in down_block_additional_residuals
@@ -161,11 +168,13 @@ class SDTrainer(BaseSDTrainProcess):
pred_kwargs['down_block_additional_residuals'] = down_block_additional_residuals pred_kwargs['down_block_additional_residuals'] = down_block_additional_residuals
if self.adapter and isinstance(self.adapter, IPAdapter): if self.adapter and isinstance(self.adapter, IPAdapter):
with self.timer('encode_adapter'):
with torch.no_grad(): with torch.no_grad():
conditional_clip_embeds = self.adapter.get_clip_image_embeds_from_tensors(adapter_images) conditional_clip_embeds = self.adapter.get_clip_image_embeds_from_tensors(adapter_images)
conditional_embeds = self.adapter(conditional_embeds, conditional_clip_embeds) conditional_embeds = self.adapter(conditional_embeds, conditional_clip_embeds)
with self.timer('predict_unet'):
noise_pred = self.sd.predict_noise( noise_pred = self.sd.predict_noise(
latents=noisy_latents.to(self.device_torch, dtype=dtype), latents=noisy_latents.to(self.device_torch, dtype=dtype),
conditional_embeddings=conditional_embeds.to(self.device_torch, dtype=dtype), conditional_embeddings=conditional_embeds.to(self.device_torch, dtype=dtype),
@@ -194,6 +203,7 @@ class SDTrainer(BaseSDTrainProcess):
# dim=1, # dim=1,
# ) # )
# else: # else:
with self.timer('calculate_loss'):
noise = noise.to(self.device_torch, dtype=dtype).detach() noise = noise.to(self.device_torch, dtype=dtype).detach()
if self.sd.prediction_type == 'v_prediction': if self.sd.prediction_type == 'v_prediction':
# v-parameterization training # v-parameterization training
@@ -215,6 +225,7 @@ class SDTrainer(BaseSDTrainProcess):
if torch.isnan(loss): if torch.isnan(loss):
raise ValueError("loss is nan") raise ValueError("loss is nan")
with self.timer('backward'):
# IMPORTANT if gradient checkpointing do not leave with network when doing backward # IMPORTANT if gradient checkpointing do not leave with network when doing backward
# it will destroy the gradients. This is because the network is a context manager # it will destroy the gradients. This is because the network is a context manager
# and will change the multipliers back to 0.0 when exiting. They will be # and will change the multipliers back to 0.0 when exiting. They will be
@@ -224,11 +235,14 @@ class SDTrainer(BaseSDTrainProcess):
torch.nn.utils.clip_grad_norm_(self.params, self.train_config.max_grad_norm) torch.nn.utils.clip_grad_norm_(self.params, self.train_config.max_grad_norm)
# flush() # flush()
with self.timer('optimizer_step'):
# apply gradients # apply gradients
self.optimizer.step() self.optimizer.step()
with self.timer('scheduler_step'):
self.lr_scheduler.step() self.lr_scheduler.step()
if self.embedding is not None: if self.embedding is not None:
with self.timer('restore_embeddings'):
# Let's make sure we don't update any embedding weights besides the newly added token # Let's make sure we don't update any embedding weights besides the newly added token
self.embedding.restore_embeddings() self.embedding.restore_embeddings()
+5
View File
@@ -2,6 +2,8 @@ import copy
import json import json
from collections import OrderedDict from collections import OrderedDict
from toolkit.timer import Timer
class BaseProcess(object): class BaseProcess(object):
@@ -18,6 +20,9 @@ class BaseProcess(object):
self.raw_process_config = config self.raw_process_config = config
self.name = self.get_conf('name', self.job.name) self.name = self.get_conf('name', self.job.name)
self.meta = copy.deepcopy(self.job.meta) self.meta = copy.deepcopy(self.job.meta)
self.timer: Timer = Timer(f'{self.name} Timer')
self.performance_log_every = self.get_conf('performance_log_every', 0)
print(json.dumps(self.config, indent=4)) print(json.dumps(self.config, indent=4))
def get_conf(self, key, default=None, required=False, as_type=None): def get_conf(self, key, default=None, required=False, as_type=None):
+25 -1
View File
@@ -144,6 +144,7 @@ class BaseSDTrainProcess(BaseTrainProcess):
self.named_lora = False self.named_lora = False
if self.embed_config is not None or is_training_adapter: if self.embed_config is not None or is_training_adapter:
self.named_lora = True self.named_lora = True
def post_process_generate_image_config_list(self, generate_image_config_list: List[GenerateImageConfig]): def post_process_generate_image_config_list(self, generate_image_config_list: List[GenerateImageConfig]):
# override in subclass # override in subclass
return generate_image_config_list return generate_image_config_list
@@ -442,6 +443,7 @@ class BaseSDTrainProcess(BaseTrainProcess):
def process_general_training_batch(self, batch: 'DataLoaderBatchDTO'): def process_general_training_batch(self, batch: 'DataLoaderBatchDTO'):
with torch.no_grad(): with torch.no_grad():
with self.timer('prepare_prompt'):
prompts = batch.get_caption_list() prompts = batch.get_caption_list()
is_reg_list = batch.get_is_reg_list() is_reg_list = batch.get_is_reg_list()
@@ -466,6 +468,7 @@ class BaseSDTrainProcess(BaseTrainProcess):
) )
conditioned_prompts.append(prompt) conditioned_prompts.append(prompt)
with self.timer('prepare_latents'):
dtype = get_torch_dtype(self.train_config.dtype) dtype = get_torch_dtype(self.train_config.dtype)
imgs = None imgs = None
if batch.tensor is not None: if batch.tensor is not None:
@@ -477,10 +480,12 @@ class BaseSDTrainProcess(BaseTrainProcess):
else: else:
latents = self.sd.encode_images(imgs) latents = self.sd.encode_images(imgs)
batch.latents = latents batch.latents = latents
flush() # flush() # todo check performance removing this
batch_size = latents.shape[0] batch_size = latents.shape[0]
with self.timer('prepare_noise'):
self.sd.noise_scheduler.set_timesteps( self.sd.noise_scheduler.set_timesteps(
1000, device=self.device_torch 1000, device=self.device_torch
) )
@@ -933,23 +938,30 @@ class BaseSDTrainProcess(BaseTrainProcess):
# don't do a reg step on sample or save steps as we dont want to normalize on those # don't do a reg step on sample or save steps as we dont want to normalize on those
if step % 2 == 0 and dataloader_reg is not None and not is_save_step and not is_sample_step: if step % 2 == 0 and dataloader_reg is not None and not is_save_step and not is_sample_step:
try: try:
with self.timer('get_batch:reg'):
batch = next(dataloader_iterator_reg) batch = next(dataloader_iterator_reg)
except StopIteration: except StopIteration:
with self.timer('reset_batch:reg'):
# hit the end of an epoch, reset # hit the end of an epoch, reset
self.progress_bar.pause() self.progress_bar.pause()
dataloader_iterator_reg = iter(dataloader_reg) dataloader_iterator_reg = iter(dataloader_reg)
trigger_dataloader_setup_epoch(dataloader_reg) trigger_dataloader_setup_epoch(dataloader_reg)
with self.timer('get_batch:reg'):
batch = next(dataloader_iterator_reg) batch = next(dataloader_iterator_reg)
self.progress_bar.unpause() self.progress_bar.unpause()
is_reg_step = True is_reg_step = True
elif dataloader is not None: elif dataloader is not None:
try: try:
with self.timer('get_batch'):
batch = next(dataloader_iterator) batch = next(dataloader_iterator)
except StopIteration: except StopIteration:
with self.timer('reset_batch'):
# hit the end of an epoch, reset # hit the end of an epoch, reset
self.progress_bar.pause() self.progress_bar.pause()
dataloader_iterator = iter(dataloader) dataloader_iterator = iter(dataloader)
trigger_dataloader_setup_epoch(dataloader) trigger_dataloader_setup_epoch(dataloader)
with self.timer('get_batch'):
batch = next(dataloader_iterator) batch = next(dataloader_iterator)
self.progress_bar.unpause() self.progress_bar.unpause()
else: else:
@@ -960,7 +972,9 @@ class BaseSDTrainProcess(BaseTrainProcess):
self.network.is_normalizing = True self.network.is_normalizing = True
# flush() # flush()
### HOOK ### ### HOOK ###
self.timer.start('train_loop')
loss_dict = self.hook_train_loop(batch) loss_dict = self.hook_train_loop(batch)
self.timer.stop('train_loop')
# flush() # flush()
# setup the networks to gradient checkpointing and everything works # setup the networks to gradient checkpointing and everything works
@@ -998,6 +1012,7 @@ class BaseSDTrainProcess(BaseTrainProcess):
if self.logging_config.log_every and self.step_num % self.logging_config.log_every == 0: if self.logging_config.log_every and self.step_num % self.logging_config.log_every == 0:
self.progress_bar.pause() self.progress_bar.pause()
with self.timer('log_to_tensorboard'):
# log to tensorboard # log to tensorboard
if self.writer is not None: if self.writer is not None:
for key, value in loss_dict.items(): for key, value in loss_dict.items():
@@ -1005,6 +1020,13 @@ class BaseSDTrainProcess(BaseTrainProcess):
self.writer.add_scalar(f"lr", learning_rate, self.step_num) self.writer.add_scalar(f"lr", learning_rate, self.step_num)
self.progress_bar.unpause() self.progress_bar.unpause()
if self.performance_log_every > 0 and self.step_num % self.performance_log_every == 0:
self.progress_bar.pause()
# print the timers and clear them
self.timer.print()
self.timer.reset()
self.progress_bar.unpause()
# sets progress bar to match out step # sets progress bar to match out step
self.progress_bar.update(step - self.progress_bar.n) self.progress_bar.update(step - self.progress_bar.n)
# end of step # end of step
@@ -1012,10 +1034,12 @@ class BaseSDTrainProcess(BaseTrainProcess):
# apply network normalizer if we are using it, not on regularization steps # apply network normalizer if we are using it, not on regularization steps
if self.network is not None and self.network.is_normalizing and not is_reg_step: if self.network is not None and self.network.is_normalizing and not is_reg_step:
with self.timer('apply_normalizer'):
self.network.apply_stored_normalizer() self.network.apply_stored_normalizer()
# if the batch is a DataLoaderBatchDTO, then we need to clean it up # if the batch is a DataLoaderBatchDTO, then we need to clean it up
if isinstance(batch, DataLoaderBatchDTO): if isinstance(batch, DataLoaderBatchDTO):
with self.timer('batch_cleanup'):
batch.cleanup() batch.cleanup()
# flush every 10 steps # flush every 10 steps
+3 -3
View File
@@ -448,7 +448,7 @@ class AiToolkitDataset(LatentCachingMixin, BucketsMixin, CaptionMixin, Dataset):
return len(self.file_list) return len(self.file_list)
def _get_single_item(self, index) -> 'FileItemDTO': def _get_single_item(self, index) -> 'FileItemDTO':
file_item = self.file_list[index] file_item = copy.deepcopy(self.file_list[index])
file_item.load_and_process_image(self.transform) file_item.load_and_process_image(self.transform)
file_item.load_caption(self.caption_dict) file_item.load_caption(self.caption_dict)
return file_item return file_item
@@ -529,14 +529,14 @@ def get_dataloader_from_datasets(
drop_last=False, drop_last=False,
shuffle=True, shuffle=True,
collate_fn=dto_collation, # Use the custom collate function collate_fn=dto_collation, # Use the custom collate function
num_workers=0 num_workers=4
) )
else: else:
data_loader = DataLoader( data_loader = DataLoader(
concatenated_dataset, concatenated_dataset,
batch_size=batch_size, batch_size=batch_size,
shuffle=True, shuffle=True,
num_workers=0, num_workers=4,
collate_fn=dto_collation collate_fn=dto_collation
) )
return data_loader return data_loader
+2 -1
View File
@@ -670,7 +670,8 @@ class LatentCachingFileItemDTOMixin:
# load it from disk # load it from disk
state_dict = load_file( state_dict = load_file(
self.get_latent_path(), self.get_latent_path(),
device=device if device is not None else self.latent_load_device # device=device if device is not None else self.latent_load_device
device='cpu'
) )
self._encoded_latent = state_dict['latent'] self._encoded_latent = state_dict['latent']
return self._encoded_latent return self._encoded_latent
+4 -4
View File
@@ -53,7 +53,7 @@ class ToolkitModuleMixin:
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.network_ref: weakref.ref = weakref.ref(network) self.network_ref: weakref.ref = weakref.ref(network)
self.is_checkpointing = False self.is_checkpointing = False
self.is_normalizing = False # self.is_normalizing = False
self.normalize_scaler = 1.0 self.normalize_scaler = 1.0
self._multiplier: Union[float, list, torch.Tensor] = None self._multiplier: Union[float, list, torch.Tensor] = None
@@ -118,7 +118,7 @@ class ToolkitModuleMixin:
multiplier = multiplier.repeat_interleave(num_interleaves) multiplier = multiplier.repeat_interleave(num_interleaves)
# multiplier = 1.0 # multiplier = 1.0
if self.is_normalizing: if self.network_ref().is_normalizing:
with torch.no_grad(): with torch.no_grad():
# do this calculation without set multiplier and instead use same polarity, but with 1.0 multiplier # do this calculation without set multiplier and instead use same polarity, but with 1.0 multiplier
@@ -390,8 +390,8 @@ class ToolkitNetworkMixin:
@is_normalizing.setter @is_normalizing.setter
def is_normalizing(self: Network, value: bool): def is_normalizing(self: Network, value: bool):
self._is_normalizing = value self._is_normalizing = value
for module in self.get_all_modules(): # for module in self.get_all_modules():
module.is_normalizing = self._is_normalizing # module.is_normalizing = self._is_normalizing
def apply_stored_normalizer(self: Network, target_normalize_scaler: float = 1.0): def apply_stored_normalizer(self: Network, target_normalize_scaler: float = 1.0):
for module in self.get_all_modules(): for module in self.get_all_modules():
+65
View File
@@ -0,0 +1,65 @@
import time
from collections import OrderedDict, deque
class Timer:
def __init__(self, name='Timer', max_buffer=10):
self.name = name
self.max_buffer = max_buffer
self.timers = OrderedDict()
self.active_timers = {}
self.current_timer = None # Used for the context manager functionality
def start(self, timer_name):
if timer_name not in self.timers:
self.timers[timer_name] = deque(maxlen=self.max_buffer)
self.active_timers[timer_name] = time.time()
def cancel(self, timer_name):
"""Cancel an active timer."""
if timer_name in self.active_timers:
del self.active_timers[timer_name]
def stop(self, timer_name):
if timer_name not in self.active_timers:
raise ValueError(f"Timer '{timer_name}' was not started!")
elapsed_time = time.time() - self.active_timers[timer_name]
self.timers[timer_name].append(elapsed_time)
# Clean up active timers
del self.active_timers[timer_name]
# Check if this timer's buffer exceeds max_buffer and remove the oldest if it does
if len(self.timers[timer_name]) > self.max_buffer:
self.timers[timer_name].popleft()
def print(self):
print(f"\nTimer '{self.name}':")
# sort by longest at top
for timer_name, timings in sorted(self.timers.items(), key=lambda x: sum(x[1]), reverse=True):
avg_time = sum(timings) / len(timings)
print(f" - {avg_time:.4f}s avg - {timer_name}, num = {len(timings)}")
print('')
def reset(self):
self.timers.clear()
self.active_timers.clear()
def __call__(self, timer_name):
"""Enable the use of the Timer class as a context manager."""
self.current_timer = timer_name
self.start(timer_name)
return self
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is None:
# No exceptions, stop the timer normally
self.stop(self.current_timer)
else:
# There was an exception, cancel the timer
self.cancel(self.current_timer)