2024-09-04 16:38:38 -04:00
import torch
import comfy . model_management
import comfy . utils
import folder_paths
import os
import logging
2024-09-07 03:21:02 -04:00
from enum import Enum
2025-10-09 09:11:45 +03:00
from typing_extensions import override
from comfy_api . latest import ComfyExtension , io
2026-02-15 17:28:51 -08:00
from tqdm . auto import trange
2024-09-04 16:38:38 -04:00
CLAMP_QUANTILE = 0.99
def extract_lora ( diff , rank ) :
conv2d = ( len ( diff . shape ) == 4 )
kernel_size = None if not conv2d else diff . size ( ) [ 2 : 4 ]
conv2d_3x3 = conv2d and kernel_size != ( 1 , 1 )
out_dim , in_dim = diff . size ( ) [ 0 : 2 ]
rank = min ( rank , in_dim , out_dim )
if conv2d :
if conv2d_3x3 :
diff = diff . flatten ( start_dim = 1 )
else :
diff = diff . squeeze ( )
U , S , Vh = torch . linalg . svd ( diff . float ( ) )
U = U [ : , : rank ]
S = S [ : rank ]
U = U @ torch . diag ( S )
Vh = Vh [ : rank , : ]
dist = torch . cat ( [ U . flatten ( ) , Vh . flatten ( ) ] )
hi_val = torch . quantile ( dist , CLAMP_QUANTILE )
low_val = - hi_val
U = U . clamp ( low_val , hi_val )
Vh = Vh . clamp ( low_val , hi_val )
if conv2d :
U = U . reshape ( out_dim , rank , 1 , 1 )
Vh = Vh . reshape ( rank , in_dim , kernel_size [ 0 ] , kernel_size [ 1 ] )
return ( U , Vh )
2024-09-07 03:21:02 -04:00
class LORAType ( Enum ) :
STANDARD = 0
FULL_DIFF = 1
LORA_TYPES = { " standard " : LORAType . STANDARD ,
" full_diff " : LORAType . FULL_DIFF }
def calc_lora_model ( model_diff , rank , prefix_model , prefix_lora , output_sd , lora_type , bias_diff = False ) :
2026-02-15 17:28:51 -08:00
comfy . model_management . load_models_gpu ( [ model_diff ] )
2024-09-07 02:30:12 -04:00
sd = model_diff . model_state_dict ( filter_prefix = prefix_model )
2026-02-15 17:28:51 -08:00
sd_keys = list ( sd . keys ( ) )
for index in trange ( len ( sd_keys ) , unit = " weight " ) :
k = sd_keys [ index ]
op_keys = sd_keys [ index ] . rsplit ( ' . ' , 1 )
if len ( op_keys ) < 2 or op_keys [ 1 ] not in [ " weight " , " bias " ] or ( op_keys [ 1 ] == " bias " and not bias_diff ) :
continue
op = comfy . utils . get_attr ( model_diff . model , op_keys [ 0 ] )
if hasattr ( op , " comfy_cast_weights " ) and not getattr ( op , " comfy_patched_weights " , False ) :
weight_diff = model_diff . patch_weight_to_device ( k , model_diff . load_device , return_weight = True )
else :
2024-09-07 02:30:12 -04:00
weight_diff = sd [ k ]
2026-02-15 17:28:51 -08:00
if op_keys [ 1 ] == " weight " :
2024-09-07 03:21:02 -04:00
if lora_type == LORAType . STANDARD :
if weight_diff . ndim < 2 :
if bias_diff :
output_sd [ " {} {} .diff " . format ( prefix_lora , k [ len ( prefix_model ) : - 7 ] ) ] = weight_diff . contiguous ( ) . half ( ) . cpu ( )
continue
try :
out = extract_lora ( weight_diff , rank )
output_sd [ " {} {} .lora_up.weight " . format ( prefix_lora , k [ len ( prefix_model ) : - 7 ] ) ] = out [ 0 ] . contiguous ( ) . half ( ) . cpu ( )
output_sd [ " {} {} .lora_down.weight " . format ( prefix_lora , k [ len ( prefix_model ) : - 7 ] ) ] = out [ 1 ] . contiguous ( ) . half ( ) . cpu ( )
except :
logging . warning ( " Could not generate lora weights for key {} , is the weight difference a zero? " . format ( k ) )
elif lora_type == LORAType . FULL_DIFF :
output_sd [ " {} {} .diff " . format ( prefix_lora , k [ len ( prefix_model ) : - 7 ] ) ] = weight_diff . contiguous ( ) . half ( ) . cpu ( )
2026-02-15 17:28:51 -08:00
elif bias_diff and op_keys [ 1 ] == " bias " :
output_sd [ " {} {} .diff_b " . format ( prefix_lora , k [ len ( prefix_model ) : - 5 ] ) ] = weight_diff . contiguous ( ) . half ( ) . cpu ( )
2024-09-07 02:30:12 -04:00
return output_sd
2025-10-09 09:11:45 +03:00
class LoraSave ( io . ComfyNode ) :
@classmethod
def define_schema ( cls ) :
return io . Schema (
node_id = " LoraSave " ,
add search aliases to all nodes (#12035)
* feat: Add search_aliases field to node schema
Adds `search_aliases` field to improve node discoverability. Users can define alternative search terms for nodes (e.g., "text concat" → StringConcatenate).
Changes:
- Add `search_aliases: list[str]` to V3 Schema
- Add `SEARCH_ALIASES` support for V1 nodes
- Include field in `/object_info` response
- Add aliases to high-priority core nodes
V1 usage:
```python
class MyNode:
SEARCH_ALIASES = ["alt name", "synonym"]
```
V3 usage:
```python
io.Schema(
node_id="MyNode",
search_aliases=["alt name", "synonym"],
...
)
```
## Related PRs
- Frontend: Comfy-Org/ComfyUI_frontend#XXXX (draft - merge after this)
- Docs: Comfy-Org/docs#XXXX (draft - merge after stable)
* Propagate search_aliases through V3 Schema.get_v1_info to NodeInfoV1
* feat: add SEARCH_ALIASES for core nodes (#12016)
Add search aliases to 22 core nodes in nodes.py to improve node discoverability:
- Checkpoint/model loaders: CheckpointLoader, DiffusersLoader
- Conditioning nodes: ConditioningAverage, ConditioningSetArea, ConditioningSetMask, ConditioningZeroOut
- Style nodes: StyleModelApply
- Image nodes: LoadImageMask, LoadImageOutput, ImageBatch, ImageInvert, ImagePadForOutpaint
- Latent nodes: LoadLatent, SaveLatent, LatentBlend, LatentComposite, LatentCrop, LatentFlip, LatentFromBatch, LatentUpscale, LatentUpscaleBy, RepeatLatentBatch
* feat: add SEARCH_ALIASES for image, mask, and string nodes (#12017)
Add search aliases to nodes in comfy_extras for better discoverability:
- nodes_mask.py: mask manipulation nodes
- nodes_images.py: image processing nodes
- nodes_post_processing.py: post-processing effect nodes
- nodes_string.py: string manipulation nodes
- nodes_compositing.py: compositing nodes
- nodes_morphology.py: morphological operation nodes
- nodes_latent.py: latent space nodes
Uses search_aliases parameter in io.Schema() for v3 nodes.
* feat: add SEARCH_ALIASES for audio and video nodes (#12018)
Add search aliases to audio and video nodes for better discoverability:
- nodes_audio.py: audio loading, saving, and processing nodes
- nodes_video.py: video loading and processing nodes
- nodes_wan.py: WAN model nodes
Uses search_aliases parameter in io.Schema() for v3 nodes.
* feat: add SEARCH_ALIASES for model and misc nodes (#12019)
Add search aliases to model-related and miscellaneous nodes:
- Model nodes: nodes_model_merging.py, nodes_model_advanced.py, nodes_lora_extract.py
- Sampler nodes: nodes_custom_sampler.py, nodes_align_your_steps.py
- Control nodes: nodes_controlnet.py, nodes_attention_multiply.py, nodes_hooks.py
- Training nodes: nodes_train.py, nodes_dataset.py
- Utility nodes: nodes_logic.py, nodes_canny.py, nodes_differential_diffusion.py
- Architecture-specific: nodes_sd3.py, nodes_pixart.py, nodes_lumina2.py, nodes_kandinsky5.py, nodes_hidream.py, nodes_fresca.py, nodes_hunyuan3d.py
- Media nodes: nodes_load_3d.py, nodes_webcam.py, nodes_preview_any.py, nodes_wanmove.py
Uses search_aliases parameter in io.Schema() for v3 nodes, SEARCH_ALIASES class attribute for legacy nodes.
2026-01-22 18:36:58 -08:00
search_aliases = [ " export lora " ] ,
2025-10-09 09:11:45 +03:00
display_name = " Extract and Save Lora " ,
category = " _for_testing " ,
2026-02-16 14:02:17 -08:00
description = " Extracts LoRA weights from a model or text encoder diff using SVD decomposition and saves them as a safetensors file, supporting standard and full diff modes. " ,
short_description = " Extract and save LoRA from model diff. " ,
2025-10-09 09:11:45 +03:00
inputs = [
io . String . Input ( " filename_prefix " , default = " loras/ComfyUI_extracted_lora " ) ,
io . Int . Input ( " rank " , default = 8 , min = 1 , max = 4096 , step = 1 ) ,
io . Combo . Input ( " lora_type " , options = tuple ( LORA_TYPES . keys ( ) ) ) ,
io . Boolean . Input ( " bias_diff " , default = True ) ,
io . Model . Input (
" model_diff " ,
tooltip = " The ModelSubtract output to be converted to a lora. " ,
optional = True ,
) ,
io . Clip . Input (
" text_encoder_diff " ,
tooltip = " The CLIPSubtract output to be converted to a lora. " ,
optional = True ,
) ,
] ,
is_experimental = True ,
is_output_node = True ,
)
2024-09-04 16:38:38 -04:00
@classmethod
2025-10-09 09:11:45 +03:00
def execute ( cls , filename_prefix , rank , lora_type , bias_diff , model_diff = None , text_encoder_diff = None ) - > io . NodeOutput :
2024-09-07 02:30:12 -04:00
if model_diff is None and text_encoder_diff is None :
2025-10-09 09:11:45 +03:00
return io . NodeOutput ( )
2024-09-04 16:38:38 -04:00
2024-09-07 03:21:02 -04:00
lora_type = LORA_TYPES . get ( lora_type )
2025-10-09 09:11:45 +03:00
full_output_folder , filename , counter , subfolder , filename_prefix = folder_paths . get_save_image_path ( filename_prefix , folder_paths . get_output_directory ( ) )
2024-09-04 16:38:38 -04:00
output_sd = { }
2024-09-07 02:30:12 -04:00
if model_diff is not None :
2024-09-07 03:21:02 -04:00
output_sd = calc_lora_model ( model_diff , rank , " diffusion_model. " , " diffusion_model. " , output_sd , lora_type , bias_diff = bias_diff )
2024-09-07 02:30:12 -04:00
if text_encoder_diff is not None :
2024-09-07 03:21:02 -04:00
output_sd = calc_lora_model ( text_encoder_diff . patcher , rank , " " , " text_encoders. " , output_sd , lora_type , bias_diff = bias_diff )
2024-09-04 16:38:38 -04:00
output_checkpoint = f " { filename } _ { counter : 05 } _.safetensors "
output_checkpoint = os . path . join ( full_output_folder , output_checkpoint )
comfy . utils . save_torch_file ( output_sd , output_checkpoint , metadata = None )
2025-10-09 09:11:45 +03:00
return io . NodeOutput ( )
class LoraSaveExtension ( ComfyExtension ) :
@override
async def get_node_list ( self ) - > list [ type [ io . ComfyNode ] ] :
return [
LoraSave ,
]
2024-09-04 16:38:38 -04:00
2024-10-18 06:01:09 -04:00
2025-10-09 09:11:45 +03:00
async def comfy_entrypoint ( ) - > LoraSaveExtension :
return LoraSaveExtension ( )