From fc8a18df36af2c041e26f9804f60673977547c4d Mon Sep 17 00:00:00 2001 From: Vladimir Mandic Date: Fri, 20 Dec 2024 18:58:29 -0500 Subject: [PATCH] ruff updates Signed-off-by: Vladimir Mandic --- extensions-builtin/Lora/network_lora.py | 4 ++-- modules/devices_mac.py | 4 ++-- modules/images_namegen.py | 4 ++-- modules/lora/network_lora.py | 4 ++-- modules/merging/merge_methods.py | 2 +- modules/processing_args.py | 2 +- modules/processing_helpers.py | 4 ++-- modules/sd_disable_initialization.py | 2 +- modules/sd_hijack_unet.py | 2 +- scripts/ltxvideo.py | 2 +- scripts/regional_prompting.py | 2 +- 11 files changed, 16 insertions(+), 16 deletions(-) diff --git a/extensions-builtin/Lora/network_lora.py b/extensions-builtin/Lora/network_lora.py index 8ebda2e22..a410a8e3b 100644 --- a/extensions-builtin/Lora/network_lora.py +++ b/extensions-builtin/Lora/network_lora.py @@ -31,7 +31,7 @@ class NetworkModuleLora(network.NetworkModule): if is_linear: weight = weight.reshape(weight.shape[0], -1) module = torch.nn.Linear(weight.shape[1], weight.shape[0], bias=False) - elif is_conv and key == "lora_down.weight" or key == "dyn_up": + elif is_conv and (key == "lora_down.weight" or key == "dyn_up"): if len(weight.shape) == 2: weight = weight.reshape(weight.shape[0], -1, 1, 1) if weight.shape[2] != 1 or weight.shape[3] != 1: @@ -40,7 +40,7 @@ class NetworkModuleLora(network.NetworkModule): module = torch.nn.Conv2d(weight.shape[1], weight.shape[0], (1, 1), bias=False) elif is_conv and key == "lora_mid.weight": module = torch.nn.Conv2d(weight.shape[1], weight.shape[0], self.sd_module.kernel_size, self.sd_module.stride, self.sd_module.padding, bias=False) - elif is_conv and key == "lora_up.weight" or key == "dyn_down": + elif is_conv and (key == "lora_up.weight" or key == "dyn_down"): module = torch.nn.Conv2d(weight.shape[1], weight.shape[0], (1, 1), bias=False) else: raise AssertionError(f'Lora unsupported: layer={self.network_key} type={type(self.sd_module).__name__}') diff --git a/modules/devices_mac.py b/modules/devices_mac.py index fe7c80f31..2ddc1fc22 100644 --- a/modules/devices_mac.py +++ b/modules/devices_mac.py @@ -24,7 +24,7 @@ def cumsum_fix(input, cumsum_func, *args, **kwargs): # pylint: disable=redefined output_dtype = kwargs.get('dtype', input.dtype) if output_dtype == torch.int64: return cumsum_func(input.cpu(), *args, **kwargs).to(input.device) - elif output_dtype == torch.bool or cumsum_needs_int_fix and (output_dtype == torch.int8 or output_dtype == torch.int16): + elif output_dtype == torch.bool or (cumsum_needs_int_fix and (output_dtype == torch.int8 or output_dtype == torch.int16)): return cumsum_func(input.to(torch.int32), *args, **kwargs).to(torch.int64) return cumsum_func(input, *args, **kwargs) @@ -42,7 +42,7 @@ if has_mps: # MPS workaround for https://github.com/pytorch/pytorch/issues/79383 CondFunc('torch.Tensor.to', lambda orig_func, self, *args, **kwargs: orig_func(self.contiguous(), *args, **kwargs), - lambda _, self, *args, **kwargs: self.device.type != 'mps' and (args and isinstance(args[0], torch.device) and args[0].type == 'mps' or isinstance(kwargs.get('device'), torch.device) and kwargs['device'].type == 'mps')) + lambda _, self, *args, **kwargs: self.device.type != 'mps' and ((args and isinstance(args[0], torch.device) and args[0].type == 'mps') or (isinstance(kwargs.get('device'), torch.device) and kwargs['device'].type == 'mps'))) # MPS workaround for https://github.com/pytorch/pytorch/issues/80800 CondFunc('torch.nn.functional.layer_norm', lambda orig_func, *args, **kwargs: orig_func(*([args[0].contiguous()] + list(args[1:])), **kwargs), lambda _, *args, **kwargs: args and isinstance(args[0], torch.Tensor) and args[0].device.type == 'mps') diff --git a/modules/images_namegen.py b/modules/images_namegen.py index bc58f728a..7cad39b92 100644 --- a/modules/images_namegen.py +++ b/modules/images_namegen.py @@ -45,12 +45,12 @@ class FilenameGenerator: 'prompt_hash': lambda self: hashlib.sha256(self.prompt.encode()).hexdigest()[0:8], 'sampler': lambda self: self.p and self.p.sampler_name, - 'seed': lambda self: self.seed and str(self.seed) or '', + 'seed': lambda self: (self.seed and str(self.seed)) or '', 'steps': lambda self: self.p and getattr(self.p, 'steps', 0), 'cfg': lambda self: self.p and getattr(self.p, 'cfg_scale', 0), 'clip_skip': lambda self: self.p and getattr(self.p, 'clip_skip', 0), 'denoising': lambda self: self.p and getattr(self.p, 'denoising_strength', 0), - 'styles': lambda self: self.p and ", ".join([style for style in self.p.styles if not style == "None"]) or "None", + 'styles': lambda self: (self.p and ", ".join([style for style in self.p.styles if not style == "None"])) or "None", 'uuid': lambda self: str(uuid.uuid4()), } default_time_format = '%Y%m%d%H%M%S' diff --git a/modules/lora/network_lora.py b/modules/lora/network_lora.py index 8bf475ebc..3604e059d 100644 --- a/modules/lora/network_lora.py +++ b/modules/lora/network_lora.py @@ -31,7 +31,7 @@ class NetworkModuleLora(network.NetworkModule): if is_linear: weight = weight.reshape(weight.shape[0], -1) module = torch.nn.Linear(weight.shape[1], weight.shape[0], bias=False) - elif is_conv and key == "lora_down.weight" or key == "dyn_up": + elif is_conv and (key == "lora_down.weight" or key == "dyn_up"): if len(weight.shape) == 2: weight = weight.reshape(weight.shape[0], -1, 1, 1) if weight.shape[2] != 1 or weight.shape[3] != 1: @@ -40,7 +40,7 @@ class NetworkModuleLora(network.NetworkModule): module = torch.nn.Conv2d(weight.shape[1], weight.shape[0], (1, 1), bias=False) elif is_conv and key == "lora_mid.weight": module = torch.nn.Conv2d(weight.shape[1], weight.shape[0], self.sd_module.kernel_size, self.sd_module.stride, self.sd_module.padding, bias=False) - elif is_conv and key == "lora_up.weight" or key == "dyn_down": + elif is_conv and (key == "lora_up.weight" or key == "dyn_down"): module = torch.nn.Conv2d(weight.shape[1], weight.shape[0], (1, 1), bias=False) else: raise AssertionError(f'Lora unsupported: layer={self.network_key} type={type(self.sd_module).__name__}') diff --git a/modules/merging/merge_methods.py b/modules/merging/merge_methods.py index 3f704c20f..ce196b60c 100644 --- a/modules/merging/merge_methods.py +++ b/modules/merging/merge_methods.py @@ -4,7 +4,7 @@ from typing import Tuple import torch from torch import Tensor -__all__ = [ +__all__ = [ # noqa: RUF022 "weighted_sum", "weighted_subtraction", "tensor_sum", diff --git a/modules/processing_args.py b/modules/processing_args.py index d0afb6722..3709368ee 100644 --- a/modules/processing_args.py +++ b/modules/processing_args.py @@ -23,7 +23,7 @@ def task_specific_kwargs(p, model): if isinstance(p.init_images[0], str): p.init_images = [helpers.decode_base64_to_image(i, quiet=True) for i in p.init_images] p.init_images = [i.convert('RGB') if i.mode != 'RGB' else i for i in p.init_images] - if sd_models.get_diffusers_task(model) == sd_models.DiffusersTaskType.TEXT_2_IMAGE or len(getattr(p, 'init_images', [])) == 0 and not is_img2img_model: + if (sd_models.get_diffusers_task(model) == sd_models.DiffusersTaskType.TEXT_2_IMAGE or len(getattr(p, 'init_images', [])) == 0) and not is_img2img_model: p.ops.append('txt2img') if hasattr(p, 'width') and hasattr(p, 'height'): task_args = { diff --git a/modules/processing_helpers.py b/modules/processing_helpers.py index 5d2661cc2..304e2c211 100644 --- a/modules/processing_helpers.py +++ b/modules/processing_helpers.py @@ -159,7 +159,7 @@ def create_random_tensors(shape, seeds, subseeds=None, subseed_strength=0.0, see # enables the generation of additional tensors with noise that the sampler will use during its processing. # Using those pre-generated tensors instead of simple torch.randn allows a batch with seeds [100, 101] to # produce the same images as with two batches [100], [101]. - if p is not None and p.sampler is not None and (len(seeds) > 1 and shared.opts.enable_batch_seeds or eta_noise_seed_delta > 0): + if p is not None and p.sampler is not None and ((len(seeds) > 1 and shared.opts.enable_batch_seeds) or (eta_noise_seed_delta > 0)): sampler_noises = [[] for _ in range(p.sampler.number_of_needed_noises(p))] else: sampler_noises = None @@ -414,7 +414,7 @@ def resize_hires(p, latents): # input=latents output=pil if not latent_upscaler if latent_upscaler is not None: return torch.nn.functional.interpolate(latents, size=(p.hr_upscale_to_y // 8, p.hr_upscale_to_x // 8), mode=latent_upscaler["mode"], antialias=latent_upscaler["antialias"]) first_pass_images = processing_vae.vae_decode(latents=latents, model=shared.sd_model, full_quality=p.full_quality, output_type='pil', width=p.width, height=p.height) - if p.hr_upscale_to_x == 0 or p.hr_upscale_to_y == 0 and hasattr(p, 'init_hr'): + if p.hr_upscale_to_x == 0 or (p.hr_upscale_to_y == 0 and hasattr(p, 'init_hr')): shared.log.error('Hires: missing upscaling dimensions') return first_pass_images resized_images = [] diff --git a/modules/sd_disable_initialization.py b/modules/sd_disable_initialization.py index e9ac1be92..688af0f34 100644 --- a/modules/sd_disable_initialization.py +++ b/modules/sd_disable_initialization.py @@ -53,7 +53,7 @@ class DisableInitialization: def transformers_utils_hub_get_file_from_cache(original, url, *args, **kwargs): # this file is always 404, prevent making request - if url == 'https://huggingface.co/openai/clip-vit-large-patch14/resolve/main/added_tokens.json' or url == 'openai/clip-vit-large-patch14' and args[0] == 'added_tokens.json': + if (url == 'https://huggingface.co/openai/clip-vit-large-patch14/resolve/main/added_tokens.json' or url == 'openai/clip-vit-large-patch14') and args[0] == 'added_tokens.json': return None try: diff --git a/modules/sd_hijack_unet.py b/modules/sd_hijack_unet.py index d8d356071..66040c5aa 100644 --- a/modules/sd_hijack_unet.py +++ b/modules/sd_hijack_unet.py @@ -70,7 +70,7 @@ CondFunc('ldm.modules.diffusionmodules.openaimodel.timestep_embedding', lambda o if version.parse(torch.__version__) <= version.parse("1.13.2") or torch.cuda.is_available(): CondFunc('ldm.modules.diffusionmodules.util.GroupNorm32.forward', lambda orig_func, self, *args, **kwargs: orig_func(self.float(), *args, **kwargs), unet_needs_upcast) CondFunc('ldm.modules.attention.GEGLU.forward', lambda orig_func, self, x: orig_func(self.float(), x.float()).to(devices.dtype_unet), unet_needs_upcast) - CondFunc('open_clip.transformer.ResidualAttentionBlock.__init__', lambda orig_func, *args, **kwargs: kwargs.update({'act_layer': GELUHijack}) and False or orig_func(*args, **kwargs), lambda _, *args, **kwargs: kwargs.get('act_layer') is None or kwargs['act_layer'] == torch.nn.GELU) + CondFunc('open_clip.transformer.ResidualAttentionBlock.__init__', lambda orig_func, *args, **kwargs: (kwargs.update({'act_layer': GELUHijack}) and False) or orig_func(*args, **kwargs), lambda _, *args, **kwargs: kwargs.get('act_layer') is None or kwargs['act_layer'] == torch.nn.GELU) first_stage_cond = lambda _, self, *args, **kwargs: devices.unet_needs_upcast and self.model.diffusion_model.dtype == torch.float16 # pylint: disable=unnecessary-lambda-assignment first_stage_sub = lambda orig_func, self, x, **kwargs: orig_func(self, x.to(devices.dtype_vae), **kwargs) # pylint: disable=unnecessary-lambda-assignment diff --git a/scripts/ltxvideo.py b/scripts/ltxvideo.py index 50530563a..148fd4481 100644 --- a/scripts/ltxvideo.py +++ b/scripts/ltxvideo.py @@ -43,7 +43,7 @@ class Script(scripts.Script): # set params image = getattr(p, 'init_images', None) image = None if image is None or len(image) == 0 else image[0] - if p.width == 0 or p.height == 0 and image is not None: + if (p.width == 0 or p.height == 0) and image is not None: p.width = image.width p.height = image.height num_frames = 8 * int(num_frames // 8) + 1 diff --git a/scripts/regional_prompting.py b/scripts/regional_prompting.py index 48309704e..3d452b0c5 100644 --- a/scripts/regional_prompting.py +++ b/scripts/regional_prompting.py @@ -9,7 +9,7 @@ from modules import shared, devices, scripts, processing, sd_models, prompt_pars def hijack_register_modules(self, **kwargs): for name, module in kwargs.items(): register_dict = None - if module is None or isinstance(module, (tuple, list)) and module[0] is None: + if module is None or (isinstance(module, (tuple, list)) and module[0] is None): register_dict = {name: (None, None)} elif isinstance(module, bool): pass