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
+294 -185

No files matched your search

+93 -79
View File
@@ -94,85 +94,94 @@ 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:
# todo move this to data loader with self.timer('get_adapter_images'):
if batch.control_tensor is not None: # todo move this to data loader
adapter_images = batch.control_tensor.to(self.device_torch, dtype=dtype).detach() if batch.control_tensor is not None:
else: adapter_images = batch.control_tensor.to(self.device_torch, dtype=dtype).detach()
adapter_images = self.get_adapter_images(batch) else:
# not 100% sure what this does. But they do it here adapter_images = self.get_adapter_images(batch)
# https://github.com/huggingface/diffusers/blob/38a664a3d61e27ab18cd698231422b3c38d6eebf/examples/t2i_adapter/train_t2i_adapter_sdxl.py#L1170 # not 100% sure what this does. But they do it here
# sigmas = self.get_sigmas(timesteps, len(noisy_latents.shape), noisy_latents.dtype) # https://github.com/huggingface/diffusers/blob/38a664a3d61e27ab18cd698231422b3c38d6eebf/examples/t2i_adapter/train_t2i_adapter_sdxl.py#L1170
# noisy_latents = noisy_latents / ((sigmas ** 2 + 1) ** 0.5) # sigmas = self.get_sigmas(timesteps, len(noisy_latents.shape), noisy_latents.dtype)
# noisy_latents = noisy_latents / ((sigmas ** 2 + 1) ** 0.5)
mask_multiplier = 1.0 mask_multiplier = 1.0
if batch.mask_tensor is not None: if batch.mask_tensor is not None:
# upsampling no supported for bfloat16 with self.timer('get_mask_multiplier'):
mask_multiplier = batch.mask_tensor.to(self.device_torch, dtype=torch.float16).detach() # upsampling no supported for bfloat16
# scale down to the size of the latents, mask multiplier shape(bs, 1, width, height), noisy_latents shape(bs, channels, width, height) mask_multiplier = batch.mask_tensor.to(self.device_torch, dtype=torch.float16).detach()
mask_multiplier = torch.nn.functional.interpolate( # scale down to the size of the latents, mask multiplier shape(bs, 1, width, height), noisy_latents shape(bs, channels, width, height)
mask_multiplier, size=(noisy_latents.shape[2], noisy_latents.shape[3]) mask_multiplier = torch.nn.functional.interpolate(
) mask_multiplier, size=(noisy_latents.shape[2], noisy_latents.shape[3])
# expand to match latents )
mask_multiplier = mask_multiplier.expand(-1, noisy_latents.shape[1], -1, -1) # expand to match latents
mask_multiplier = mask_multiplier.to(self.device_torch, dtype=dtype).detach() mask_multiplier = mask_multiplier.expand(-1, noisy_latents.shape[1], -1, -1)
mask_multiplier = mask_multiplier.to(self.device_torch, dtype=dtype).detach()
# flush() # flush()
self.optimizer.zero_grad() with self.timer('grad_setup'):
self.optimizer.zero_grad()
# text encoding # text encoding
grad_on_text_encoder = False grad_on_text_encoder = False
if self.train_config.train_text_encoder: if self.train_config.train_text_encoder:
grad_on_text_encoder = True grad_on_text_encoder = True
if self.embedding: if self.embedding:
grad_on_text_encoder = True grad_on_text_encoder = True
# have a blank network so we can wrap it in a context and set multipliers without checking every time # have a blank network so we can wrap it in a context and set multipliers without checking every time
if self.network is not None: if self.network is not None:
network = self.network network = self.network
else: else:
network = BlankNetwork() network = BlankNetwork()
# set the weights # set the weights
network.multiplier = network_weight_list network.multiplier = network_weight_list
# activate network if it exits # activate network if it exits
with network: with network:
with torch.set_grad_enabled(grad_on_text_encoder): with self.timer('encode_prompt'):
conditional_embeds = self.sd.encode_prompt(conditioned_prompts).to(self.device_torch, dtype=dtype) with torch.set_grad_enabled(grad_on_text_encoder):
if not grad_on_text_encoder: conditional_embeds = self.sd.encode_prompt(conditioned_prompts).to(self.device_torch, dtype=dtype)
# detach the embeddings if not grad_on_text_encoder:
conditional_embeds = conditional_embeds.detach() # detach the embeddings
conditional_embeds = conditional_embeds.detach()
# flush() # flush()
pred_kwargs = {} pred_kwargs = {}
if self.adapter and isinstance(self.adapter, T2IAdapter): if self.adapter and isinstance(self.adapter, T2IAdapter):
down_block_additional_residuals = self.adapter(adapter_images) with self.timer('encode_adapter'):
down_block_additional_residuals = [ down_block_additional_residuals = self.adapter(adapter_images)
sample.to(dtype=dtype) for sample in down_block_additional_residuals down_block_additional_residuals = [
] sample.to(dtype=dtype) for sample in down_block_additional_residuals
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 torch.no_grad(): with self.timer('encode_adapter'):
conditional_clip_embeds = self.adapter.get_clip_image_embeds_from_tensors(adapter_images) with torch.no_grad():
conditional_embeds = self.adapter(conditional_embeds, conditional_clip_embeds) conditional_clip_embeds = self.adapter.get_clip_image_embeds_from_tensors(adapter_images)
conditional_embeds = self.adapter(conditional_embeds, conditional_clip_embeds)
noise_pred = self.sd.predict_noise( with self.timer('predict_unet'):
latents=noisy_latents.to(self.device_torch, dtype=dtype), noise_pred = self.sd.predict_noise(
conditional_embeddings=conditional_embeds.to(self.device_torch, dtype=dtype), latents=noisy_latents.to(self.device_torch, dtype=dtype),
timestep=timesteps, conditional_embeddings=conditional_embeds.to(self.device_torch, dtype=dtype),
guidance_scale=1.0, timestep=timesteps,
**pred_kwargs guidance_scale=1.0,
) **pred_kwargs
)
# if self.adapter: # if self.adapter:
# # todo, diffusers does this on t2i training, is it better approach? # # todo, diffusers does this on t2i training, is it better approach?
@@ -194,43 +203,48 @@ class SDTrainer(BaseSDTrainProcess):
# dim=1, # dim=1,
# ) # )
# else: # else:
noise = noise.to(self.device_torch, dtype=dtype).detach() with self.timer('calculate_loss'):
if self.sd.prediction_type == 'v_prediction': noise = noise.to(self.device_torch, dtype=dtype).detach()
# v-parameterization training if self.sd.prediction_type == 'v_prediction':
target = self.sd.noise_scheduler.get_velocity(noisy_latents, noise, timesteps) # v-parameterization training
else: target = self.sd.noise_scheduler.get_velocity(noisy_latents, noise, timesteps)
target = noise else:
loss = torch.nn.functional.mse_loss(noise_pred.float(), target.float(), reduction="none") target = noise
# multiply by our mask loss = torch.nn.functional.mse_loss(noise_pred.float(), target.float(), reduction="none")
loss = loss * mask_multiplier # multiply by our mask
loss = loss * mask_multiplier
loss = loss.mean([1, 2, 3]) loss = loss.mean([1, 2, 3])
if self.train_config.min_snr_gamma is not None and self.train_config.min_snr_gamma > 0.000001: if self.train_config.min_snr_gamma is not None and self.train_config.min_snr_gamma > 0.000001:
# add min_snr_gamma # add min_snr_gamma
loss = apply_snr_weight(loss, timesteps, self.sd.noise_scheduler, self.train_config.min_snr_gamma) loss = apply_snr_weight(loss, timesteps, self.sd.noise_scheduler, self.train_config.min_snr_gamma)
loss = loss.mean() loss = loss.mean()
# check if nan # check if nan
if torch.isnan(loss): if torch.isnan(loss):
raise ValueError("loss is nan") raise ValueError("loss is nan")
# IMPORTANT if gradient checkpointing do not leave with network when doing backward with self.timer('backward'):
# it will destroy the gradients. This is because the network is a context manager # IMPORTANT if gradient checkpointing do not leave with network when doing backward
# and will change the multipliers back to 0.0 when exiting. They will be # it will destroy the gradients. This is because the network is a context manager
# 0.0 for the backward pass and the gradients will be 0.0 # and will change the multipliers back to 0.0 when exiting. They will be
# I spent weeks on fighting this. DON'T DO IT # 0.0 for the backward pass and the gradients will be 0.0
loss.backward() # I spent weeks on fighting this. DON'T DO IT
torch.nn.utils.clip_grad_norm_(self.params, self.train_config.max_grad_norm) loss.backward()
# flush() torch.nn.utils.clip_grad_norm_(self.params, self.train_config.max_grad_norm)
# flush()
# apply gradients with self.timer('optimizer_step'):
self.optimizer.step() # apply gradients
self.lr_scheduler.step() self.optimizer.step()
with self.timer('scheduler_step'):
self.lr_scheduler.step()
if self.embedding is not None: if self.embedding is not None:
# Let's make sure we don't update any embedding weights besides the newly added token with self.timer('restore_embeddings'):
self.embedding.restore_embeddings() # Let's make sure we don't update any embedding weights besides the newly added token
self.embedding.restore_embeddings()
loss_dict = OrderedDict( loss_dict = OrderedDict(
{'loss': loss.item()} {'loss': loss.item()}
+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):
+122 -98
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,98 +443,102 @@ 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():
prompts = batch.get_caption_list() with self.timer('prepare_prompt'):
is_reg_list = batch.get_is_reg_list() prompts = batch.get_caption_list()
is_reg_list = batch.get_is_reg_list()
conditioned_prompts = [] conditioned_prompts = []
for prompt, is_reg in zip(prompts, is_reg_list): for prompt, is_reg in zip(prompts, is_reg_list):
# make sure the embedding is in the prompts # make sure the embedding is in the prompts
if self.embedding is not None: if self.embedding is not None:
prompt = self.embedding.inject_embedding_to_prompt( prompt = self.embedding.inject_embedding_to_prompt(
prompt, prompt,
expand_token=True, expand_token=True,
add_if_not_present=not is_reg, add_if_not_present=not is_reg,
) )
# make sure trigger is in the prompts if not a regularization run # make sure trigger is in the prompts if not a regularization run
if self.trigger_word is not None: if self.trigger_word is not None:
prompt = self.sd.inject_trigger_into_prompt( prompt = self.sd.inject_trigger_into_prompt(
prompt, prompt,
trigger=self.trigger_word, trigger=self.trigger_word,
add_if_not_present=not is_reg, add_if_not_present=not is_reg,
) )
conditioned_prompts.append(prompt) conditioned_prompts.append(prompt)
dtype = get_torch_dtype(self.train_config.dtype) with self.timer('prepare_latents'):
imgs = None dtype = get_torch_dtype(self.train_config.dtype)
if batch.tensor is not None: imgs = None
imgs = batch.tensor if batch.tensor is not None:
imgs = imgs.to(self.device_torch, dtype=dtype) imgs = batch.tensor
if batch.latents is not None: imgs = imgs.to(self.device_torch, dtype=dtype)
latents = batch.latents.to(self.device_torch, dtype=dtype) if batch.latents is not None:
batch.latents = latents latents = batch.latents.to(self.device_torch, dtype=dtype)
else: batch.latents = latents
latents = self.sd.encode_images(imgs) else:
batch.latents = latents latents = self.sd.encode_images(imgs)
flush() batch.latents = latents
# flush() # todo check performance removing this
batch_size = latents.shape[0] batch_size = latents.shape[0]
self.sd.noise_scheduler.set_timesteps( with self.timer('prepare_noise'):
1000, device=self.device_torch
)
# if self.train_config.timestep_sampling == 'style' or self.train_config.timestep_sampling == 'content': self.sd.noise_scheduler.set_timesteps(
if self.train_config.content_or_style in ['style', 'content']: 1000, device=self.device_torch
# this is from diffusers training code
# Cubic sampling for favoring later or earlier timesteps
# For more details about why cubic sampling is used for content / structure,
# refer to section 3.4 of https://arxiv.org/abs/2302.08453
# for content / structure, it is best to favor earlier timesteps
# for style, it is best to favor later timesteps
timesteps = torch.rand((batch_size,), device=latents.device)
if self.train_config.content_or_style == 'style':
timesteps = timesteps ** 3 * self.sd.noise_scheduler.config['num_train_timesteps']
elif self.train_config.content_or_style == 'content':
timesteps = (1 - timesteps ** 3) * self.sd.noise_scheduler.config['num_train_timesteps']
timesteps = value_map(
timesteps,
0,
self.sd.noise_scheduler.config['num_train_timesteps'] - 1,
self.train_config.min_denoising_steps,
self.train_config.max_denoising_steps
)
timesteps = timesteps.long().clamp(
self.train_config.min_denoising_steps,
self.train_config.max_denoising_steps - 1
) )
elif self.train_config.content_or_style == 'balanced': # if self.train_config.timestep_sampling == 'style' or self.train_config.timestep_sampling == 'content':
timesteps = torch.randint( if self.train_config.content_or_style in ['style', 'content']:
self.train_config.min_denoising_steps, # this is from diffusers training code
self.train_config.max_denoising_steps, # Cubic sampling for favoring later or earlier timesteps
(batch_size,), # For more details about why cubic sampling is used for content / structure,
device=self.device_torch # refer to section 3.4 of https://arxiv.org/abs/2302.08453
)
timesteps = timesteps.long()
else:
raise ValueError(f"Unknown content_or_style {self.train_config.content_or_style}")
# get noise # for content / structure, it is best to favor earlier timesteps
noise = self.sd.get_latent_noise( # for style, it is best to favor later timesteps
height=latents.shape[2],
width=latents.shape[3],
batch_size=batch_size,
noise_offset=self.train_config.noise_offset
).to(self.device_torch, dtype=dtype)
noisy_latents = self.sd.noise_scheduler.add_noise(latents, noise, timesteps) timesteps = torch.rand((batch_size,), device=latents.device)
if self.train_config.content_or_style == 'style':
timesteps = timesteps ** 3 * self.sd.noise_scheduler.config['num_train_timesteps']
elif self.train_config.content_or_style == 'content':
timesteps = (1 - timesteps ** 3) * self.sd.noise_scheduler.config['num_train_timesteps']
timesteps = value_map(
timesteps,
0,
self.sd.noise_scheduler.config['num_train_timesteps'] - 1,
self.train_config.min_denoising_steps,
self.train_config.max_denoising_steps
)
timesteps = timesteps.long().clamp(
self.train_config.min_denoising_steps,
self.train_config.max_denoising_steps - 1
)
elif self.train_config.content_or_style == 'balanced':
timesteps = torch.randint(
self.train_config.min_denoising_steps,
self.train_config.max_denoising_steps,
(batch_size,),
device=self.device_torch
)
timesteps = timesteps.long()
else:
raise ValueError(f"Unknown content_or_style {self.train_config.content_or_style}")
# get noise
noise = self.sd.get_latent_noise(
height=latents.shape[2],
width=latents.shape[3],
batch_size=batch_size,
noise_offset=self.train_config.noise_offset
).to(self.device_torch, dtype=dtype)
noisy_latents = self.sd.noise_scheduler.add_noise(latents, noise, timesteps)
# remove grads for these # remove grads for these
noisy_latents.requires_grad = False noisy_latents.requires_grad = False
@@ -933,24 +938,31 @@ 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:
batch = next(dataloader_iterator_reg) with self.timer('get_batch:reg'):
batch = next(dataloader_iterator_reg)
except StopIteration: except StopIteration:
# hit the end of an epoch, reset with self.timer('reset_batch:reg'):
self.progress_bar.pause() # hit the end of an epoch, reset
dataloader_iterator_reg = iter(dataloader_reg) self.progress_bar.pause()
trigger_dataloader_setup_epoch(dataloader_reg) dataloader_iterator_reg = iter(dataloader_reg)
batch = next(dataloader_iterator_reg) trigger_dataloader_setup_epoch(dataloader_reg)
with self.timer('get_batch: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:
batch = next(dataloader_iterator) with self.timer('get_batch'):
batch = next(dataloader_iterator)
except StopIteration: except StopIteration:
# hit the end of an epoch, reset with self.timer('reset_batch'):
self.progress_bar.pause() # hit the end of an epoch, reset
dataloader_iterator = iter(dataloader) self.progress_bar.pause()
trigger_dataloader_setup_epoch(dataloader) dataloader_iterator = iter(dataloader)
batch = next(dataloader_iterator) trigger_dataloader_setup_epoch(dataloader)
with self.timer('get_batch'):
batch = next(dataloader_iterator)
self.progress_bar.unpause() self.progress_bar.unpause()
else: else:
batch = None batch = None
@@ -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,11 +1012,19 @@ 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()
# log to tensorboard with self.timer('log_to_tensorboard'):
if self.writer is not None: # log to tensorboard
for key, value in loss_dict.items(): if self.writer is not None:
self.writer.add_scalar(f"{key}", value, self.step_num) for key, value in loss_dict.items():
self.writer.add_scalar(f"lr", learning_rate, self.step_num) self.writer.add_scalar(f"{key}", value, self.step_num)
self.writer.add_scalar(f"lr", learning_rate, self.step_num)
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() self.progress_bar.unpause()
# sets progress bar to match out step # sets progress bar to match out step
@@ -1012,11 +1034,13 @@ 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:
self.network.apply_stored_normalizer() with self.timer('apply_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):
batch.cleanup() with self.timer('batch_cleanup'):
batch.cleanup()
# flush every 10 steps # flush every 10 steps
# if self.step_num % 10 == 0: # if self.step_num % 10 == 0:
+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)