├── chatglm3
├── __init__.py
├── configuration_chatglm.py
├── tokenization_chatglm.py
└── quantization.py
├── examples
├── workflow_ipa.png
├── workflow_legacy.png
├── workflow_controlnet.png
├── workflow_inpainting.png
├── workflow_ipa_faceid.png
├── workflow_ipa_legacy.png
├── workflow_same_seed_test.png
└── workflow_official_controlnet.png
├── configs
├── tokenizer
│ ├── vocab.txt
│ ├── tokenizer.model
│ └── tokenizer_config.json
└── text_encoder_config.json
├── clip_vit_336
└── config.json
├── pyproject.toml
├── .github
└── workflows
│ └── publish.yml
├── hook_comfyui_kolors_v1.py
├── .gitignore
├── mz_kolors_legacy.py
├── README.md
├── ComfyUI_IPAdapter_plus
├── CrossAttentionPatch.py
├── image_proj_models.py
└── utils.py
├── __init__.py
├── mz_kolors_core.py
├── hook_comfyui_kolors_v2.py
├── LICENSE
└── mz_kolors_utils.py
/chatglm3/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/examples/workflow_ipa.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MinusZoneAI/ComfyUI-Kolors-MZ/HEAD/examples/workflow_ipa.png
--------------------------------------------------------------------------------
/configs/tokenizer/vocab.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MinusZoneAI/ComfyUI-Kolors-MZ/HEAD/configs/tokenizer/vocab.txt
--------------------------------------------------------------------------------
/examples/workflow_legacy.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MinusZoneAI/ComfyUI-Kolors-MZ/HEAD/examples/workflow_legacy.png
--------------------------------------------------------------------------------
/configs/tokenizer/tokenizer.model:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MinusZoneAI/ComfyUI-Kolors-MZ/HEAD/configs/tokenizer/tokenizer.model
--------------------------------------------------------------------------------
/examples/workflow_controlnet.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MinusZoneAI/ComfyUI-Kolors-MZ/HEAD/examples/workflow_controlnet.png
--------------------------------------------------------------------------------
/examples/workflow_inpainting.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MinusZoneAI/ComfyUI-Kolors-MZ/HEAD/examples/workflow_inpainting.png
--------------------------------------------------------------------------------
/examples/workflow_ipa_faceid.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MinusZoneAI/ComfyUI-Kolors-MZ/HEAD/examples/workflow_ipa_faceid.png
--------------------------------------------------------------------------------
/examples/workflow_ipa_legacy.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MinusZoneAI/ComfyUI-Kolors-MZ/HEAD/examples/workflow_ipa_legacy.png
--------------------------------------------------------------------------------
/examples/workflow_same_seed_test.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MinusZoneAI/ComfyUI-Kolors-MZ/HEAD/examples/workflow_same_seed_test.png
--------------------------------------------------------------------------------
/examples/workflow_official_controlnet.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MinusZoneAI/ComfyUI-Kolors-MZ/HEAD/examples/workflow_official_controlnet.png
--------------------------------------------------------------------------------
/configs/tokenizer/tokenizer_config.json:
--------------------------------------------------------------------------------
1 | {
2 | "name_or_path": "THUDM/chatglm3-6b-base",
3 | "remove_space": false,
4 | "do_lower_case": false,
5 | "tokenizer_class": "ChatGLMTokenizer",
6 | "auto_map": {
7 | "AutoTokenizer": [
8 | "tokenization_chatglm.ChatGLMTokenizer",
9 | null
10 | ]
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/clip_vit_336/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "attention_dropout": 0.0,
3 | "dropout": 0.0,
4 | "hidden_act": "quick_gelu",
5 | "hidden_size": 1024,
6 | "image_size": 336,
7 | "initializer_factor": 1.0,
8 | "initializer_range": 0.02,
9 | "intermediate_size": 4096,
10 | "layer_norm_eps": 1e-05,
11 | "model_type": "clip_vision_model",
12 | "num_attention_heads": 16,
13 | "num_channels": 3,
14 | "num_hidden_layers": 24,
15 | "patch_size": 14,
16 | "projection_dim": 768,
17 | "torch_dtype": "float32"
18 | }
19 |
20 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [project]
2 | name = "comfyui-kolors-mz"
3 | description = "Implementation of Kolors on ComfyUI\nReference from [a/https://github.com/kijai/ComfyUI-KwaiKolorsWrapper](https://github.com/kijai/ComfyUI-KwaiKolorsWrapper)\nUsing ComfyUI Native Sampling"
4 | version = "2.0.0"
5 | license = { file = "GPL-3.0 license" }
6 |
7 | [project.urls]
8 | Repository = "https://github.com/MinusZoneAI/ComfyUI-Kolors-MZ"
9 | # Used by Comfy Registry https://comfyregistry.org
10 |
11 | [tool.comfy]
12 | PublisherId = "wailovet"
13 | DisplayName = "ComfyUI-Kolors-MZ"
14 | Icon = ""
15 |
--------------------------------------------------------------------------------
/.github/workflows/publish.yml:
--------------------------------------------------------------------------------
1 | name: Publish to Comfy registry
2 | on:
3 | workflow_dispatch:
4 | push:
5 | branches:
6 | - main
7 | - master
8 | paths:
9 | - "pyproject.toml"
10 |
11 | permissions:
12 | issues: write
13 |
14 | jobs:
15 | publish-node:
16 | name: Publish Custom Node to registry
17 | runs-on: ubuntu-latest
18 | if: ${{ github.repository_owner == 'MinusZoneAI' }}
19 | steps:
20 | - name: Check out code
21 | uses: actions/checkout@v4
22 | - name: Publish Custom Node
23 | uses: Comfy-Org/publish-node-action@v1
24 | with:
25 | ## Add your own personal access token to your Github Repository secrets and reference it here.
26 | personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
27 |
--------------------------------------------------------------------------------
/configs/text_encoder_config.json:
--------------------------------------------------------------------------------
1 | {
2 | "_name_or_path": "THUDM/chatglm3-6b-base",
3 | "model_type": "chatglm",
4 | "architectures": [
5 | "ChatGLMModel"
6 | ],
7 | "auto_map": {
8 | "AutoConfig": "configuration_chatglm.ChatGLMConfig",
9 | "AutoModel": "modeling_chatglm.ChatGLMForConditionalGeneration",
10 | "AutoModelForCausalLM": "modeling_chatglm.ChatGLMForConditionalGeneration",
11 | "AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGeneration",
12 | "AutoModelForSequenceClassification": "modeling_chatglm.ChatGLMForSequenceClassification"
13 | },
14 | "add_bias_linear": false,
15 | "add_qkv_bias": true,
16 | "apply_query_key_layer_scaling": true,
17 | "apply_residual_connection_post_layernorm": false,
18 | "attention_dropout": 0.0,
19 | "attention_softmax_in_fp32": true,
20 | "bias_dropout_fusion": true,
21 | "ffn_hidden_size": 13696,
22 | "fp32_residual_connection": false,
23 | "hidden_dropout": 0.0,
24 | "hidden_size": 4096,
25 | "kv_channels": 128,
26 | "layernorm_epsilon": 1e-05,
27 | "multi_query_attention": true,
28 | "multi_query_group_num": 2,
29 | "num_attention_heads": 32,
30 | "num_layers": 28,
31 | "original_rope": true,
32 | "padded_vocab_size": 65024,
33 | "post_layer_norm": true,
34 | "rmsnorm": true,
35 | "seq_length": 32768,
36 | "use_cache": true,
37 | "torch_dtype": "float16",
38 | "transformers_version": "4.30.2",
39 | "tie_word_embeddings": false,
40 | "eos_token_id": 2,
41 | "pad_token_id": 0
42 | }
--------------------------------------------------------------------------------
/chatglm3/configuration_chatglm.py:
--------------------------------------------------------------------------------
1 | from transformers import PretrainedConfig
2 |
3 |
4 | class ChatGLMConfig(PretrainedConfig):
5 | model_type = "chatglm"
6 | def __init__(
7 | self,
8 | num_layers=28,
9 | padded_vocab_size=65024,
10 | hidden_size=4096,
11 | ffn_hidden_size=13696,
12 | kv_channels=128,
13 | num_attention_heads=32,
14 | seq_length=2048,
15 | hidden_dropout=0.0,
16 | classifier_dropout=None,
17 | attention_dropout=0.0,
18 | layernorm_epsilon=1e-5,
19 | rmsnorm=True,
20 | apply_residual_connection_post_layernorm=False,
21 | post_layer_norm=True,
22 | add_bias_linear=False,
23 | add_qkv_bias=False,
24 | bias_dropout_fusion=True,
25 | multi_query_attention=False,
26 | multi_query_group_num=1,
27 | apply_query_key_layer_scaling=True,
28 | attention_softmax_in_fp32=True,
29 | fp32_residual_connection=False,
30 | quantization_bit=0,
31 | pre_seq_len=None,
32 | prefix_projection=False,
33 | **kwargs
34 | ):
35 | self.num_layers = num_layers
36 | self.vocab_size = padded_vocab_size
37 | self.padded_vocab_size = padded_vocab_size
38 | self.hidden_size = hidden_size
39 | self.ffn_hidden_size = ffn_hidden_size
40 | self.kv_channels = kv_channels
41 | self.num_attention_heads = num_attention_heads
42 | self.seq_length = seq_length
43 | self.hidden_dropout = hidden_dropout
44 | self.classifier_dropout = classifier_dropout
45 | self.attention_dropout = attention_dropout
46 | self.layernorm_epsilon = layernorm_epsilon
47 | self.rmsnorm = rmsnorm
48 | self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
49 | self.post_layer_norm = post_layer_norm
50 | self.add_bias_linear = add_bias_linear
51 | self.add_qkv_bias = add_qkv_bias
52 | self.bias_dropout_fusion = bias_dropout_fusion
53 | self.multi_query_attention = multi_query_attention
54 | self.multi_query_group_num = multi_query_group_num
55 | self.apply_query_key_layer_scaling = apply_query_key_layer_scaling
56 | self.attention_softmax_in_fp32 = attention_softmax_in_fp32
57 | self.fp32_residual_connection = fp32_residual_connection
58 | self.quantization_bit = quantization_bit
59 | self.pre_seq_len = pre_seq_len
60 | self.prefix_projection = prefix_projection
61 | super().__init__(**kwargs)
62 |
--------------------------------------------------------------------------------
/hook_comfyui_kolors_v1.py:
--------------------------------------------------------------------------------
1 | from comfy.model_detection import *
2 | import comfy.model_detection as model_detection
3 | import comfy.supported_models
4 |
5 |
6 | class Kolors(comfy.supported_models.SDXL):
7 | unet_config = {
8 | "model_channels": 320,
9 | "use_linear_in_transformer": True,
10 | "transformer_depth": [0, 0, 2, 2, 10, 10],
11 | "context_dim": 2048,
12 | "adm_in_channels": 5632,
13 | "use_temporal_attention": False,
14 | }
15 |
16 |
17 | def kolors_unet_config_from_diffusers_unet(state_dict, dtype=None):
18 | match = {}
19 | transformer_depth = []
20 |
21 | attn_res = 1
22 | down_blocks = count_blocks(state_dict, "down_blocks.{}")
23 | for i in range(down_blocks):
24 | attn_blocks = count_blocks(
25 | state_dict, "down_blocks.{}.attentions.".format(i) + '{}')
26 | res_blocks = count_blocks(
27 | state_dict, "down_blocks.{}.resnets.".format(i) + '{}')
28 | for ab in range(attn_blocks):
29 | transformer_count = count_blocks(
30 | state_dict, "down_blocks.{}.attentions.{}.transformer_blocks.".format(i, ab) + '{}')
31 | transformer_depth.append(transformer_count)
32 | if transformer_count > 0:
33 | match["context_dim"] = state_dict["down_blocks.{}.attentions.{}.transformer_blocks.0.attn2.to_k.weight".format(
34 | i, ab)].shape[1]
35 |
36 | attn_res *= 2
37 | if attn_blocks == 0:
38 | for i in range(res_blocks):
39 | transformer_depth.append(0)
40 |
41 | match["transformer_depth"] = transformer_depth
42 |
43 | match["model_channels"] = state_dict["conv_in.weight"].shape[0]
44 | match["in_channels"] = state_dict["conv_in.weight"].shape[1]
45 | match["adm_in_channels"] = None
46 | if "class_embedding.linear_1.weight" in state_dict:
47 | match["adm_in_channels"] = state_dict["class_embedding.linear_1.weight"].shape[1]
48 | elif "add_embedding.linear_1.weight" in state_dict:
49 | match["adm_in_channels"] = state_dict["add_embedding.linear_1.weight"].shape[1]
50 |
51 | Kolors = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
52 | 'num_classes': 'sequential', 'adm_in_channels': 5632, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
53 | 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 2, 2, 10, 10], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 10,
54 | 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 2, 2, 2, 10, 10, 10],
55 | 'use_temporal_attention': False, 'use_temporal_resblock': False}
56 |
57 | supported_models = [Kolors]
58 |
59 | for unet_config in supported_models:
60 | matches = True
61 | for k in match:
62 | if match[k] != unet_config[k]:
63 | print("key {} does not match".format(
64 | k), match[k], "||", unet_config[k])
65 | matches = False
66 | break
67 | if matches:
68 | return convert_config(unet_config)
69 | return None
70 |
71 |
72 | class apply_kolors:
73 | def __enter__(self):
74 | import comfy.supported_models
75 | self.old_supported_models = comfy.supported_models.models
76 | comfy.supported_models.models = [Kolors]
77 |
78 | self.old_unet_config_from_diffusers_unet = model_detection.unet_config_from_diffusers_unet
79 | model_detection.unet_config_from_diffusers_unet = kolors_unet_config_from_diffusers_unet
80 |
81 | def __exit__(self, type, value, traceback):
82 | model_detection.unet_config_from_diffusers_unet = self.old_unet_config_from_diffusers_unet
83 |
84 | import comfy.supported_models
85 | comfy.supported_models.models = self.old_supported_models
86 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # poetry
98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99 | # This is especially recommended for binary packages to ensure reproducibility, and is more
100 | # commonly ignored for libraries.
101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102 | #poetry.lock
103 |
104 | # pdm
105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106 | #pdm.lock
107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108 | # in version control.
109 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110 | .pdm.toml
111 | .pdm-python
112 | .pdm-build/
113 |
114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115 | __pypackages__/
116 |
117 | # Celery stuff
118 | celerybeat-schedule
119 | celerybeat.pid
120 |
121 | # SageMath parsed files
122 | *.sage.py
123 |
124 | # Environments
125 | .env
126 | .venv
127 | env/
128 | venv/
129 | ENV/
130 | env.bak/
131 | venv.bak/
132 |
133 | # Spyder project settings
134 | .spyderproject
135 | .spyproject
136 |
137 | # Rope project settings
138 | .ropeproject
139 |
140 | # mkdocs documentation
141 | /site
142 |
143 | # mypy
144 | .mypy_cache/
145 | .dmypy.json
146 | dmypy.json
147 |
148 | # Pyre type checker
149 | .pyre/
150 |
151 | # pytype static type analyzer
152 | .pytype/
153 |
154 | # Cython debug symbols
155 | cython_debug/
156 |
157 | # PyCharm
158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160 | # and can be added to the global gitignore or merged into this file. For a more nuclear
161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162 | #.idea/
163 | exclude.txt
164 | copytoww.bat
165 |
--------------------------------------------------------------------------------
/mz_kolors_legacy.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | import gc
4 | import json
5 | import os
6 | import random
7 | import re
8 |
9 | import torch
10 | import folder_paths
11 | import comfy.model_management as mm
12 | from . import mz_kolors_core
13 |
14 |
15 | def MZ_ChatGLM3TextEncode_call(args):
16 |
17 | text = args.get("text")
18 | chatglm3_model = args.get("chatglm3_model")
19 |
20 | prompt_embeds, pooled_output = mz_kolors_core.chatglm3_text_encode(
21 | chatglm3_model,
22 | text,
23 | )
24 |
25 | from torch import nn
26 | hid_proj: nn.Linear = args.get("hid_proj")
27 |
28 | if hid_proj.weight.dtype != prompt_embeds.dtype:
29 | with torch.cuda.amp.autocast(dtype=hid_proj.weight.dtype):
30 | prompt_embeds = hid_proj(prompt_embeds)
31 | else:
32 | prompt_embeds = hid_proj(prompt_embeds)
33 |
34 | return ([[
35 | prompt_embeds,
36 | {"pooled_output": pooled_output},
37 | ]], )
38 |
39 |
40 | def load_unet_state_dict(sd): # load unet in diffusers or regular format
41 | from comfy import model_management, model_detection
42 | import comfy.utils
43 |
44 | # Allow loading unets from checkpoint files
45 | checkpoint = False
46 | diffusion_model_prefix = model_detection.unet_prefix_from_state_dict(sd)
47 | temp_sd = comfy.utils.state_dict_prefix_replace(
48 | sd, {diffusion_model_prefix: ""}, filter_keys=True)
49 | if len(temp_sd) > 0:
50 | sd = temp_sd
51 | checkpoint = True
52 |
53 | parameters = comfy.utils.calculate_parameters(sd)
54 | unet_dtype = model_management.unet_dtype(model_params=parameters)
55 | load_device = model_management.get_torch_device()
56 |
57 | from torch import nn
58 | hid_proj: nn.Linear = None
59 | if True:
60 | model_config = model_detection.model_config_from_diffusers_unet(sd)
61 | if model_config is None:
62 | return None
63 |
64 | diffusers_keys = comfy.utils.unet_to_diffusers(
65 | model_config.unet_config)
66 |
67 | new_sd = {}
68 | for k in diffusers_keys:
69 | if k in sd:
70 | new_sd[diffusers_keys[k]] = sd.pop(k)
71 | else:
72 | print("{} {}".format(diffusers_keys[k], k))
73 |
74 | encoder_hid_proj_weight = sd.pop("encoder_hid_proj.weight")
75 | encoder_hid_proj_bias = sd.pop("encoder_hid_proj.bias")
76 | hid_proj = nn.Linear(
77 | encoder_hid_proj_weight.shape[1], encoder_hid_proj_weight.shape[0])
78 | hid_proj.weight.data = encoder_hid_proj_weight
79 | hid_proj.bias.data = encoder_hid_proj_bias
80 | hid_proj = hid_proj.to(load_device)
81 |
82 | offload_device = model_management.unet_offload_device()
83 | unet_dtype = model_management.unet_dtype(
84 | model_params=parameters, supported_dtypes=model_config.supported_inference_dtypes)
85 | manual_cast_dtype = model_management.unet_manual_cast(
86 | unet_dtype, load_device, model_config.supported_inference_dtypes)
87 | model_config.set_inference_dtype(unet_dtype, manual_cast_dtype)
88 | model = model_config.get_model(new_sd, "")
89 | model = model.to(offload_device)
90 | model.load_model_weights(new_sd, "")
91 | left_over = sd.keys()
92 | if len(left_over) > 0:
93 | print("left over keys in unet: {}".format(left_over))
94 | return comfy.model_patcher.ModelPatcher(model, load_device=load_device, offload_device=offload_device), hid_proj
95 |
96 |
97 | def MZ_KolorsUNETLoader_call(kwargs):
98 |
99 | from . import hook_comfyui_kolors_v1
100 | with hook_comfyui_kolors_v1.apply_kolors():
101 | unet_name = kwargs.get("unet_name")
102 | unet_path = folder_paths.get_full_path("unet", unet_name)
103 | import comfy.utils
104 | sd = comfy.utils.load_torch_file(unet_path)
105 | model, hid_proj = load_unet_state_dict(sd)
106 | if model is None:
107 | raise RuntimeError(
108 | "ERROR: Could not detect model type of: {}".format(unet_path))
109 | return (model, hid_proj)
110 |
111 |
112 | def MZ_FakeCond_call(kwargs):
113 | import torch
114 | cond = torch.zeros(2, 256, 4096)
115 | pool = torch.zeros(2, 4096)
116 |
117 | dtype = kwargs.get("dtype")
118 | if dtype == "fp16":
119 | print("fp16")
120 | cond = cond.half()
121 | pool = pool.half()
122 | elif dtype == "bf16":
123 | print("bf16")
124 | cond = cond.bfloat16()
125 | pool = pool.bfloat16()
126 | else:
127 | print("fp32")
128 | cond = cond.float()
129 | pool = pool.float()
130 |
131 | return ([[
132 | cond,
133 | {"pooled_output": pool},
134 | ]],)
135 |
136 |
137 | NODE_CLASS_MAPPINGS = {
138 | }
139 |
140 |
141 | NODE_DISPLAY_NAME_MAPPINGS = {
142 | }
143 |
144 | AUTHOR_NAME = "MinusZone"
145 | CATEGORY_NAME = f"{AUTHOR_NAME} - Kolors"
146 |
147 |
148 | class MZ_ChatGLM3TextEncode:
149 | @classmethod
150 | def INPUT_TYPES(s):
151 | return {
152 | "required": {
153 | "chatglm3_model": ("CHATGLM3MODEL", ),
154 | "text": ("STRING", {"multiline": True, "dynamicPrompts": True}),
155 | "hid_proj": ("TorchLinear", ),
156 | }
157 | }
158 |
159 | RETURN_TYPES = ("CONDITIONING",)
160 |
161 | FUNCTION = "encode"
162 | CATEGORY = CATEGORY_NAME + "/Legacy"
163 |
164 | def encode(self, **kwargs):
165 | return MZ_ChatGLM3TextEncode_call(kwargs)
166 |
167 |
168 | NODE_CLASS_MAPPINGS["MZ_ChatGLM3"] = MZ_ChatGLM3TextEncode
169 | NODE_DISPLAY_NAME_MAPPINGS[
170 | "MZ_ChatGLM3"] = f"{AUTHOR_NAME} - ChatGLM3TextEncode"
171 |
172 |
173 | class MZ_KolorsUNETLoader():
174 | @classmethod
175 | def INPUT_TYPES(s):
176 | return {"required": {
177 | "unet_name": (folder_paths.get_filename_list("unet"), ),
178 | }}
179 |
180 | RETURN_TYPES = ("MODEL", "TorchLinear")
181 |
182 | RETURN_NAMES = ("model", "hid_proj")
183 |
184 | FUNCTION = "load_unet"
185 |
186 | CATEGORY = CATEGORY_NAME + "/Legacy"
187 |
188 | def load_unet(self, **kwargs):
189 | return MZ_KolorsUNETLoader_call(kwargs)
190 |
191 |
192 | NODE_CLASS_MAPPINGS["MZ_KolorsUNETLoader"] = MZ_KolorsUNETLoader
193 | NODE_DISPLAY_NAME_MAPPINGS[
194 | "MZ_KolorsUNETLoader"] = f"{AUTHOR_NAME} - Kolors UNET Loader"
195 |
196 |
197 | class MZ_FakeCond:
198 | @classmethod
199 | def INPUT_TYPES(s):
200 | return {
201 | "required": {
202 | "seed": ("INT", {"default": 0}),
203 | "dtype": ([
204 | "fp32",
205 | "fp16",
206 | "bf16",
207 | ],),
208 | }
209 | }
210 |
211 | RETURN_TYPES = ("CONDITIONING", )
212 | RETURN_NAMES = ("prompt", )
213 | FUNCTION = "encode"
214 | CATEGORY = CATEGORY_NAME
215 |
216 | def encode(self, **kwargs):
217 | return MZ_FakeCond_call(kwargs)
218 |
219 |
220 | try:
221 | if os.environ.get("MZ_DEV", None) is not None:
222 | NODE_CLASS_MAPPINGS["MZ_FakeCond"] = MZ_FakeCond
223 | NODE_DISPLAY_NAME_MAPPINGS[
224 | "MZ_FakeCond"] = f"{AUTHOR_NAME} - FakeCond"
225 | except ImportError:
226 | pass
227 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | ## Recent changes
4 | * [2024-08-02] 支持faceid,新增一些相关节点,工作流见examples/workflow_ipa_faceid.png
5 | * [2024-07-27] 新增MZ_KolorsControlNetLoader节点,用于加载可图ControlNet官方模型
6 | * [2024-07-26] 新增MZ_ApplySDXLSamplingSettings节点,用于V2版本重新回到SDXL的scheduler配置.
7 | 
8 |
9 | * [2024-07-25] 修正sampling_settings,参数来自 [scheduler_config.json](https://huggingface.co/Kwai-Kolors/Kolors/blob/main/scheduler/scheduler_config.json),仅V2生效
10 | * [2024-07-21] 感谢来自yiwangsimple对Mac修复和测试的分支 https://github.com/yiwangsimple/ComfyUI-Kolors-MZ
11 | * [2024-07-21] 新增MZ_ChatGLM3TextEncodeAdvanceV2节点
12 | * [2024-07-18] IPA相关节点已在ComfyUI_IPAdapter_plus中支持
13 | * [2024-07-17] 新增支持IPAdapter_plus的加载器和高级应用节点 MZ_KolorsCLIPVisionLoader,MZ_IPAdapterModelLoaderKolors,MZ_IPAdapterAdvancedKolors
14 | * [2024-07-14] 删除自动兼容ControlNet, 新增MZ_KolorsControlNetPatch节点
15 | 
16 |
17 | ## ComfyUI上Kolors的实现
18 |
19 | 参考自 https://github.com/kijai/ComfyUI-KwaiKolorsWrapper
20 |
21 | 使用ComfyUI原生采样
22 |
23 | 工作流在examples/workflow.png中获取
24 |
25 | ### UNET模型下载
26 | unet模型放置在 models/unet/ 文件夹下
27 |
28 | 模型主页: https://huggingface.co/Kwai-Kolors/Kolors
29 |
30 | 下载地址: https://huggingface.co/Kwai-Kolors/Kolors/resolve/main/unet/diffusion_pytorch_model.fp16.safetensors
31 |
32 |
33 | ### ChatGLM3模型下载
34 | chatglm3放置在 models/LLM/ 文件夹下
35 |
36 | 模型主页: https://huggingface.co/Kijai/ChatGLM3-safetensors
37 |
38 | 下载地址: https://huggingface.co/Kijai/ChatGLM3-safetensors/resolve/main/chatglm3-fp16.safetensors
39 |
40 |
41 | ## IPAdapter实现推荐使用 [cubiq/ComfyUI_IPAdapter_plus](https://github.com/cubiq/ComfyUI_IPAdapter_plus)
42 | faceid相关节点已经在其中支持,IPAdapter实现需要更新ComfyUI_IPAdapter_plus到最新版本
43 | ### IPAdapter工作流
44 | https://github.com/cubiq/ComfyUI_IPAdapter_plus/blob/main/examples/ipadapter_kolors.json
45 |
46 | ### IPAdapter_FaceIDv2工作流
47 | https://github.com/cubiq/ComfyUI_IPAdapter_plus/blob/main/examples/IPAdapter_FaceIDv2_Kolors.json
48 |
49 |
50 | ### 官方IP-Adapter-Plus模型下载地址
51 | 模型主页: https://huggingface.co/Kwai-Kolors/Kolors-IP-Adapter-Plus
52 |
53 | https://huggingface.co/Kwai-Kolors/Kolors-IP-Adapter-Plus/resolve/main/ip_adapter_plus_general.bin 下载至 models/ipadapter/
54 |
55 | https://huggingface.co/Kwai-Kolors/Kolors-IP-Adapter-Plus/resolve/main/image_encoder/pytorch_model.bin 下载至 models/clip_vision/
56 |
57 | ### 官方Kolors-IP-Adapter-FaceID-Plus模型下载地址
58 | 模型主页: https://huggingface.co/Kwai-Kolors/Kolors-IP-Adapter-FaceID-Plus
59 |
60 | https://huggingface.co/Kwai-Kolors/Kolors-IP-Adapter-FaceID-Plus/resolve/main/ipa-faceid-plus.bin 下载至 models/ipadapter/
61 |
62 | https://huggingface.co/Kwai-Kolors/Kolors-IP-Adapter-FaceID-Plus/resolve/main/clip-vit-large-patch14-336/pytorch_model.bin 下载至 models/clip_vision/
63 |
64 | https://huggingface.co/MonsterMMORPG/tools/resolve/main/antelopev2.zip 下载并解压至 models/insightface/models/antelopev2/*.onnx
65 |
66 | ### 官方ControlNet模型下载地址
67 | 模型主页(Depth): https://huggingface.co/Kwai-Kolors/Kolors-ControlNet-Depth
68 |
69 | 模型主页(Canny): https://huggingface.co/Kwai-Kolors/Kolors-ControlNet-Canny
70 |
71 | 模型主页(Pose): https://huggingface.co/Kwai-Kolors/Kolors-ControlNet-Pose
72 |
73 | ### Kolors-Inpainting模型下载地址
74 | 模型主页: https://huggingface.co/Kwai-Kolors/Kolors-Inpainting
75 |
76 | https://huggingface.co/Kwai-Kolors/Kolors-Inpainting/resolve/main/unet/diffusion_pytorch_model.safetensors 下载至 models/unet/
77 |
78 |
79 |
80 | ## Implementation of Kolors on ComfyUI
81 |
82 | Reference from https://github.com/kijai/ComfyUI-KwaiKolorsWrapper
83 |
84 | Using ComfyUI Native Sampling
85 |
86 | The workflow is obtained in examples/workflow.png
87 |
88 |
89 | ### UNET model download
90 | The unet model is placed in the models/unet/ folder
91 |
92 | Model homepage: https://huggingface.co/Kwai-Kolors/Kolors
93 |
94 | Download link:
95 | https://huggingface.co/Kwai-Kolors/Kolors/resolve/main/unet/diffusion_pytorch_model.fp16.safetensors
96 |
97 |
98 | ### ChatGLM3 model download
99 | The chatglm3 is placed in the models/LLM/ folder
100 |
101 | Model homepage: https://huggingface.co/Kijai/ChatGLM3-safetensors
102 |
103 | Download link:
104 | https://huggingface.co/Kijai/ChatGLM3-safetensors/resolve/main/chatglm3-fp16.safetensors
105 |
106 |
107 | ## IPAdapter implementation is recommended to use [cubiq/ComfyUI_IPAdapter_plus](https://github.com/cubiq/ComfyUI_IPAdapter_plus)
108 | The faceid related nodes have been supported in it, and the IPAdapter implementation needs to update ComfyUI_IPAdapter_plus to the latest version
109 | ### IPAdapter workflow
110 | https://github.com/cubiq/ComfyUI_IPAdapter_plus/blob/main/examples/ipadapter_kolors.json
111 |
112 | ### IPAdapter_FaceIDv2 workflow
113 | https://github.com/cubiq/ComfyUI_IPAdapter_plus/blob/main/examples/IPAdapter_FaceIDv2_Kolors.json
114 |
115 |
116 | ### Official IP-Adapter-Plus model download link
117 |
118 | Model homepage: https://huggingface.co/Kwai-Kolors/Kolors-IP-Adapter-Plus
119 |
120 | https://huggingface.co/Kwai-Kolors/Kolors-IP-Adapter-Plus/resolve/main/ip_adapter_plus_general.bin Download to models/ipadapter/
121 |
122 | https://huggingface.co/Kwai-Kolors/Kolors-IP-Adapter-Plus/resolve/main/image_encoder/pytorch_model.bin Download to models/clip_vision/
123 |
124 |
125 | ### Official Kolors-IP-Adapter-FaceID-Plus model download link
126 | Model homepage: https://huggingface.co/Kwai-Kolors/Kolors-IP-Adapter-FaceID-Plus
127 |
128 | https://huggingface.co/Kwai-Kolors/Kolors-IP-Adapter-FaceID-Plus/resolve/main/ipa-faceid-plus.bin Download to models/ipadapter/
129 |
130 | https://huggingface.co/Kwai-Kolors/Kolors-IP-Adapter-FaceID-Plus/resolve/main/clip-vit-large-patch14-336/pytorch_model.bin Download to models/clip_vision/
131 |
132 | https://huggingface.co/MonsterMMORPG/tools/resolve/main/antelopev2.zip Download and unzip to models/insightface/models/antelopev2/*.onnx
133 |
134 | ### Official ControlNet model download link
135 | Model homepage(Depth): https://huggingface.co/Kwai-Kolors/Kolors-ControlNet-Depth
136 |
137 | Model homepage(Canny): https://huggingface.co/Kwai-Kolors/Kolors-ControlNet-Canny
138 |
139 | Model homepage(Pose): https://huggingface.co/Kwai-Kolors/Kolors-ControlNet-Pose
140 |
141 | ### Kolors-Inpainting model download link
142 | Model homepage: https://huggingface.co/Kwai-Kolors/Kolors-Inpainting
143 |
144 | https://huggingface.co/Kwai-Kolors/Kolors-Inpainting/resolve/main/unet/diffusion_pytorch_model.safetensors Download to models/unet/
145 |
146 |
147 | ## 使用ComfyUI-KwaiKolorsWrapper在相同种子下测试结果 (Testing results with the same seed using ComfyUI-KwaiKolorsWrapper)
148 | 测试工作流来自examples/workflow_same_seed_test.png
149 |
150 | The test workflow comes from examples/workflow_same_seed_test.png
151 |
152 | 
153 |
154 | ## FAQ
155 | 加载模型时出现的错误
156 | + 目前kolors有两个版本, 一种是unet类型采用unet加载器, 一种是放checkpoints文件夹用KolorsCheckpointLoaderSimple加载器, 如果你的模型来自huggingface的unet文件夹, 优先尝试使用unet加载器 (Currently, there are two versions of kolors, one is unet type using unet loader, and the other is placed in the checkpoints folder using KolorsCheckpointLoaderSimple loader. If your model comes from the huggingface unet folder, try to use the unet loader first)
157 | + 如果你无法确定模型类型, 那就都试一下 (If you are not sure about the model type, try both)
158 |
159 | Mac用户无法使用(Mac users cannot use)
160 | + Mac用户可移步至[ComfyUI-Kolors-MZ](https://github.com/yiwangsimple/ComfyUI-Kolors-MZ) (Mac users can go to [ComfyUI-Kolors-MZ](https://github.com/yiwangsimple/ComfyUI-Kolors-MZ) )
161 |
162 | 和IPAdapter有关的错误(Errors related to IPAdapter)
163 | + 确保ComfyUI本体和ComfyUI_IPAdapter_plus已经更新到最新版本(Make sure ComfyUI ontology and ComfyUI_IPAdapter_plus are updated to the latest version)
164 |
165 | name 'round_up' is not defined
166 | + 参考:https://github.com/THUDM/ChatGLM2-6B/issues/272#issuecomment-1632164243 , 使用 pip install cpm_kernels 或者 pip install -U cpm_kernels 更新 cpm_kernels
167 |
168 | module 'comfy.model_detection' has no attribute 'unet_prefix_from_state_dict'
169 | + 更新ComfyUI本体到最新版本(Update ComfyUI ontology to the latest version)
170 |
171 | RuntimeError: Only Tensors of floating point dtype can require gradients
172 | + 尝试使用fp16版本的模型: https://huggingface.co/Kijai/ChatGLM3-safetensors/blob/main/chatglm3-fp16.safetensors
173 |
174 | Error occurred when executing MZ_ChatGLM3Loader: 'ChatGLMModel' object has no attribute 'transformer'
175 | + 检查ChatGLM3Loader节点选择的模型是否已经正确下载
176 |
177 |
178 | ## Credits
179 |
180 | - [Kolors](https://github.com/Kwai-Kolors/Kolors)
181 | - [ComfyUI](https://github.com/comfyanonymous/ComfyUI)
182 | - [ComfyUI_IPAdapter_plus](https://github.com/cubiq/ComfyUI_IPAdapter_plus)
183 |
184 | ## Star History
185 |
186 |
187 |
188 |
189 |
190 |
191 |
192 |
193 |
194 |
195 | ## Contact
196 | - 微信Wechat: minrszone
197 | - Bilibili: [minus_zone](https://space.bilibili.com/5950992)
198 | - 小红书: [MinusZoneAI](https://www.xiaohongshu.com/user/profile/5f072e990000000001005472)
199 |
200 | ## Stargazers
201 | [](https://github.com/MinusZoneAI/ComfyUI-Kolors-MZ/stargazers)
202 |
203 |
204 |
205 |
206 |
--------------------------------------------------------------------------------
/ComfyUI_IPAdapter_plus/CrossAttentionPatch.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import math
3 | import torch.nn.functional as F
4 | from comfy.ldm.modules.attention import optimized_attention
5 | from .utils import tensor_to_size
6 |
7 | class Attn2Replace:
8 | def __init__(self, callback=None, **kwargs):
9 | self.callback = [callback]
10 | self.kwargs = [kwargs]
11 |
12 | def add(self, callback, **kwargs):
13 | self.callback.append(callback)
14 | self.kwargs.append(kwargs)
15 |
16 | for key, value in kwargs.items():
17 | setattr(self, key, value)
18 |
19 | def __call__(self, q, k, v, extra_options):
20 | dtype = q.dtype
21 | out = optimized_attention(q, k, v, extra_options["n_heads"])
22 | sigma = extra_options["sigmas"].detach().cpu()[0].item() if 'sigmas' in extra_options else 999999999.9
23 |
24 | for i, callback in enumerate(self.callback):
25 | if sigma <= self.kwargs[i]["sigma_start"] and sigma >= self.kwargs[i]["sigma_end"]:
26 | out = out + callback(out, q, k, v, extra_options, **self.kwargs[i])
27 |
28 | return out.to(dtype=dtype)
29 |
30 | def ipadapter_attention(out, q, k, v, extra_options, module_key='', ipadapter=None, weight=1.0, cond=None, cond_alt=None, uncond=None, weight_type="linear", mask=None, sigma_start=0.0, sigma_end=1.0, unfold_batch=False, embeds_scaling='V only', **kwargs):
31 | dtype = q.dtype
32 | cond_or_uncond = extra_options["cond_or_uncond"]
33 | block_type = extra_options["block"][0]
34 | #block_id = extra_options["block"][1]
35 | t_idx = extra_options["transformer_index"]
36 | layers = 11 if '101_to_k_ip' in ipadapter.ip_layers.to_kvs else 16
37 | k_key = module_key + "_to_k_ip"
38 | v_key = module_key + "_to_v_ip"
39 |
40 | # extra options for AnimateDiff
41 | ad_params = extra_options['ad_params'] if "ad_params" in extra_options else None
42 |
43 | b = q.shape[0]
44 | seq_len = q.shape[1]
45 | batch_prompt = b // len(cond_or_uncond)
46 | _, _, oh, ow = extra_options["original_shape"]
47 |
48 | if weight_type == 'ease in':
49 | weight = weight * (0.05 + 0.95 * (1 - t_idx / layers))
50 | elif weight_type == 'ease out':
51 | weight = weight * (0.05 + 0.95 * (t_idx / layers))
52 | elif weight_type == 'ease in-out':
53 | weight = weight * (0.05 + 0.95 * (1 - abs(t_idx - (layers/2)) / (layers/2)))
54 | elif weight_type == 'reverse in-out':
55 | weight = weight * (0.05 + 0.95 * (abs(t_idx - (layers/2)) / (layers/2)))
56 | elif weight_type == 'weak input' and block_type == 'input':
57 | weight = weight * 0.2
58 | elif weight_type == 'weak middle' and block_type == 'middle':
59 | weight = weight * 0.2
60 | elif weight_type == 'weak output' and block_type == 'output':
61 | weight = weight * 0.2
62 | elif weight_type == 'strong middle' and (block_type == 'input' or block_type == 'output'):
63 | weight = weight * 0.2
64 | elif isinstance(weight, dict):
65 | if t_idx not in weight:
66 | return 0
67 |
68 | if weight_type == "style transfer precise":
69 | if layers == 11 and t_idx == 3:
70 | uncond = cond
71 | cond = cond * 0
72 | elif layers == 16 and (t_idx == 4 or t_idx == 5):
73 | uncond = cond
74 | cond = cond * 0
75 | elif weight_type == "composition precise":
76 | if layers == 11 and t_idx != 3:
77 | uncond = cond
78 | cond = cond * 0
79 | elif layers == 16 and (t_idx != 4 and t_idx != 5):
80 | uncond = cond
81 | cond = cond * 0
82 |
83 | weight = weight[t_idx]
84 |
85 | if cond_alt is not None and t_idx in cond_alt:
86 | cond = cond_alt[t_idx]
87 | del cond_alt
88 |
89 | if unfold_batch:
90 | # Check AnimateDiff context window
91 | if ad_params is not None and ad_params["sub_idxs"] is not None:
92 | if isinstance(weight, torch.Tensor):
93 | weight = tensor_to_size(weight, ad_params["full_length"])
94 | weight = torch.Tensor(weight[ad_params["sub_idxs"]])
95 | if torch.all(weight == 0):
96 | return 0
97 | weight = weight.repeat(len(cond_or_uncond), 1, 1) # repeat for cond and uncond
98 | elif weight == 0:
99 | return 0
100 |
101 | # if image length matches or exceeds full_length get sub_idx images
102 | if cond.shape[0] >= ad_params["full_length"]:
103 | cond = torch.Tensor(cond[ad_params["sub_idxs"]])
104 | uncond = torch.Tensor(uncond[ad_params["sub_idxs"]])
105 | # otherwise get sub_idxs images
106 | else:
107 | cond = tensor_to_size(cond, ad_params["full_length"])
108 | uncond = tensor_to_size(uncond, ad_params["full_length"])
109 | cond = cond[ad_params["sub_idxs"]]
110 | uncond = uncond[ad_params["sub_idxs"]]
111 | else:
112 | if isinstance(weight, torch.Tensor):
113 | weight = tensor_to_size(weight, batch_prompt)
114 | if torch.all(weight == 0):
115 | return 0
116 | weight = weight.repeat(len(cond_or_uncond), 1, 1) # repeat for cond and uncond
117 | elif weight == 0:
118 | return 0
119 |
120 | cond = tensor_to_size(cond, batch_prompt)
121 | uncond = tensor_to_size(uncond, batch_prompt)
122 |
123 | k_cond = ipadapter.ip_layers.to_kvs[k_key](cond)
124 | k_uncond = ipadapter.ip_layers.to_kvs[k_key](uncond)
125 | v_cond = ipadapter.ip_layers.to_kvs[v_key](cond)
126 | v_uncond = ipadapter.ip_layers.to_kvs[v_key](uncond)
127 | else:
128 | # TODO: should we always convert the weights to a tensor?
129 | if isinstance(weight, torch.Tensor):
130 | weight = tensor_to_size(weight, batch_prompt)
131 | if torch.all(weight == 0):
132 | return 0
133 | weight = weight.repeat(len(cond_or_uncond), 1, 1) # repeat for cond and uncond
134 | elif weight == 0:
135 | return 0
136 |
137 | k_cond = ipadapter.ip_layers.to_kvs[k_key](cond).repeat(batch_prompt, 1, 1)
138 | k_uncond = ipadapter.ip_layers.to_kvs[k_key](uncond).repeat(batch_prompt, 1, 1)
139 | v_cond = ipadapter.ip_layers.to_kvs[v_key](cond).repeat(batch_prompt, 1, 1)
140 | v_uncond = ipadapter.ip_layers.to_kvs[v_key](uncond).repeat(batch_prompt, 1, 1)
141 |
142 | if len(cond_or_uncond) == 3: # TODO: conxl, I need to check this
143 | ip_k = torch.cat([(k_cond, k_uncond, k_cond)[i] for i in cond_or_uncond], dim=0)
144 | ip_v = torch.cat([(v_cond, v_uncond, v_cond)[i] for i in cond_or_uncond], dim=0)
145 | else:
146 | ip_k = torch.cat([(k_cond, k_uncond)[i] for i in cond_or_uncond], dim=0)
147 | ip_v = torch.cat([(v_cond, v_uncond)[i] for i in cond_or_uncond], dim=0)
148 |
149 | if embeds_scaling == 'K+mean(V) w/ C penalty':
150 | scaling = float(ip_k.shape[2]) / 1280.0
151 | weight = weight * scaling
152 | ip_k = ip_k * weight
153 | ip_v_mean = torch.mean(ip_v, dim=1, keepdim=True)
154 | ip_v = (ip_v - ip_v_mean) + ip_v_mean * weight
155 | out_ip = optimized_attention(q, ip_k, ip_v, extra_options["n_heads"])
156 | del ip_v_mean
157 | elif embeds_scaling == 'K+V w/ C penalty':
158 | scaling = float(ip_k.shape[2]) / 1280.0
159 | weight = weight * scaling
160 | ip_k = ip_k * weight
161 | ip_v = ip_v * weight
162 | out_ip = optimized_attention(q, ip_k, ip_v, extra_options["n_heads"])
163 | elif embeds_scaling == 'K+V':
164 | ip_k = ip_k * weight
165 | ip_v = ip_v * weight
166 | out_ip = optimized_attention(q, ip_k, ip_v, extra_options["n_heads"])
167 | else:
168 | #ip_v = ip_v * weight
169 | out_ip = optimized_attention(q, ip_k, ip_v, extra_options["n_heads"])
170 | out_ip = out_ip * weight # I'm doing this to get the same results as before
171 |
172 | if mask is not None:
173 | mask_h = oh / math.sqrt(oh * ow / seq_len)
174 | mask_h = int(mask_h) + int((seq_len % int(mask_h)) != 0)
175 | mask_w = seq_len // mask_h
176 |
177 | # check if using AnimateDiff and sliding context window
178 | if (mask.shape[0] > 1 and ad_params is not None and ad_params["sub_idxs"] is not None):
179 | # if mask length matches or exceeds full_length, get sub_idx masks
180 | if mask.shape[0] >= ad_params["full_length"]:
181 | mask = torch.Tensor(mask[ad_params["sub_idxs"]])
182 | mask = F.interpolate(mask.unsqueeze(1), size=(mask_h, mask_w), mode="bilinear").squeeze(1)
183 | else:
184 | mask = F.interpolate(mask.unsqueeze(1), size=(mask_h, mask_w), mode="bilinear").squeeze(1)
185 | mask = tensor_to_size(mask, ad_params["full_length"])
186 | mask = mask[ad_params["sub_idxs"]]
187 | else:
188 | mask = F.interpolate(mask.unsqueeze(1), size=(mask_h, mask_w), mode="bilinear").squeeze(1)
189 | mask = tensor_to_size(mask, batch_prompt)
190 |
191 | mask = mask.repeat(len(cond_or_uncond), 1, 1)
192 | mask = mask.view(mask.shape[0], -1, 1).repeat(1, 1, out.shape[2])
193 |
194 | # covers cases where extreme aspect ratios can cause the mask to have a wrong size
195 | mask_len = mask_h * mask_w
196 | if mask_len < seq_len:
197 | pad_len = seq_len - mask_len
198 | pad1 = pad_len // 2
199 | pad2 = pad_len - pad1
200 | mask = F.pad(mask, (0, 0, pad1, pad2), value=0.0)
201 | elif mask_len > seq_len:
202 | crop_start = (mask_len - seq_len) // 2
203 | mask = mask[:, crop_start:crop_start+seq_len, :]
204 |
205 | out_ip = out_ip * mask
206 |
207 | #out = out + out_ip
208 |
209 | return out_ip.to(dtype=dtype)
210 |
--------------------------------------------------------------------------------
/ComfyUI_IPAdapter_plus/image_proj_models.py:
--------------------------------------------------------------------------------
1 | import math
2 | import torch
3 | import torch.nn as nn
4 | from einops import rearrange
5 | from einops.layers.torch import Rearrange
6 |
7 |
8 | # FFN
9 | def FeedForward(dim, mult=4):
10 | inner_dim = int(dim * mult)
11 | return nn.Sequential(
12 | nn.LayerNorm(dim),
13 | nn.Linear(dim, inner_dim, bias=False),
14 | nn.GELU(),
15 | nn.Linear(inner_dim, dim, bias=False),
16 | )
17 |
18 |
19 | def reshape_tensor(x, heads):
20 | bs, length, width = x.shape
21 | # (bs, length, width) --> (bs, length, n_heads, dim_per_head)
22 | x = x.view(bs, length, heads, -1)
23 | # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
24 | x = x.transpose(1, 2)
25 | # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
26 | x = x.reshape(bs, heads, length, -1)
27 | return x
28 |
29 |
30 | class PerceiverAttention(nn.Module):
31 | def __init__(self, *, dim, dim_head=64, heads=8):
32 | super().__init__()
33 | self.scale = dim_head**-0.5
34 | self.dim_head = dim_head
35 | self.heads = heads
36 | inner_dim = dim_head * heads
37 |
38 | self.norm1 = nn.LayerNorm(dim)
39 | self.norm2 = nn.LayerNorm(dim)
40 |
41 | self.to_q = nn.Linear(dim, inner_dim, bias=False)
42 | self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
43 | self.to_out = nn.Linear(inner_dim, dim, bias=False)
44 |
45 | def forward(self, x, latents):
46 | """
47 | Args:
48 | x (torch.Tensor): image features
49 | shape (b, n1, D)
50 | latent (torch.Tensor): latent features
51 | shape (b, n2, D)
52 | """
53 | x = self.norm1(x)
54 | latents = self.norm2(latents)
55 |
56 | b, l, _ = latents.shape
57 |
58 | q = self.to_q(latents)
59 | kv_input = torch.cat((x, latents), dim=-2)
60 | k, v = self.to_kv(kv_input).chunk(2, dim=-1)
61 |
62 | q = reshape_tensor(q, self.heads)
63 | k = reshape_tensor(k, self.heads)
64 | v = reshape_tensor(v, self.heads)
65 |
66 | # attention
67 | scale = 1 / math.sqrt(math.sqrt(self.dim_head))
68 | weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards
69 | weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
70 | out = weight @ v
71 |
72 | out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
73 |
74 | return self.to_out(out)
75 |
76 |
77 | class Resampler(nn.Module):
78 | def __init__(
79 | self,
80 | dim=1024,
81 | depth=8,
82 | dim_head=64,
83 | heads=16,
84 | num_queries=8,
85 | embedding_dim=768,
86 | output_dim=1024,
87 | ff_mult=4,
88 | max_seq_len: int = 257, # CLIP tokens + CLS token
89 | apply_pos_emb: bool = False,
90 | num_latents_mean_pooled: int = 0, # number of latents derived from mean pooled representation of the sequence
91 | ):
92 | super().__init__()
93 | self.pos_emb = nn.Embedding(max_seq_len, embedding_dim) if apply_pos_emb else None
94 |
95 | self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim**0.5)
96 |
97 | self.proj_in = nn.Linear(embedding_dim, dim)
98 |
99 | self.proj_out = nn.Linear(dim, output_dim)
100 | self.norm_out = nn.LayerNorm(output_dim)
101 |
102 | self.to_latents_from_mean_pooled_seq = (
103 | nn.Sequential(
104 | nn.LayerNorm(dim),
105 | nn.Linear(dim, dim * num_latents_mean_pooled),
106 | Rearrange("b (n d) -> b n d", n=num_latents_mean_pooled),
107 | )
108 | if num_latents_mean_pooled > 0
109 | else None
110 | )
111 |
112 | self.layers = nn.ModuleList([])
113 | for _ in range(depth):
114 | self.layers.append(
115 | nn.ModuleList(
116 | [
117 | PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
118 | FeedForward(dim=dim, mult=ff_mult),
119 | ]
120 | )
121 | )
122 |
123 | def forward(self, x):
124 | if self.pos_emb is not None:
125 | n, device = x.shape[1], x.device
126 | pos_emb = self.pos_emb(torch.arange(n, device=device))
127 | x = x + pos_emb
128 |
129 | latents = self.latents.repeat(x.size(0), 1, 1)
130 |
131 | x = self.proj_in(x)
132 |
133 | if self.to_latents_from_mean_pooled_seq:
134 | meanpooled_seq = masked_mean(x, dim=1, mask=torch.ones(x.shape[:2], device=x.device, dtype=torch.bool))
135 | meanpooled_latents = self.to_latents_from_mean_pooled_seq(meanpooled_seq)
136 | latents = torch.cat((meanpooled_latents, latents), dim=-2)
137 |
138 | for attn, ff in self.layers:
139 | latents = attn(x, latents) + latents
140 | latents = ff(latents) + latents
141 |
142 | latents = self.proj_out(latents)
143 | return self.norm_out(latents)
144 |
145 |
146 | def masked_mean(t, *, dim, mask=None):
147 | if mask is None:
148 | return t.mean(dim=dim)
149 |
150 | denom = mask.sum(dim=dim, keepdim=True)
151 | mask = rearrange(mask, "b n -> b n 1")
152 | masked_t = t.masked_fill(~mask, 0.0)
153 |
154 | return masked_t.sum(dim=dim) / denom.clamp(min=1e-5)
155 |
156 |
157 | class FacePerceiverResampler(nn.Module):
158 | def __init__(
159 | self,
160 | *,
161 | dim=768,
162 | depth=4,
163 | dim_head=64,
164 | heads=16,
165 | embedding_dim=1280,
166 | output_dim=768,
167 | ff_mult=4,
168 | ):
169 | super().__init__()
170 |
171 | self.proj_in = nn.Linear(embedding_dim, dim)
172 | self.proj_out = nn.Linear(dim, output_dim)
173 | self.norm_out = nn.LayerNorm(output_dim)
174 | self.layers = nn.ModuleList([])
175 | for _ in range(depth):
176 | self.layers.append(
177 | nn.ModuleList(
178 | [
179 | PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
180 | FeedForward(dim=dim, mult=ff_mult),
181 | ]
182 | )
183 | )
184 |
185 | def forward(self, latents, x):
186 | x = self.proj_in(x)
187 | for attn, ff in self.layers:
188 | latents = attn(x, latents) + latents
189 | latents = ff(latents) + latents
190 | latents = self.proj_out(latents)
191 | return self.norm_out(latents)
192 |
193 |
194 | class MLPProjModel(nn.Module):
195 | def __init__(self, cross_attention_dim=1024, clip_embeddings_dim=1024):
196 | super().__init__()
197 |
198 | self.proj = nn.Sequential(
199 | nn.Linear(clip_embeddings_dim, clip_embeddings_dim),
200 | nn.GELU(),
201 | nn.Linear(clip_embeddings_dim, cross_attention_dim),
202 | nn.LayerNorm(cross_attention_dim)
203 | )
204 |
205 | def forward(self, image_embeds):
206 | clip_extra_context_tokens = self.proj(image_embeds)
207 | return clip_extra_context_tokens
208 |
209 | class MLPProjModelFaceId(nn.Module):
210 | def __init__(self, cross_attention_dim=768, id_embeddings_dim=512, num_tokens=4):
211 | super().__init__()
212 |
213 | self.cross_attention_dim = cross_attention_dim
214 | self.num_tokens = num_tokens
215 |
216 | self.proj = nn.Sequential(
217 | nn.Linear(id_embeddings_dim, id_embeddings_dim*2),
218 | nn.GELU(),
219 | nn.Linear(id_embeddings_dim*2, cross_attention_dim*num_tokens),
220 | )
221 | self.norm = nn.LayerNorm(cross_attention_dim)
222 |
223 | def forward(self, id_embeds):
224 | x = self.proj(id_embeds)
225 | x = x.reshape(-1, self.num_tokens, self.cross_attention_dim)
226 | x = self.norm(x)
227 | return x
228 |
229 | class ProjModelFaceIdPlus(nn.Module):
230 | def __init__(self, cross_attention_dim=768, id_embeddings_dim=512, clip_embeddings_dim=1280, num_tokens=4):
231 | super().__init__()
232 |
233 | self.cross_attention_dim = cross_attention_dim
234 | self.num_tokens = num_tokens
235 |
236 | self.proj = nn.Sequential(
237 | nn.Linear(id_embeddings_dim, id_embeddings_dim*2),
238 | nn.GELU(),
239 | nn.Linear(id_embeddings_dim*2, cross_attention_dim*num_tokens),
240 | )
241 | self.norm = nn.LayerNorm(cross_attention_dim)
242 |
243 | self.perceiver_resampler = FacePerceiverResampler(
244 | dim=cross_attention_dim,
245 | depth=4,
246 | dim_head=64,
247 | heads=cross_attention_dim // 64,
248 | embedding_dim=clip_embeddings_dim,
249 | output_dim=cross_attention_dim,
250 | ff_mult=4,
251 | )
252 |
253 | def forward(self, id_embeds, clip_embeds, scale=1.0, shortcut=False):
254 | x = self.proj(id_embeds)
255 | x = x.reshape(-1, self.num_tokens, self.cross_attention_dim)
256 | x = self.norm(x)
257 | out = self.perceiver_resampler(x, clip_embeds)
258 | if shortcut:
259 | out = x + scale * out
260 | return out
261 |
262 | class ImageProjModel(nn.Module):
263 | def __init__(self, cross_attention_dim=1024, clip_embeddings_dim=1024, clip_extra_context_tokens=4):
264 | super().__init__()
265 |
266 | self.cross_attention_dim = cross_attention_dim
267 | self.clip_extra_context_tokens = clip_extra_context_tokens
268 | self.proj = nn.Linear(clip_embeddings_dim, self.clip_extra_context_tokens * cross_attention_dim)
269 | self.norm = nn.LayerNorm(cross_attention_dim)
270 |
271 | def forward(self, image_embeds):
272 | embeds = image_embeds
273 | x = self.proj(embeds).reshape(-1, self.clip_extra_context_tokens, self.cross_attention_dim)
274 | x = self.norm(x)
275 | return x
276 |
--------------------------------------------------------------------------------
/ComfyUI_IPAdapter_plus/utils.py:
--------------------------------------------------------------------------------
1 | import re
2 | import torch
3 | import os
4 | import folder_paths
5 | from comfy.clip_vision import clip_preprocess, Output
6 | import comfy.utils
7 | import comfy.model_management as model_management
8 | try:
9 | import torchvision.transforms.v2 as T
10 | except ImportError:
11 | import torchvision.transforms as T
12 |
13 | def get_clipvision_file(preset):
14 | preset = preset.lower()
15 | clipvision_list = folder_paths.get_filename_list("clip_vision")
16 |
17 | if preset.startswith("vit-g"):
18 | pattern = r'(ViT.bigG.14.*39B.b160k|ipadapter.*sdxl|sdxl.*model\.(bin|safetensors))'
19 | else:
20 | pattern = r'(ViT.H.14.*s32B.b79K|ipadapter.*sd15|sd1.?5.*model\.(bin|safetensors))'
21 | clipvision_file = [e for e in clipvision_list if re.search(pattern, e, re.IGNORECASE)]
22 |
23 | clipvision_file = folder_paths.get_full_path("clip_vision", clipvision_file[0]) if clipvision_file else None
24 |
25 | return clipvision_file
26 |
27 | def get_ipadapter_file(preset, is_sdxl):
28 | preset = preset.lower()
29 | ipadapter_list = folder_paths.get_filename_list("ipadapter")
30 | is_insightface = False
31 | lora_pattern = None
32 |
33 | if preset.startswith("light"):
34 | if is_sdxl:
35 | raise Exception("light model is not supported for SDXL")
36 | pattern = r'sd15.light.v11\.(safetensors|bin)$'
37 | # if v11 is not found, try with the old version
38 | if not [e for e in ipadapter_list if re.search(pattern, e, re.IGNORECASE)]:
39 | pattern = r'sd15.light\.(safetensors|bin)$'
40 | elif preset.startswith("standard"):
41 | if is_sdxl:
42 | pattern = r'ip.adapter.sdxl.vit.h\.(safetensors|bin)$'
43 | else:
44 | pattern = r'ip.adapter.sd15\.(safetensors|bin)$'
45 | elif preset.startswith("vit-g"):
46 | if is_sdxl:
47 | pattern = r'ip.adapter.sdxl\.(safetensors|bin)$'
48 | else:
49 | pattern = r'sd15.vit.g\.(safetensors|bin)$'
50 | elif preset.startswith("plus ("):
51 | if is_sdxl:
52 | pattern = r'plus.sdxl.vit.h\.(safetensors|bin)$'
53 | else:
54 | pattern = r'ip.adapter.plus.sd15\.(safetensors|bin)$'
55 | elif preset.startswith("plus face"):
56 | if is_sdxl:
57 | pattern = r'plus.face.sdxl.vit.h\.(safetensors|bin)$'
58 | else:
59 | pattern = r'plus.face.sd15\.(safetensors|bin)$'
60 | elif preset.startswith("full"):
61 | if is_sdxl:
62 | raise Exception("full face model is not supported for SDXL")
63 | pattern = r'full.face.sd15\.(safetensors|bin)$'
64 | elif preset.startswith("faceid portrait ("):
65 | if is_sdxl:
66 | pattern = r'portrait.sdxl\.(safetensors|bin)$'
67 | else:
68 | pattern = r'portrait.v11.sd15\.(safetensors|bin)$'
69 | # if v11 is not found, try with the old version
70 | if not [e for e in ipadapter_list if re.search(pattern, e, re.IGNORECASE)]:
71 | pattern = r'portrait.sd15\.(safetensors|bin)$'
72 | is_insightface = True
73 | elif preset.startswith("faceid portrait unnorm"):
74 | if is_sdxl:
75 | pattern = r'portrait.sdxl.unnorm\.(safetensors|bin)$'
76 | else:
77 | raise Exception("portrait unnorm model is not supported for SD1.5")
78 | is_insightface = True
79 | elif preset == "faceid":
80 | if is_sdxl:
81 | pattern = r'faceid.sdxl\.(safetensors|bin)$'
82 | lora_pattern = r'faceid.sdxl.lora\.safetensors$'
83 | else:
84 | pattern = r'faceid.sd15\.(safetensors|bin)$'
85 | lora_pattern = r'faceid.sd15.lora\.safetensors$'
86 | is_insightface = True
87 | elif preset.startswith("faceid plus -"):
88 | if is_sdxl:
89 | raise Exception("faceid plus model is not supported for SDXL")
90 | pattern = r'faceid.plus.sd15\.(safetensors|bin)$'
91 | lora_pattern = r'faceid.plus.sd15.lora\.safetensors$'
92 | is_insightface = True
93 | elif preset.startswith("faceid plus v2"):
94 | if is_sdxl:
95 | pattern = r'faceid.plusv2.sdxl\.(safetensors|bin)$'
96 | lora_pattern = r'faceid.plusv2.sdxl.lora\.safetensors$'
97 | else:
98 | pattern = r'faceid.plusv2.sd15\.(safetensors|bin)$'
99 | lora_pattern = r'faceid.plusv2.sd15.lora\.safetensors$'
100 | is_insightface = True
101 | # Community's models
102 | elif preset.startswith("composition"):
103 | if is_sdxl:
104 | pattern = r'plus.composition.sdxl\.safetensors$'
105 | else:
106 | pattern = r'plus.composition.sd15\.safetensors$'
107 | else:
108 | raise Exception(f"invalid type '{preset}'")
109 |
110 | ipadapter_file = [e for e in ipadapter_list if re.search(pattern, e, re.IGNORECASE)]
111 | ipadapter_file = folder_paths.get_full_path("ipadapter", ipadapter_file[0]) if ipadapter_file else None
112 |
113 | return ipadapter_file, is_insightface, lora_pattern
114 |
115 | def get_lora_file(pattern):
116 | lora_list = folder_paths.get_filename_list("loras")
117 | lora_file = [e for e in lora_list if re.search(pattern, e, re.IGNORECASE)]
118 | lora_file = folder_paths.get_full_path("loras", lora_file[0]) if lora_file else None
119 |
120 | return lora_file
121 |
122 | def ipadapter_model_loader(file):
123 | model = comfy.utils.load_torch_file(file, safe_load=True)
124 |
125 | if file.lower().endswith(".safetensors"):
126 | st_model = {"image_proj": {}, "ip_adapter": {}}
127 | for key in model.keys():
128 | if key.startswith("image_proj."):
129 | st_model["image_proj"][key.replace("image_proj.", "")] = model[key]
130 | elif key.startswith("ip_adapter."):
131 | st_model["ip_adapter"][key.replace("ip_adapter.", "")] = model[key]
132 | model = st_model
133 | del st_model
134 |
135 | if "adapter_modules" in model.keys():
136 | model["ip_adapter"] = model["adapter_modules"]
137 | del model["adapter_modules"]
138 |
139 | if not "ip_adapter" in model.keys() or not model["ip_adapter"]:
140 | raise Exception("invalid IPAdapter model {}".format(file))
141 |
142 | if 'plusv2' in file.lower():
143 | model["faceidplusv2"] = True
144 |
145 | if 'unnorm' in file.lower():
146 | model["portraitunnorm"] = True
147 |
148 | return model
149 |
150 | def insightface_loader(provider):
151 | try:
152 | from insightface.app import FaceAnalysis
153 | except ImportError as e:
154 | raise Exception(e)
155 |
156 | path = os.path.join(folder_paths.models_dir, "insightface")
157 | model = FaceAnalysis(name="antelopev2", root=path, providers=[provider + 'ExecutionProvider',])
158 | model.prepare(ctx_id=0, det_size=(640, 640))
159 | return model
160 |
161 | def encode_image_masked(clip_vision, image, mask=None, batch_size=0, size=224):
162 | model_management.load_model_gpu(clip_vision.patcher)
163 | outputs = Output()
164 |
165 | if batch_size == 0:
166 | batch_size = image.shape[0]
167 | elif batch_size > image.shape[0]:
168 | batch_size = image.shape[0]
169 |
170 | image_batch = torch.split(image, batch_size, dim=0)
171 |
172 | for img in image_batch:
173 | img = img.to(clip_vision.load_device)
174 |
175 | pixel_values = clip_preprocess(img.to(clip_vision.load_device), size=size).float()
176 |
177 | # TODO: support for multiple masks
178 | if mask is not None:
179 | pixel_values = pixel_values * mask.to(clip_vision.load_device)
180 |
181 | out = clip_vision.model(pixel_values=pixel_values, intermediate_output=-2)
182 |
183 | if not hasattr(outputs, "last_hidden_state"):
184 | outputs["last_hidden_state"] = out[0].to(model_management.intermediate_device())
185 | outputs["image_embeds"] = out[2].to(model_management.intermediate_device())
186 | outputs["penultimate_hidden_states"] = out[1].to(model_management.intermediate_device())
187 | else:
188 | outputs["last_hidden_state"] = torch.cat((outputs["last_hidden_state"], out[0].to(model_management.intermediate_device())), dim=0)
189 | outputs["image_embeds"] = torch.cat((outputs["image_embeds"], out[2].to(model_management.intermediate_device())), dim=0)
190 | outputs["penultimate_hidden_states"] = torch.cat((outputs["penultimate_hidden_states"], out[1].to(model_management.intermediate_device())), dim=0)
191 |
192 | del img, pixel_values, out
193 | torch.cuda.empty_cache()
194 |
195 | return outputs
196 |
197 | def tensor_to_size(source, dest_size):
198 | if isinstance(dest_size, torch.Tensor):
199 | dest_size = dest_size.shape[0]
200 | source_size = source.shape[0]
201 |
202 | if source_size < dest_size:
203 | shape = [dest_size - source_size] + [1]*(source.dim()-1)
204 | source = torch.cat((source, source[-1:].repeat(shape)), dim=0)
205 | elif source_size > dest_size:
206 | source = source[:dest_size]
207 |
208 | return source
209 |
210 | def min_(tensor_list):
211 | # return the element-wise min of the tensor list.
212 | x = torch.stack(tensor_list)
213 | mn = x.min(axis=0)[0]
214 | return torch.clamp(mn, min=0)
215 |
216 | def max_(tensor_list):
217 | # return the element-wise max of the tensor list.
218 | x = torch.stack(tensor_list)
219 | mx = x.max(axis=0)[0]
220 | return torch.clamp(mx, max=1)
221 |
222 | # From https://github.com/Jamy-L/Pytorch-Contrast-Adaptive-Sharpening/
223 | def contrast_adaptive_sharpening(image, amount):
224 | img = T.functional.pad(image, (1, 1, 1, 1)).cpu()
225 |
226 | a = img[..., :-2, :-2]
227 | b = img[..., :-2, 1:-1]
228 | c = img[..., :-2, 2:]
229 | d = img[..., 1:-1, :-2]
230 | e = img[..., 1:-1, 1:-1]
231 | f = img[..., 1:-1, 2:]
232 | g = img[..., 2:, :-2]
233 | h = img[..., 2:, 1:-1]
234 | i = img[..., 2:, 2:]
235 |
236 | # Computing contrast
237 | cross = (b, d, e, f, h)
238 | mn = min_(cross)
239 | mx = max_(cross)
240 |
241 | diag = (a, c, g, i)
242 | mn2 = min_(diag)
243 | mx2 = max_(diag)
244 | mx = mx + mx2
245 | mn = mn + mn2
246 |
247 | # Computing local weight
248 | inv_mx = torch.reciprocal(mx)
249 | amp = inv_mx * torch.minimum(mn, (2 - mx))
250 |
251 | # scaling
252 | amp = torch.sqrt(amp)
253 | w = - amp * (amount * (1/5 - 1/8) + 1/8)
254 | div = torch.reciprocal(1 + 4*w)
255 |
256 | output = ((b + d + f + h)*w + e) * div
257 | output = torch.nan_to_num(output)
258 | output = output.clamp(0, 1)
259 |
260 | return output
261 |
262 | def tensor_to_image(tensor):
263 | image = tensor.mul(255).clamp(0, 255).byte().cpu()
264 | image = image[..., [2, 1, 0]].numpy()
265 | return image
266 |
267 | def image_to_tensor(image):
268 | tensor = torch.clamp(torch.from_numpy(image).float() / 255., 0, 1)
269 | tensor = tensor[..., [2, 1, 0]]
270 | return tensor
271 |
--------------------------------------------------------------------------------
/__init__.py:
--------------------------------------------------------------------------------
1 | import inspect
2 | import json
3 | import os
4 | import folder_paths
5 | import importlib
6 |
7 |
8 | NODE_CLASS_MAPPINGS = {
9 | }
10 |
11 |
12 | NODE_DISPLAY_NAME_MAPPINGS = {
13 | }
14 |
15 | MAX_RESOLUTION = 16384
16 |
17 | AUTHOR_NAME = "MinusZone"
18 | CATEGORY_NAME = f"{AUTHOR_NAME} - Kolors"
19 | folder_paths.add_model_folder_path(
20 | "LLM", os.path.join(folder_paths.models_dir, "LLM"))
21 |
22 |
23 | class MZ_ChatGLM3Loader:
24 | @classmethod
25 | def INPUT_TYPES(s):
26 | # from .mz_kolors_utils import Utils
27 | # llm_dir = os.path.join(Utils.get_models_path(), "LLM")
28 | # print("llm_dir:", llm_dir)
29 | llm_models = folder_paths.get_filename_list("LLM")
30 |
31 | # 筛选safetensors结尾的文件
32 | llm_models = [
33 | model for model in llm_models if model.endswith("safetensors")]
34 |
35 | return {"required": {
36 | "chatglm3_checkpoint": (llm_models,),
37 | }}
38 |
39 | RETURN_TYPES = ("CHATGLM3MODEL",)
40 | RETURN_NAMES = ("chatglm3_model",)
41 | FUNCTION = "load_chatglm3"
42 | CATEGORY = CATEGORY_NAME
43 |
44 | def load_chatglm3(self, **kwargs):
45 | from . import mz_kolors_core
46 | importlib.reload(mz_kolors_core)
47 | return mz_kolors_core.MZ_ChatGLM3Loader_call(kwargs)
48 |
49 |
50 | NODE_CLASS_MAPPINGS["MZ_ChatGLM3Loader"] = MZ_ChatGLM3Loader
51 | NODE_DISPLAY_NAME_MAPPINGS["MZ_ChatGLM3Loader"] = f"{AUTHOR_NAME} - ChatGLM3Loader"
52 |
53 |
54 | class MZ_ChatGLM3TextEncodeV2:
55 | @classmethod
56 | def INPUT_TYPES(s):
57 | return {
58 | "required": {
59 | "chatglm3_model": ("CHATGLM3MODEL", ),
60 | "text": ("STRING", {"multiline": True, "dynamicPrompts": True}),
61 | }
62 | }
63 |
64 | RETURN_TYPES = ("CONDITIONING",)
65 |
66 | FUNCTION = "encode"
67 | CATEGORY = CATEGORY_NAME
68 |
69 | def encode(self, **kwargs):
70 | from . import mz_kolors_core
71 | importlib.reload(mz_kolors_core)
72 | return mz_kolors_core.MZ_ChatGLM3TextEncodeV2_call(kwargs)
73 |
74 |
75 | NODE_CLASS_MAPPINGS["MZ_ChatGLM3_V2"] = MZ_ChatGLM3TextEncodeV2
76 | NODE_DISPLAY_NAME_MAPPINGS[
77 | "MZ_ChatGLM3_V2"] = f"{AUTHOR_NAME} - ChatGLM3TextEncodeV2"
78 |
79 |
80 | class MZ_ChatGLM3Embeds2Conditioning:
81 | @classmethod
82 | def INPUT_TYPES(s):
83 | return {
84 | "required": {
85 | "kolors_embeds": ("KOLORS_EMBEDS", ),
86 | "width": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
87 | "height": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
88 | "crop_w": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION}),
89 | "crop_h": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION}),
90 | "target_width": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
91 | "target_height": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
92 | }
93 | }
94 |
95 | RETURN_TYPES = ("CONDITIONING", "CONDITIONING",)
96 | RETURN_NAMES = ("positive", "negative",)
97 |
98 | FUNCTION = "embeds2conditioning"
99 | CATEGORY = CATEGORY_NAME
100 |
101 | def embeds2conditioning(self, **kwargs):
102 | from . import mz_kolors_core
103 | importlib.reload(mz_kolors_core)
104 | return mz_kolors_core.MZ_ChatGLM3Embeds2Conditioning_call(kwargs)
105 |
106 |
107 | NODE_CLASS_MAPPINGS["MZ_ChatGLM3Embeds2Conditioning"] = MZ_ChatGLM3Embeds2Conditioning
108 | NODE_DISPLAY_NAME_MAPPINGS[
109 | "MZ_ChatGLM3Embeds2Conditioning"] = f"{AUTHOR_NAME} - ChatGLM3Embeds2Conditioning"
110 |
111 |
112 | # for 2048 resolution
113 | class MZ_ChatGLM3TextEncodeAdvanceV2:
114 | @classmethod
115 | def INPUT_TYPES(s):
116 | return {
117 | "required": {
118 | "chatglm3_model": ("CHATGLM3MODEL", ),
119 | "text": ("STRING", {"multiline": True, "dynamicPrompts": True}),
120 | "width": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
121 | "height": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
122 | "crop_w": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION}),
123 | "crop_h": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION}),
124 | "target_width": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
125 | "target_height": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
126 | }
127 | }
128 |
129 | RETURN_TYPES = ("CONDITIONING",)
130 |
131 | FUNCTION = "encode"
132 | CATEGORY = CATEGORY_NAME
133 |
134 | def encode(self, **kwargs):
135 | from . import mz_kolors_core
136 | importlib.reload(mz_kolors_core)
137 | return mz_kolors_core.MZ_ChatGLM3TextEncodeV2_call(kwargs)
138 |
139 |
140 | NODE_CLASS_MAPPINGS["MZ_ChatGLM3_Advance_V2"] = MZ_ChatGLM3TextEncodeAdvanceV2
141 | NODE_DISPLAY_NAME_MAPPINGS[
142 | "MZ_ChatGLM3_Advance_V2"] = f"{AUTHOR_NAME} - ChatGLM3TextEncodeAdvanceV2"
143 |
144 |
145 | class MZ_KolorsCheckpointLoaderSimple():
146 | @classmethod
147 | def INPUT_TYPES(s):
148 | return {"required": {"ckpt_name": (folder_paths.get_filename_list("checkpoints"), ),
149 | }}
150 | RETURN_TYPES = ("MODEL", "VAE")
151 | FUNCTION = "load_checkpoint"
152 |
153 | CATEGORY = CATEGORY_NAME
154 |
155 | def load_checkpoint(self, **kwargs):
156 | from . import mz_kolors_core
157 | importlib.reload(mz_kolors_core)
158 | return mz_kolors_core.MZ_KolorsCheckpointLoaderSimple_call(kwargs)
159 |
160 |
161 | NODE_CLASS_MAPPINGS["MZ_KolorsCheckpointLoaderSimple"] = MZ_KolorsCheckpointLoaderSimple
162 | NODE_DISPLAY_NAME_MAPPINGS[
163 | "MZ_KolorsCheckpointLoaderSimple"] = f"{AUTHOR_NAME} - KolorsCheckpointLoaderSimple"
164 |
165 |
166 | class MZ_KolorsControlNetLoader:
167 | @classmethod
168 | def INPUT_TYPES(s):
169 | return {"required": {
170 | "control_net_name": (folder_paths.get_filename_list("controlnet"), ),
171 | # "seed": ("INT", {"default": 0, "min": 0, "max": 1000000}),
172 | }}
173 |
174 | RETURN_TYPES = ("CONTROL_NET",)
175 | RETURN_NAMES = ("ControlNet",)
176 | FUNCTION = "load_controlnet"
177 |
178 | CATEGORY = CATEGORY_NAME
179 |
180 | def load_controlnet(self, **kwargs):
181 | from . import mz_kolors_core
182 | importlib.reload(mz_kolors_core)
183 | return mz_kolors_core.MZ_KolorsControlNetLoader_call(kwargs)
184 |
185 |
186 | NODE_CLASS_MAPPINGS["MZ_KolorsControlNetLoader"] = MZ_KolorsControlNetLoader
187 | NODE_DISPLAY_NAME_MAPPINGS[
188 | "MZ_KolorsControlNetLoader"] = f"{AUTHOR_NAME} - KolorsControlNetLoader"
189 |
190 |
191 | class MZ_KolorsUNETLoaderV2():
192 | @classmethod
193 | def INPUT_TYPES(s):
194 | return {"required": {
195 | "unet_name": (folder_paths.get_filename_list("unet"), ),
196 | }}
197 |
198 | RETURN_TYPES = ("MODEL",)
199 |
200 | RETURN_NAMES = ("model",)
201 |
202 | FUNCTION = "load_unet"
203 |
204 | CATEGORY = CATEGORY_NAME
205 |
206 | def load_unet(self, **kwargs):
207 | from . import mz_kolors_core
208 | importlib.reload(mz_kolors_core)
209 | return mz_kolors_core.MZ_KolorsUNETLoaderV2_call(kwargs)
210 |
211 |
212 | NODE_CLASS_MAPPINGS["MZ_KolorsUNETLoaderV2"] = MZ_KolorsUNETLoaderV2
213 | NODE_DISPLAY_NAME_MAPPINGS[
214 | "MZ_KolorsUNETLoaderV2"] = f"{AUTHOR_NAME} - KolorsUNETLoaderV2"
215 |
216 |
217 | class MZ_KolorsControlNetPatch:
218 | @classmethod
219 | def INPUT_TYPES(s):
220 | return {
221 | "required": {
222 | "control_net": ("CONTROL_NET", ),
223 | "model": ("MODEL", ),
224 | }
225 | }
226 |
227 | RETURN_TYPES = ("CONTROL_NET",)
228 |
229 | FUNCTION = "start"
230 | CATEGORY = CATEGORY_NAME
231 |
232 | def start(self, **kwargs):
233 | from . import mz_kolors_core
234 | importlib.reload(mz_kolors_core)
235 | return mz_kolors_core.MZ_KolorsControlNetPatch_call(kwargs)
236 |
237 |
238 | NODE_CLASS_MAPPINGS["MZ_KolorsControlNetPatch"] = MZ_KolorsControlNetPatch
239 | NODE_DISPLAY_NAME_MAPPINGS[
240 | "MZ_KolorsControlNetPatch"] = f"{AUTHOR_NAME} - KolorsControlNetPatch"
241 |
242 |
243 | class MZ_KolorsCLIPVisionLoader:
244 | @classmethod
245 | def INPUT_TYPES(s):
246 | return {"required": {"clip_name": (folder_paths.get_filename_list("clip_vision"), ),
247 | }}
248 | RETURN_TYPES = ("CLIP_VISION",)
249 | FUNCTION = "load_clip"
250 |
251 | CATEGORY = CATEGORY_NAME + "/Legacy"
252 |
253 | def load_clip(self, **kwargs):
254 | from . import mz_kolors_core
255 | importlib.reload(mz_kolors_core)
256 | return mz_kolors_core.MZ_KolorsCLIPVisionLoader_call(kwargs)
257 |
258 |
259 | NODE_CLASS_MAPPINGS["MZ_KolorsCLIPVisionLoader"] = MZ_KolorsCLIPVisionLoader
260 | NODE_DISPLAY_NAME_MAPPINGS["MZ_KolorsCLIPVisionLoader"] = f"{AUTHOR_NAME} - KolorsCLIPVisionLoader - Legacy"
261 |
262 |
263 | class MZ_ApplySDXLSamplingSettings():
264 | @classmethod
265 | def INPUT_TYPES(s):
266 | return {
267 | "required": {
268 | "model": ("MODEL", ),
269 | }
270 | }
271 |
272 | RETURN_TYPES = ("MODEL", )
273 |
274 | FUNCTION = "apply_sampling_settings"
275 | CATEGORY = CATEGORY_NAME
276 |
277 | def apply_sampling_settings(self, **kwargs):
278 | from . import mz_kolors_core
279 | importlib.reload(mz_kolors_core)
280 | return mz_kolors_core.MZ_ApplySDXLSamplingSettings_call(kwargs)
281 |
282 |
283 | NODE_CLASS_MAPPINGS["MZ_ApplySDXLSamplingSettings"] = MZ_ApplySDXLSamplingSettings
284 | NODE_DISPLAY_NAME_MAPPINGS[
285 | "MZ_ApplySDXLSamplingSettings"] = f"{AUTHOR_NAME} - ApplySDXLSamplingSettings"
286 |
287 |
288 | class MZ_ApplyCUDAGenerator():
289 | @classmethod
290 | def INPUT_TYPES(s):
291 | return {
292 | "required": {
293 | "model": ("MODEL", ),
294 | }
295 | }
296 |
297 | RETURN_TYPES = ("MODEL", )
298 |
299 | FUNCTION = "apply_cuda_generator"
300 | CATEGORY = CATEGORY_NAME
301 |
302 | def apply_cuda_generator(self, **kwargs):
303 | from . import mz_kolors_core
304 | importlib.reload(mz_kolors_core)
305 | return mz_kolors_core.MZ_ApplyCUDAGenerator_call(kwargs)
306 |
307 |
308 | NODE_CLASS_MAPPINGS["MZ_ApplyCUDAGenerator"] = MZ_ApplyCUDAGenerator
309 | NODE_DISPLAY_NAME_MAPPINGS[
310 | "MZ_ApplyCUDAGenerator"] = f"{AUTHOR_NAME} - ApplyCUDAGenerator"
311 |
312 |
313 | from .ComfyUI_IPAdapter_plus.IPAdapterPlus import IPAdapterAdvanced, IPAdapterModelLoader, IPAdapterInsightFaceLoader, IPAdapterFaceID
314 |
315 | IPAdapterModelLoader.CATEGORY = CATEGORY_NAME + "/IPAdapter"
316 | NODE_CLASS_MAPPINGS["MZ_IPAdapterModelLoaderKolors"] = IPAdapterModelLoader
317 | NODE_DISPLAY_NAME_MAPPINGS[
318 | "MZ_IPAdapterModelLoaderKolors"] = f"IPAdapterModelLoader(kolors) - Legacy"
319 |
320 | IPAdapterAdvanced.CATEGORY = CATEGORY_NAME + "/IPAdapter"
321 | NODE_CLASS_MAPPINGS["MZ_IPAdapterAdvancedKolors"] = IPAdapterAdvanced
322 | NODE_DISPLAY_NAME_MAPPINGS[
323 | "MZ_IPAdapterAdvancedKolors"] = f"IPAdapterAdvanced(kolors) - Legacy"
324 |
325 | IPAdapterInsightFaceLoader.CATEGORY = CATEGORY_NAME + "/IPAdapter"
326 | NODE_CLASS_MAPPINGS["MZ_IPAdapterInsightFaceLoader"] = IPAdapterInsightFaceLoader
327 |
328 | NODE_DISPLAY_NAME_MAPPINGS[
329 | "MZ_IPAdapterInsightFaceLoader"] = f"IPAdapterInsightFaceLoader(kolors) - Legacy"
330 |
331 | IPAdapterFaceID.CATEGORY = CATEGORY_NAME + "/IPAdapter"
332 | NODE_CLASS_MAPPINGS["MZ_IPAdapterFaceID"] = IPAdapterFaceID
333 |
334 | NODE_DISPLAY_NAME_MAPPINGS[
335 | "MZ_IPAdapterFaceID"] = f"IPAdapterFaceID(kolors) - Legacy"
336 |
337 | from . import mz_kolors_legacy
338 | NODE_CLASS_MAPPINGS.update(mz_kolors_legacy.NODE_CLASS_MAPPINGS)
339 | NODE_DISPLAY_NAME_MAPPINGS.update(mz_kolors_legacy.NODE_DISPLAY_NAME_MAPPINGS)
340 |
--------------------------------------------------------------------------------
/chatglm3/tokenization_chatglm.py:
--------------------------------------------------------------------------------
1 | import json
2 | import os
3 | import re
4 | from typing import List, Optional, Union, Dict
5 | from sentencepiece import SentencePieceProcessor
6 | from transformers import PreTrainedTokenizer
7 | from transformers.utils import logging, PaddingStrategy
8 | from transformers.tokenization_utils_base import EncodedInput, BatchEncoding
9 |
10 |
11 | class SPTokenizer:
12 | def __init__(self, model_path: str):
13 | # reload tokenizer
14 | assert os.path.isfile(model_path), model_path
15 | self.sp_model = SentencePieceProcessor(model_file=model_path)
16 |
17 | # BOS / EOS token IDs
18 | self.n_words: int = self.sp_model.vocab_size()
19 | self.bos_id: int = self.sp_model.bos_id()
20 | self.eos_id: int = self.sp_model.eos_id()
21 | self.pad_id: int = self.sp_model.unk_id()
22 | assert self.sp_model.vocab_size() == self.sp_model.get_piece_size()
23 |
24 | role_special_tokens = ["<|system|>", "<|user|>",
25 | "<|assistant|>", "<|observation|>"]
26 | special_tokens = ["[MASK]", "[gMASK]", "[sMASK]",
27 | "sop", "eop"] + role_special_tokens
28 | self.special_tokens = {}
29 | self.index_special_tokens = {}
30 | for token in special_tokens:
31 | self.special_tokens[token] = self.n_words
32 | self.index_special_tokens[self.n_words] = token
33 | self.n_words += 1
34 | self.role_special_token_expression = "|".join(
35 | [re.escape(token) for token in role_special_tokens])
36 |
37 | def tokenize(self, s: str, encode_special_tokens=False):
38 | if encode_special_tokens:
39 | last_index = 0
40 | t = []
41 | for match in re.finditer(self.role_special_token_expression, s):
42 | if last_index < match.start():
43 | t.extend(self.sp_model.EncodeAsPieces(
44 | s[last_index:match.start()]))
45 | t.append(s[match.start():match.end()])
46 | last_index = match.end()
47 | if last_index < len(s):
48 | t.extend(self.sp_model.EncodeAsPieces(s[last_index:]))
49 | return t
50 | else:
51 | return self.sp_model.EncodeAsPieces(s)
52 |
53 | def encode(self, s: str, bos: bool = False, eos: bool = False) -> List[int]:
54 | assert type(s) is str
55 | t = self.sp_model.encode(s)
56 | if bos:
57 | t = [self.bos_id] + t
58 | if eos:
59 | t = t + [self.eos_id]
60 | return t
61 |
62 | def decode(self, t: List[int]) -> str:
63 | text, buffer = "", []
64 | for token in t:
65 | if token in self.index_special_tokens:
66 | if buffer:
67 | text += self.sp_model.decode(buffer)
68 | buffer = []
69 | text += self.index_special_tokens[token]
70 | else:
71 | buffer.append(token)
72 | if buffer:
73 | text += self.sp_model.decode(buffer)
74 | return text
75 |
76 | def decode_tokens(self, tokens: List[str]) -> str:
77 | text = self.sp_model.DecodePieces(tokens)
78 | return text
79 |
80 | def convert_token_to_id(self, token):
81 | """ Converts a token (str) in an id using the vocab. """
82 | if token in self.special_tokens:
83 | return self.special_tokens[token]
84 | return self.sp_model.PieceToId(token)
85 |
86 | def convert_id_to_token(self, index):
87 | """Converts an index (integer) in a token (str) using the vocab."""
88 | if index in self.index_special_tokens:
89 | return self.index_special_tokens[index]
90 | if index in [self.eos_id, self.bos_id, self.pad_id] or index < 0:
91 | return ""
92 | return self.sp_model.IdToPiece(index)
93 |
94 |
95 | class ChatGLMTokenizer(PreTrainedTokenizer):
96 | vocab_files_names = {"vocab_file": "tokenizer.model"}
97 |
98 | model_input_names = ["input_ids", "attention_mask", "position_ids"]
99 |
100 | def __init__(self, vocab_file, padding_side="left", clean_up_tokenization_spaces=False, encode_special_tokens=False,
101 | **kwargs):
102 | self.name = "GLMTokenizer"
103 |
104 | self.vocab_file = vocab_file
105 | self.tokenizer = SPTokenizer(vocab_file)
106 | self.special_tokens = {
107 | "": self.tokenizer.bos_id,
108 | "": self.tokenizer.eos_id,
109 | "": self.tokenizer.pad_id
110 | }
111 | self.encode_special_tokens = encode_special_tokens
112 | super().__init__(padding_side=padding_side, clean_up_tokenization_spaces=clean_up_tokenization_spaces,
113 | encode_special_tokens=encode_special_tokens,
114 | **kwargs)
115 |
116 | def get_command(self, token):
117 | if token in self.special_tokens:
118 | return self.special_tokens[token]
119 | assert token in self.tokenizer.special_tokens, f"{token} is not a special token for {self.name}"
120 | return self.tokenizer.special_tokens[token]
121 |
122 | @property
123 | def unk_token(self) -> str:
124 | return ""
125 |
126 | @property
127 | def pad_token(self) -> str:
128 | return ""
129 |
130 | @property
131 | def pad_token_id(self):
132 | return self.get_command("")
133 |
134 | @property
135 | def eos_token(self) -> str:
136 | return ""
137 |
138 | @property
139 | def eos_token_id(self):
140 | return self.get_command("")
141 |
142 | @property
143 | def vocab_size(self):
144 | return self.tokenizer.n_words
145 |
146 | def get_vocab(self):
147 | """ Returns vocab as a dict """
148 | vocab = {self._convert_id_to_token(
149 | i): i for i in range(self.vocab_size)}
150 | vocab.update(self.added_tokens_encoder)
151 | return vocab
152 |
153 | def _tokenize(self, text, **kwargs):
154 | return self.tokenizer.tokenize(text, encode_special_tokens=self.encode_special_tokens)
155 |
156 | def _convert_token_to_id(self, token):
157 | """ Converts a token (str) in an id using the vocab. """
158 | return self.tokenizer.convert_token_to_id(token)
159 |
160 | def _convert_id_to_token(self, index):
161 | """Converts an index (integer) in a token (str) using the vocab."""
162 | return self.tokenizer.convert_id_to_token(index)
163 |
164 | def convert_tokens_to_string(self, tokens: List[str]) -> str:
165 | return self.tokenizer.decode_tokens(tokens)
166 |
167 | def save_vocabulary(self, save_directory, filename_prefix=None):
168 | """
169 | Save the vocabulary and special tokens file to a directory.
170 |
171 | Args:
172 | save_directory (`str`):
173 | The directory in which to save the vocabulary.
174 | filename_prefix (`str`, *optional*):
175 | An optional prefix to add to the named of the saved files.
176 |
177 | Returns:
178 | `Tuple(str)`: Paths to the files saved.
179 | """
180 | if os.path.isdir(save_directory):
181 | vocab_file = os.path.join(
182 | save_directory, self.vocab_files_names["vocab_file"]
183 | )
184 | else:
185 | vocab_file = save_directory
186 |
187 | with open(self.vocab_file, 'rb') as fin:
188 | proto_str = fin.read()
189 |
190 | with open(vocab_file, "wb") as writer:
191 | writer.write(proto_str)
192 |
193 | return (vocab_file,)
194 |
195 | def get_prefix_tokens(self):
196 | prefix_tokens = [self.get_command("[gMASK]"), self.get_command("sop")]
197 | return prefix_tokens
198 |
199 | def build_single_message(self, role, metadata, message):
200 | assert role in ["system", "user", "assistant", "observation"], role
201 | role_tokens = [self.get_command(
202 | f"<|{role}|>")] + self.tokenizer.encode(f"{metadata}\n")
203 | message_tokens = self.tokenizer.encode(message)
204 | tokens = role_tokens + message_tokens
205 | return tokens
206 |
207 | def build_chat_input(self, query, history=None, role="user"):
208 | if history is None:
209 | history = []
210 | input_ids = []
211 | for item in history:
212 | content = item["content"]
213 | if item["role"] == "system" and "tools" in item:
214 | content = content + "\n" + \
215 | json.dumps(item["tools"], indent=4, ensure_ascii=False)
216 | input_ids.extend(self.build_single_message(
217 | item["role"], item.get("metadata", ""), content))
218 | input_ids.extend(self.build_single_message(role, "", query))
219 | input_ids.extend([self.get_command("<|assistant|>")])
220 | return self.batch_encode_plus([input_ids], return_tensors="pt", is_split_into_words=True)
221 |
222 | def build_inputs_with_special_tokens(
223 | self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
224 | ) -> List[int]:
225 | """
226 | Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
227 | adding special tokens. A BERT sequence has the following format:
228 |
229 | - single sequence: `[CLS] X [SEP]`
230 | - pair of sequences: `[CLS] A [SEP] B [SEP]`
231 |
232 | Args:
233 | token_ids_0 (`List[int]`):
234 | List of IDs to which the special tokens will be added.
235 | token_ids_1 (`List[int]`, *optional*):
236 | Optional second list of IDs for sequence pairs.
237 |
238 | Returns:
239 | `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
240 | """
241 | prefix_tokens = self.get_prefix_tokens()
242 | token_ids_0 = prefix_tokens + token_ids_0
243 | if token_ids_1 is not None:
244 | token_ids_0 = token_ids_0 + token_ids_1 + \
245 | [self.get_command("")]
246 | return token_ids_0
247 |
248 | def _pad(
249 | self,
250 | encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
251 | max_length: Optional[int] = None,
252 | padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
253 | pad_to_multiple_of: Optional[int] = None,
254 | return_attention_mask: Optional[bool] = None,
255 | **kwargs,
256 | ) -> dict:
257 | """
258 | Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
259 |
260 | Args:
261 | encoded_inputs:
262 | Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
263 | max_length: maximum length of the returned list and optionally padding length (see below).
264 | Will truncate by taking into account the special tokens.
265 | padding_strategy: PaddingStrategy to use for padding.
266 |
267 | - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
268 | - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
269 | - PaddingStrategy.DO_NOT_PAD: Do not pad
270 | The tokenizer padding sides are defined in self.padding_side:
271 |
272 | - 'left': pads on the left of the sequences
273 | - 'right': pads on the right of the sequences
274 | pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
275 | This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
276 | `>= 7.5` (Volta).
277 | return_attention_mask:
278 | (optional) Set to False to avoid returning attention mask (default: set to model specifics)
279 | """
280 | # Load from model defaults
281 | assert self.padding_side == "left"
282 |
283 | required_input = encoded_inputs[self.model_input_names[0]]
284 | seq_length = len(required_input)
285 |
286 | if padding_strategy == PaddingStrategy.LONGEST:
287 | max_length = len(required_input)
288 |
289 | if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
290 | max_length = ((max_length // pad_to_multiple_of) +
291 | 1) * pad_to_multiple_of
292 |
293 | needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(
294 | required_input) != max_length
295 |
296 | # Initialize attention mask if not present.
297 | if "attention_mask" not in encoded_inputs:
298 | encoded_inputs["attention_mask"] = [1] * seq_length
299 |
300 | if "position_ids" not in encoded_inputs:
301 | encoded_inputs["position_ids"] = list(range(seq_length))
302 |
303 | if needs_to_be_padded:
304 | difference = max_length - len(required_input)
305 |
306 | if "attention_mask" in encoded_inputs:
307 | encoded_inputs["attention_mask"] = [0] * \
308 | difference + encoded_inputs["attention_mask"]
309 | if "position_ids" in encoded_inputs:
310 | encoded_inputs["position_ids"] = [0] * \
311 | difference + encoded_inputs["position_ids"]
312 | encoded_inputs[self.model_input_names[0]] = [
313 | self.pad_token_id] * difference + required_input
314 |
315 | return encoded_inputs
316 |
--------------------------------------------------------------------------------
/mz_kolors_core.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | import gc
4 | import json
5 | import os
6 | import random
7 | import re
8 | import subprocess
9 | import sys
10 | from types import MethodType
11 |
12 | import torch
13 | import folder_paths
14 | import comfy.model_management as mm
15 |
16 |
17 | def chatglm3_text_encode(chatglm3_model, prompt):
18 | device = mm.get_torch_device()
19 | offload_device = mm.unet_offload_device()
20 | mm.unload_all_models()
21 | mm.soft_empty_cache()
22 | # Function to randomly select an option from the brackets
23 |
24 | def choose_random_option(match):
25 | options = match.group(1).split('|')
26 | return random.choice(options)
27 |
28 | prompt = re.sub(r'\{([^{}]*)\}', choose_random_option, prompt)
29 |
30 | # Define tokenizers and text encoders
31 | tokenizer = chatglm3_model['tokenizer']
32 | text_encoder = chatglm3_model['text_encoder']
33 | text_encoder.to(device)
34 | text_inputs = tokenizer(
35 | prompt,
36 | padding="max_length",
37 | max_length=256,
38 | truncation=True,
39 | return_tensors="pt",
40 | ).to(device)
41 |
42 | output = text_encoder(
43 | input_ids=text_inputs['input_ids'],
44 | attention_mask=text_inputs['attention_mask'],
45 | position_ids=text_inputs['position_ids'],
46 | output_hidden_states=True)
47 |
48 | # [batch_size, 77, 4096]
49 | prompt_embeds = output.hidden_states[-2].permute(1, 0, 2).clone()
50 | text_proj = output.hidden_states[-1][-1,
51 | :, :].clone() # [batch_size, 4096]
52 | bs_embed, seq_len, _ = prompt_embeds.shape
53 | prompt_embeds = prompt_embeds.repeat(1, 1, 1)
54 | prompt_embeds = prompt_embeds.view(
55 | bs_embed, seq_len, -1)
56 |
57 | bs_embed = text_proj.shape[0]
58 | text_proj = text_proj.repeat(1, 1).view(
59 | bs_embed, -1
60 | )
61 | text_encoder.to(offload_device)
62 | mm.soft_empty_cache()
63 | gc.collect()
64 | return prompt_embeds, text_proj
65 |
66 |
67 | def MZ_ChatGLM3Loader_call(args):
68 | # from .mz_kolors_utils import Utils
69 | # llm_dir = os.path.join(Utils.get_models_path(), "LLM")
70 | chatglm3_checkpoint = args.get("chatglm3_checkpoint")
71 |
72 | chatglm3_checkpoint_path = folder_paths.get_full_path(
73 | 'LLM', chatglm3_checkpoint)
74 |
75 | if not os.path.exists(chatglm3_checkpoint_path):
76 | raise RuntimeError(
77 | f"ERROR: Could not find chatglm3 checkpoint: {chatglm3_checkpoint_path}")
78 |
79 | from .chatglm3.configuration_chatglm import ChatGLMConfig
80 | from .chatglm3.modeling_chatglm import ChatGLMModel
81 | from .chatglm3.tokenization_chatglm import ChatGLMTokenizer
82 |
83 | offload_device = mm.unet_offload_device()
84 |
85 | text_encoder_config = os.path.join(
86 | os.path.dirname(__file__), 'configs', 'text_encoder_config.json')
87 | with open(text_encoder_config, 'r') as file:
88 | config = json.load(file)
89 |
90 | text_encoder_config = ChatGLMConfig(**config)
91 |
92 | from comfy.utils import load_torch_file
93 | from contextlib import nullcontext
94 | is_accelerate_available = False
95 | try:
96 | from accelerate import init_empty_weights
97 | from accelerate.utils import set_module_tensor_to_device
98 | is_accelerate_available = True
99 | except:
100 | pass
101 |
102 | with (init_empty_weights() if is_accelerate_available else nullcontext()):
103 | with torch.no_grad():
104 | # 打印版本号
105 | print("torch version:", torch.__version__)
106 | text_encoder = ChatGLMModel(text_encoder_config).eval()
107 | if '4bit' in chatglm3_checkpoint:
108 | try:
109 | import cpm_kernels
110 | except ImportError:
111 | print("Installing cpm_kernels...")
112 | subprocess.run(
113 | [sys.executable, "-m", "pip", "install", "cpm_kernels"], check=True)
114 | pass
115 | text_encoder.quantize(4)
116 | elif '8bit' in chatglm3_checkpoint:
117 | text_encoder.quantize(8)
118 | text_encoder_sd = load_torch_file(chatglm3_checkpoint_path)
119 | if is_accelerate_available:
120 | for key in text_encoder_sd:
121 | set_module_tensor_to_device(
122 | text_encoder, key, device=offload_device, value=text_encoder_sd[key])
123 | else:
124 | print("WARNING: Accelerate not available, use load_state_dict load model")
125 | text_encoder.load_state_dict(text_encoder_sd)
126 |
127 | tokenizer_path = os.path.join(
128 | os.path.dirname(__file__), 'configs', "tokenizer")
129 | tokenizer = ChatGLMTokenizer.from_pretrained(tokenizer_path)
130 |
131 | return ({"text_encoder": text_encoder, "tokenizer": tokenizer},)
132 |
133 |
134 | def MZ_ChatGLM3TextEncodeV2_call(args):
135 | text = args.get("text")
136 | chatglm3_model = args.get("chatglm3_model")
137 | prompt_embeds, pooled_output = chatglm3_text_encode(
138 | chatglm3_model,
139 | text,
140 | )
141 | extra_kwargs = {
142 | "pooled_output": pooled_output,
143 | }
144 | extra_cond_keys = [
145 | "width",
146 | "height",
147 | "crop_w",
148 | "crop_h",
149 | "target_width",
150 | "target_height"
151 | ]
152 | for key, value in args.items():
153 | if key in extra_cond_keys:
154 | extra_kwargs[key] = value
155 | return ([[
156 | prompt_embeds,
157 | # {"pooled_output": pooled_output},
158 | extra_kwargs
159 | ]], )
160 |
161 |
162 | def MZ_ChatGLM3Embeds2Conditioning_call(args):
163 | kolors_embeds = args.get("kolors_embeds")
164 |
165 | # kolors_embeds = {
166 | # 'prompt_embeds': prompt_embeds,
167 | # 'negative_prompt_embeds': negative_prompt_embeds,
168 | # 'pooled_prompt_embeds': text_proj,
169 | # 'negative_pooled_prompt_embeds': negative_text_proj
170 | # }
171 |
172 | positive = [[
173 | kolors_embeds['prompt_embeds'],
174 | {
175 | "pooled_output": kolors_embeds['pooled_prompt_embeds'],
176 | "width": args.get("width"),
177 | "height": args.get("height"),
178 | "crop_w": args.get("crop_w"),
179 | "crop_h": args.get("crop_h"),
180 | "target_width": args.get("target_width"),
181 | "target_height": args.get("target_height")
182 | }
183 | ]]
184 |
185 | negative = [[
186 | kolors_embeds['negative_prompt_embeds'],
187 | {
188 | "pooled_output": kolors_embeds['negative_pooled_prompt_embeds'],
189 | }
190 | ]]
191 |
192 | return (positive, negative)
193 |
194 |
195 | def MZ_KolorsUNETLoaderV2_call(kwargs):
196 |
197 | from . import hook_comfyui_kolors_v2
198 | import comfy.sd
199 |
200 | with hook_comfyui_kolors_v2.apply_kolors():
201 | unet_name = kwargs.get("unet_name")
202 | unet_path = folder_paths.get_full_path("unet", unet_name)
203 | import comfy.utils
204 | sd = comfy.utils.load_torch_file(unet_path)
205 | model = comfy.sd.load_unet_state_dict(sd)
206 | if model is None:
207 | raise RuntimeError(
208 | "ERROR: Could not detect model type of: {}".format(unet_path))
209 |
210 | return (model, )
211 |
212 |
213 | def MZ_KolorsCheckpointLoaderSimple_call(kwargs):
214 | checkpoint_name = kwargs.get("ckpt_name")
215 |
216 | ckpt_path = folder_paths.get_full_path("checkpoints", checkpoint_name)
217 |
218 | from . import hook_comfyui_kolors_v2
219 | import comfy.sd
220 |
221 | with hook_comfyui_kolors_v2.apply_kolors():
222 | out = comfy.sd.load_checkpoint_guess_config(
223 | ckpt_path, output_vae=True, output_clip=False, embedding_directory=folder_paths.get_folder_paths("embeddings"))
224 |
225 | unet, _, vae = out[:3]
226 | return (unet, vae)
227 |
228 |
229 | from comfy.cldm.cldm import ControlNet
230 | from comfy.controlnet import ControlLora
231 |
232 |
233 | def MZ_KolorsControlNetLoader_call(kwargs):
234 | control_net_name = kwargs.get("control_net_name")
235 | controlnet_path = folder_paths.get_full_path(
236 | "controlnet", control_net_name)
237 |
238 | from torch import nn
239 | from . import hook_comfyui_kolors_v2
240 | import comfy.controlnet
241 |
242 | with hook_comfyui_kolors_v2.apply_kolors():
243 | control_net = comfy.controlnet.load_controlnet(controlnet_path)
244 | return (control_net, )
245 |
246 |
247 | def MZ_KolorsControlNetPatch_call(kwargs):
248 | import copy
249 | from . import hook_comfyui_kolors_v2
250 | import comfy.model_management
251 | import comfy.model_patcher
252 |
253 | model = kwargs.get("model")
254 | control_net = kwargs.get("control_net")
255 |
256 | if hasattr(control_net, "control_model") and hasattr(control_net.control_model, "encoder_hid_proj"):
257 | return (control_net,)
258 |
259 | control_net = copy.deepcopy(control_net)
260 |
261 | import comfy.controlnet
262 | if isinstance(control_net, ControlLora):
263 | del_keys = []
264 | for k in control_net.control_weights:
265 | if k.startswith("label_emb.0.0."):
266 | del_keys.append(k)
267 |
268 | for k in del_keys:
269 | control_net.control_weights.pop(k)
270 |
271 | super_pre_run = ControlLora.pre_run
272 | super_forward = ControlNet.forward
273 |
274 | def KolorsControlNet_forward(self, x, hint, timesteps, context, **kwargs):
275 | with torch.cuda.amp.autocast(enabled=True):
276 | context = self.encoder_hid_proj(context)
277 | return super_forward(self, x, hint, timesteps, context, **kwargs)
278 |
279 | def KolorsControlLora_pre_run(self, *args, **kwargs):
280 | result = super_pre_run(self, *args, **kwargs)
281 |
282 | if hasattr(self, "control_model"):
283 | if hasattr(self.control_model, "encoder_hid_proj"):
284 | return result
285 |
286 | setattr(self.control_model, "encoder_hid_proj",
287 | model.model.diffusion_model.encoder_hid_proj)
288 |
289 | self.control_model.forward = MethodType(
290 | KolorsControlNet_forward, self.control_model)
291 |
292 | return result
293 |
294 | control_net.pre_run = MethodType(
295 | KolorsControlLora_pre_run, control_net)
296 |
297 | super_copy = ControlLora.copy
298 |
299 | def KolorsControlLora_copy(self, *args, **kwargs):
300 | c = super_copy(self, *args, **kwargs)
301 | c.pre_run = MethodType(
302 | KolorsControlLora_pre_run, c)
303 | return c
304 |
305 | control_net.copy = MethodType(
306 | KolorsControlLora_copy, control_net)
307 |
308 | control_net = copy.deepcopy(control_net)
309 |
310 | elif isinstance(control_net, comfy.controlnet.ControlNet):
311 | model_label_emb = model.model.diffusion_model.label_emb
312 |
313 | control_net.control_model.label_emb = model_label_emb
314 | setattr(control_net.control_model, "encoder_hid_proj",
315 | model.model.diffusion_model.encoder_hid_proj)
316 |
317 | control_net.control_model_wrapped = comfy.model_patcher.ModelPatcher(
318 | control_net.control_model, load_device=control_net.load_device, offload_device=comfy.model_management.unet_offload_device())
319 |
320 | super_forward = ControlNet.forward
321 |
322 | def KolorsControlNet_forward(self, x, hint, timesteps, context, **kwargs):
323 | with torch.cuda.amp.autocast(enabled=True):
324 | context = self.encoder_hid_proj(context)
325 | return super_forward(self, x, hint, timesteps, context, **kwargs)
326 |
327 | control_net.control_model.forward = MethodType(
328 | KolorsControlNet_forward, control_net.control_model)
329 |
330 | else:
331 | raise NotImplementedError(
332 | f"Type {control_net} not supported for KolorsControlNetPatch")
333 |
334 | return (control_net,)
335 |
336 |
337 | def MZ_KolorsCLIPVisionLoader_call(kwargs):
338 | import comfy.clip_vision
339 | from . import hook_comfyui_kolors_v2
340 | clip_name = kwargs.get("clip_name")
341 | clip_path = folder_paths.get_full_path("clip_vision", clip_name)
342 | with hook_comfyui_kolors_v2.apply_kolors():
343 | clip_vision = comfy.clip_vision.load(clip_path)
344 | return (clip_vision,)
345 |
346 |
347 | def MZ_ApplySDXLSamplingSettings_call(kwargs):
348 | model = kwargs.get("model").clone()
349 |
350 | import comfy.model_sampling
351 | sampling_base = comfy.model_sampling.ModelSamplingDiscrete
352 | sampling_type = comfy.model_sampling.EPS
353 |
354 | class SDXLSampling(sampling_base, sampling_type):
355 | pass
356 |
357 | model.model.model_config.sampling_settings["beta_schedule"] = "linear"
358 | model.model.model_config.sampling_settings["linear_start"] = 0.00085
359 | model.model.model_config.sampling_settings["linear_end"] = 0.012
360 | model.model.model_config.sampling_settings["timesteps"] = 1000
361 |
362 | model_sampling = SDXLSampling(model.model.model_config)
363 |
364 | model.add_object_patch("model_sampling", model_sampling)
365 |
366 | return (model,)
367 |
368 |
369 | def MZ_ApplyCUDAGenerator_call(kwargs):
370 | model = kwargs.get("model")
371 |
372 | def prepare_noise(latent_image, seed, noise_inds=None):
373 | """
374 | creates random noise given a latent image and a seed.
375 | optional arg skip can be used to skip and discard x number of noise generations for a given seed
376 | """
377 | generator = torch.Generator(device="cuda").manual_seed(seed)
378 | if noise_inds is None:
379 | return torch.randn(latent_image.size(), dtype=latent_image.dtype, layout=latent_image.layout, generator=generator, device="cuda")
380 |
381 | unique_inds, inverse = np.unique(noise_inds, return_inverse=True)
382 | noises = []
383 | for i in range(unique_inds[-1] + 1):
384 | noise = torch.randn([1] + list(latent_image.size())[1:], dtype=latent_image.dtype,
385 | layout=latent_image.layout, generator=generator, device="cuda")
386 | if i in unique_inds:
387 | noises.append(noise)
388 | noises = [noises[i] for i in inverse]
389 | noises = torch.cat(noises, axis=0)
390 | return noises
391 |
392 | import comfy.sample
393 | comfy.sample.prepare_noise = prepare_noise
394 | return (model,)
395 |
--------------------------------------------------------------------------------
/chatglm3/quantization.py:
--------------------------------------------------------------------------------
1 | from torch.nn import Linear
2 | from torch.nn.parameter import Parameter
3 |
4 | import bz2
5 | import torch
6 | import base64
7 | import ctypes
8 | from transformers.utils import logging
9 |
10 | from typing import List
11 | from functools import partial
12 |
13 | logger = logging.get_logger(__name__)
14 |
15 | try:
16 | from cpm_kernels.kernels.base import LazyKernelCModule, KernelFunction, round_up
17 |
18 | import cpm_kernels.library.base
19 |
20 | original_windows_find_lib = cpm_kernels.library.base.windows_find_lib
21 |
22 | def windows_find_lib(name):
23 | result = original_windows_find_lib(name)
24 | if result is not None:
25 | return result
26 | import torch
27 | import os
28 | torch_dir = os.path.dirname(torch.__file__)
29 | torch_lib_dir = os.path.join(torch_dir, "lib")
30 |
31 | for name in os.listdir(torch_lib_dir):
32 | if name.startswith(name) and name.lower().endswith(".dll"):
33 | return os.path.join(torch_lib_dir, name)
34 |
35 | return None
36 | cpm_kernels.library.base.windows_find_lib = windows_find_lib
37 |
38 | class Kernel:
39 | def __init__(self, code: bytes, function_names: List[str]):
40 | self.code = code
41 | self._function_names = function_names
42 | self._cmodule = LazyKernelCModule(self.code)
43 |
44 | for name in self._function_names:
45 | setattr(self, name, KernelFunction(self._cmodule, name))
46 |
47 | quantization_code = "$QlpoOTFBWSZTWU9yuJUAQHN//////////f/n/8/n///n//bt4dTidcVx8X3V9FV/92/v4B7/AD5FBQFAAAChSgKpFCFAFVSigUAAAEKhSgUUqgFBKigqVREQAABQBQIANDTTIGI00BkZBkNGE0A0BkBkGQGRkaNAaAGQNBoGgDIAAYIGTI0DQAQAaGmmQMRpoDIyDIaMJoBoDIDIMgMjI0aA0AMgaDQNAGQAAwQMmRoGgAgA0NNMgYjTQGRkGQ0YTQDQGQGQZAZGRo0BoAZA0GgaAMgABggZMjQNABABoaaZAxGmgMjIMhowmgGgMgMgyAyMjRoDQAyBoNA0AZAADBAyZGgaAAmqU1NEgJqnptU/Sn4jRR6J6epk2pqb1Q/SgAPUGgyNNGjQ2SBpoAZAAGg0NB6mgDIAAAAA2oaApSREBNAARhGiYEaEwU8pvImlP0k2aam1GaGqbFNM1MHpTwmkepmyU9R6nqPKekHqNNPUxNGhp6n6p6QaZ6o9TG1GMqcoV9ly6nRanHlq6zPNbnGZNi6HSug+2nPiZ13XcnFYZW+45W11CumhzYhchOJ2GLLV1OBjBjGf4TptOddTSOcVxhqYZMYwZXZZY00zI1paX5X9J+b+f4e+x43RXSxXPOdquiGpduatGyXneN696M9t4HU2eR5XX/kPhP261NTx3JO1Ow7LyuDmeo9a7d351T1ZxnvnrvYnrXv/hXxPCeuYx2XsNmO003eg9J3Z6U7b23meJ4ri01OdzTk9BNO96brz+qT5nuvvH3ds/G+m/JcG/F2XYuhXlvO+jP7U3XgrzPN/lr8Sf1n6j4j7jZs+s/T0tNaNNYzTs12rxjwztHlnire3Nzc3N1wuBwOBwXBvZfoHpD7rFmR99V5vj3aXza3xdBbXMalubTg/jIv5dfAi54Pdc75j4z412n3Npj3Ld/ENm7a3b/Cod6h/ret1/5vn/C+l+gdslMvgPSLJ8d8q+U66fevYn/tW1chleEtNTGlcHCbLRlq0tHzF5tsbbZZfHjjLgZu42XCuC3NrdjTasZGNzgxPIrGqp7r3p7L2p5XjnpPSmTd5XtzqnB6U87zzg1Ol0zd0zsLszxR6lkxp35u6/teL0L0W922cR7Lu1lpL9CsHirzuM2T+BgsyViT6LHcm0/Vr6U/7LGGyJeqTEjt0PHWhF5mCT7R9mtlDwriYv0Tyr/OxYt6qp5r0mPVT0608TqnqMZaarU2nFwrTzzlrs1ed7z1ux60wyr4ydCaTi3enW8x68x0zU7tXSlcmPSW1mGpWJMg4zmPC2lK96tp0OE80y4MfEvnZj8zGluR6b22ki1Ou9V2nCd9xovcPvcYMZYy0lvN60ScZ45vN6yeCeeXFb1lVjnnCar5fwXwE2bzJ4HI1XVPXfXZMm44GUsMpYsmLB65TuVdm0cl0b+i/wGNN66XjeV7zuPpHcnK/juhhjdfId5jMdE5nN0dGmmm2zZs2cexD5n9p/dY352XsvXHaZNWWsmmS1atjR452nYudzvqv2HMRyvNNnlMcDl3R2+yx2uVrBubTW9icHDVtbNXlZm7jma1rM4VurZZd2y6nUau7ZXZ7bVU+mnoOVxZGMrVmvX60605JwmzGZhhhjTWtaaaMaaGTGmNMZasY0iX8VMUl8eepaIrzGSpemWOQyZORk2bNpjUybMmxqYmknCGCFynutfksaZpjTNMaaatM0xsxcGR0sociNqxNSmhhR1ZJPbsn8qyF0t2qH6iYBclclalbtTTcHTDsPaX6rlnElph2Jyumumtynv2Kk8GI7rsvXbIcJgHJOSaSXnnGaI3m87RtVXJOZ/YtgdTE6Wpha6ZlE8ayXkef1fh602r2WwvfMXtMdLlkfnLFdYYwYso+bWqm7yJqHXZGw2nrS5ZanSYnWlxBxMF1V940K2wdrI7R6OYf7DGGamMmTSbRhlS45xmVOumF1EyPCmHrrN8wwZOOrdNtLeMtzFzDlWnfTBxMk2NaXIZHBYxYLD4w8yju0ao65Vz1OIXoS9dLanwCe1PWrYuWMqf1if1z2k2yYfKJ741PDgno1ZQ8DRqvUny3mNoWTzGO6m1DkrJI8JiR5cSd+vZdGOO8nrMoc5+NDUFsMSXaZJeNlMmGLtJsovOsUp7I9S5VojKxF6bTVEelXqlfJobQr3LozSh2Jk7VcrVMfhXqszGWMzNqGhqZY0OadxkyyMssKugZR0KNFXBHlqwmJgTE/BNVMk6ItJXZMR0H47GpXv/DMOvNkmVuaV1PRfEdxuqc7Hcd+ZV/zTLaRxWk0nl9CdCeM6mn5rstHIBcpiuwmUZXeq81DacHI2rmrZ5SuE5mOZd6LQrZg9mx32TprA8BMo5jKN6yLTCi3WzQaZSuhzTtM1fUTGVpG8Tw+KXI0tjEpiWxtLYynOlktSbVlaI5kxP8TDH8kx50xoxi5KcA4pcja8KWLRlO/Ks6q06ergnvm1ca3Tq8Uw7LTUsmWyctXPWmpitl/uvGcWTGXGuAXDfhqazGmjkxcJW5hMMMMpYsXl2TZYtVOddG3XCarUt6Ptq9CZXSNzyuRzqRZOjsxdBbFVz6OA5HI43r1jityVlVpVkxmOsyaYWE1NTGq1sOVh36mHMcxtSvcy70edG0ZGR3I1Go1GRlV7mWWo1G0ZGRqlvH40l7o4m5xMWLLLYyNjnqc8556mdPqLJ31n/1nWOncxzG1tizrHs/Z+d2vP/B/l8wdJ6rHUn2nbbDq4p6htFtYzMMMTaZis1K5GKzGNmxhmUx2DDlZ/qNnIx41xnaMfCZWYaZWtNLTNW8ND4Fw1MyZOCdM428suKG1ehW8TesOydg7J+YYcD4cYR+8dFK6M4E3HM9ZfRNNL+Sn6rsl4DsrDl2HpPCnfxjGXtbZtYys1ttlyJ4T+BvexjGWRjMszK4Jpc77D3GyuVD7q0+G8m9G+2+rGm7cOR2y7FdtY2XUYx/oNlfRYxhMYyYZkyyg55enna9Kt/FFi6GMMwYwdwxWgxGMLKYmUyGExTKMZkMFhkymKuh0NOBNnBu+23LdwDoZYYzGGMxtORaTU1pjTGWTTGGtMrNWUsyyTTLLG1qy2ZjbK2DBllWqxMtBMaYZQmcE7zvvRcTkclUwdkxTaSdyySt/7fpL+T1v516Ji97fwr5JbLu305zMn5+GMTTZ9F+y7ExwmGVfG44yxn3dLv6l5i+Wth1jCrDq21nW9LqvvDzz3Vf3LLH/O/32TJ/erx3bXftO4eF+G956D952K/An4NfvOpjFjExjevP/UmE0fIoZXx6/w6lX/no3D0bLt+ixjieBM6ksRd0yB4Lt2SwYNE+gd1detlZWUnpiZfGfFaK+4PyCa/v18V8X75pe9fLXzp7l3VjF76vWZmHwGz1IZNWT7b8yddJ4q5kyrVdfru6atWc7bVYztL9Jf4GXvT+Y8m9/YsXP6H018a8D4XVOqvfzqeR+6yZOD8dPv0+U7/q5Pl+2dNb0MjzGVH5p6MNQ7cOWvw62U9aHE8DprDek+McLyvDz+te+9Zhq5+YTruufMcWMabqysTmZVWjKPfnK0wyVcrsuhjZRdLkHNvD72b9abriOSGIxiLixMOoalNPXzy+wT/tf+U6HHONfsz+xe8ufHBdQWWGWLA9if0rsnmrxK5LvRZQeWsTCsrmOYy8VteVfuRfcVTtDLItLIsMYxZLdU/DbtSemxF6Z6Zo5WBXE4tFdCyVMMXMTEMZXVlS6Xec2T4e0tHsRcEuWshcJ2YsNF5rUx1E8ifCq6Z+ZP7qdCeu/aTwFd53l16/o0NOw6O3dLavP4Hbi4RdmuDk6DoYaninC0+o4uZjbJ7Rxeu0/FbuFg+q7DVS6fQe0rZ6NDGUNNU6DEqOaLTicKnYZMnBWruljQxoaS3dZhocDge0bSTyOvdAbG5hxe2xji7E/L55xX13wWNDi6HCekcFxfCPGxY0MXC+s7afWaMdDyjyr+o8Rudm/NabOZvdl274zH4f5XK9z6On1Pe/K5TdPAslg77BjuO6Y3eO7GqvOPG/stknp1leyvLL0Z7bl9I4noMvLkzytLhWYzrOZzLXCORe028rORzOg4N/L0HlMOQ3Pgmnbb6KczlabORpu980q37TBqRu0/p3PO6234Bl03Ynuz+9W7gnsEcmvYaYY3aMYY0wx3pYd+ujsXauWdaY5Xkbtl23fPzFHiDB/QMo0yFjBllYxTQYYyxkrwn7JufwJ/PfgJ+C83X69ni6zvXcnyXabv0ncbLwsceS+RNlyN2mnneJtX0ngYO0+e+0+UnA+Wch3ji8hj5an4h+i6XBySU4n+R0roVcbw5yvHrmr4Yw8Y7x6c+9POPYHI5HI5HI5HI5HGXGww4nE4nrVyOR8XeqPEO7PLOiukYa3Novk5hV4cdtYZLI93e+uxff2jRo0aNGjRo0aNG1bVtW1dy3m83m8+tQ5ZzHw3nObwOu8La9Rc1dtkdS8A3eTk823tnktXWlxN6Oixe06zrN70Isd9jiOgZFq9yfkPqP/SLhN2Myl8jDM43bl1nbcb4cO57jlh8Jow6pzXZdL4dyODTuuhu77FyO27DdwdRxmvO+O+3N2+BdqyTwLHVczDVY4UPE4O66/ZO2cx1LFzVdSXtF7G4HMbrauOHRw6c8FdZ5m9fHZHYZXfTlZquyynSyTTKke6vcffSD9pzPA/G7n7jxPmuhc1DHMynPMrGL6AdewYmwu5ko+UUyTwrMv27rPH1v1nGqd87+p6N6LU8k3NEng53xXyHS97+44OSg/sy/hn+Se6yfYNjW0/uTgP+PvWYzLMmjhcLB/gGpri6H83/84eUXWT6T9Hsv7785z/7z4icpW+zfXypuR7rx/gMdZb1/wC678pcs8/2a3mDitGHxl9mfPlll5MafWWqxk/eYuTDgcNMzDGWLWvsuglNxs53GtN6uWpktlW1tZZYcuinMMWmnNnJydze3b2Y1McBxrBkXw799izLMZZYyy0TkbsGM4p03S2uVu5s/XXUdSdec6smVxZYYGpVmT8A+8ajuEyV5FatkvVru2x6uxGXXbH4A+jvgP4GMYy3iPLXzq/6z65+E005ey+cwMZD3fZcqc6xpjTFjQ0P3U+e++cPYmTIwj0nrK5NPTfl3WvpfLtXDcb2HQMudYOxFXQBor4L4T6vrOauFctYXJQ++NUWmJe5bmx1jDiZS1dTqWxo4GR8jm3fttpmPHppk9PEyv4/y8/sO07XacOmcqc0x2Vi9BvNJvN5oW8x4mOsydpidRxMYJPx06m1bqPzq9KtK8sxXNXFodD/+MYYaJTLwOhc9brCsV18oOR1i4tXChyTkq4lf4y1Ke+9axjDHqs1mfBbMXuP4Hzi+X7t8vzv7bHerrUPgPCxhjre4fXdfLNtNM+Jd+Zdh8xd8wP87uNPoPgv4W7/5P2BuxfsMabNnMnza+54Pdi5U671GPZY8CehX8Voeoo7FHpkeEc6715FwHZrIrUrHaviPUbPZHND+IhczrP6FcYvhOZ0Di/ETt0OI+YwNWR9r7tpf6WDeZKZDB1+z2IthOl1mPyb5FluvEx9h9d0NnM0Y1XPFkWIsk1WotJ0PBMmkvjvQTd0e71tfeV+8r8lQ/tpzpsmxJ+InrI/dj2UajUajVTUajatRqNRtGo1Go1Go4wjeMpZFMVV9CHbofPraLsJ3JpWV2XOoanCuFky4y3PPNxucK2uKC1Lbdb1eo+m5XomN6HfeZsabHLHRX/K+offtNGGmHWctcVcG44MdSqsOLY9VzX+Zxfxn2HPdWTpzWvkrtJ8M5zorrKcquRytJ5N5DZmcaW02l76nWO+BqPXm1A2Ry/0q71dH/mqrqeFjkYxjEXtsX8qubTk67rGycyqsdm4tZx5D6D5hhi0waaWmiaMP81Yjii5qxPlPuU/GfTL1Y5E6Jyfiq63qTa39A4J0sOGDgO9WF9bOXl0XfPRbsY2bPNKPy1YrFYrFYmRhhlTIyMjJWJYZHXuCXI8OoXsvfljGLFicNifpp2XunoPiG1wtx3p1Tah+/DD66OnVtVXP9rKbVxOnL0tR/rHtqB5UDErUVcl11D4qqvjpOcxX7armUNJB3LpW6bxVvD08e8h3odKKvyCFZBdSh2FVcST9xV3n3T8t1j7Kr9qgrqXg+13Pt5U7JCvFXVIV1YG5lRhkVYZJYYDDD4KOIMoHCp26WS8GB7uBh2zIdgq/PKyInjV2STShuoapUdCpX1yTwqq/z1VvET7Kh5nVPkO8YyxjLt2MaaMmWTLQvx3qnzltnXW0p2jxgbEtSny/Osv8Y9pLMXYoHVPAhkVdWVeODhR6q9/Sxe2liwwZWMVvFXfRkeIDxAePUPIrdJ4ey6yquzH+PD/bUOWAu05qVHtFd8rrKHSoeNIOUqrYr3FXyToqfYJgwmJdKpXXOwYYegNNGMzfZPp/t3t/DVs4zjNTN61rRqaWaa4NYbRjTa0tWwy2Y2tGN8ZO8ofNKq4j9SL7I+cSm4/6ovLV5HNXLI0jJidwrtk6ynCaP6Z++GjRlWS3tLeW129Mi9evxU9mtz6s5J3Z7M2ngTgnKvmpomxpaLCzPfmx0JWE+m3NLDDGOX47RctdYYNK5jakdqLkRlI39n590T5zctGSwwZZDJj6kW8XSi6ot2MmWWJ0DUT3nuvebBudScjZ79g8cWJ8av0k+/bE5WKd5MdbFpbDVMxu1DVMmtNZGJvq1mtRbn6M+g/kP0FwDwr7quZs7xosNGpbscyxhhd9TyJyFwbLcxlTasg75vW7TsV5K7ji44XPMMrdoj+Y3rT0Hie62nlYV/pwczzOmdLqLhYkzGMzCZWGMQzGMSsZYY6Di1t4nlJ+Em63mJxrVLxPbYxNEdgc1dU2iOKyoYYWjNrEeHTYybVk0atSa7ehuwsWMWTqn1TrnS6hYsi71d1+s+k+ic70e20fzE/VaTdxT9ZtU4GIXdeNx3X77guYYfpHeTQjaMX6brOu4OY4K7Y2d9mbHarI5ox3p4GpJ2Vd/Tst60f7j999pppjR+Q/Qf8J/VaORs3cji7FfFuN61+ui9s8hix1OCh5KGVV23BPXvZfz3CLyHpix+exi8z/KnCnosY2eunor+cxyPO/xJ0vKey9OvE9VjqaYu0x3Z3jd6o2b1T12D+F8l232lwaaacD5LE8LBxu7WTlbWraWpew8Xexjel3E+wWD4APITdNqR8F3R3T0lunCQ4GaE9R37DxeCYfcHi4xci5ovKfxVs55y2hf+65E/Xdp6jR5nrebTmi5incpkyOjs50JvrZwstbbW6kfuuQw+2mykf/EXNFzxfKTrxew929TR6bWnGL//F3JFOFCQT3K4lQ"
48 |
49 | kernels = Kernel(
50 | bz2.decompress(base64.b64decode(quantization_code)),
51 | [
52 | "int4WeightCompression",
53 | "int4WeightExtractionFloat",
54 | "int4WeightExtractionHalf",
55 | "int8WeightExtractionFloat",
56 | "int8WeightExtractionHalf",
57 | ],
58 | )
59 | except Exception as exception:
60 | kernels = None
61 | logger.warning("Failed to load cpm_kernels:" + str(exception))
62 |
63 |
64 | class W8A16Linear(torch.autograd.Function):
65 | @staticmethod
66 | def forward(ctx, inp: torch.Tensor, quant_w: torch.Tensor, scale_w: torch.Tensor, weight_bit_width):
67 | ctx.inp_shape = inp.size()
68 | ctx.weight_bit_width = weight_bit_width
69 | out_features = quant_w.size(0)
70 | inp = inp.contiguous().view(-1, inp.size(-1))
71 | weight = extract_weight_to_half(quant_w, scale_w, weight_bit_width)
72 | ctx.weight_shape = weight.size()
73 | output = inp.mm(weight.t())
74 | ctx.save_for_backward(inp, quant_w, scale_w)
75 | return output.view(*(ctx.inp_shape[:-1] + (out_features,)))
76 |
77 | @staticmethod
78 | def backward(ctx, grad_output: torch.Tensor):
79 | inp, quant_w, scale_w = ctx.saved_tensors
80 | weight = extract_weight_to_half(quant_w, scale_w, ctx.weight_bit_width)
81 | grad_output = grad_output.contiguous().view(-1, weight.size(0))
82 | grad_input = grad_output.mm(weight)
83 | grad_weight = grad_output.t().mm(inp)
84 | return grad_input.view(ctx.inp_shape), grad_weight.view(ctx.weight_shape), None, None
85 |
86 |
87 | def compress_int4_weight(weight: torch.Tensor): # (n, m)
88 | with torch.cuda.device(weight.device):
89 | n, m = weight.size(0), weight.size(1)
90 | assert m % 2 == 0
91 | m = m // 2
92 | out = torch.empty(n, m, dtype=torch.int8, device="cuda")
93 | stream = torch.cuda.current_stream()
94 |
95 | gridDim = (n, 1, 1)
96 | blockDim = (min(round_up(m, 32), 1024), 1, 1)
97 |
98 | kernels.int4WeightCompression(
99 | gridDim,
100 | blockDim,
101 | 0,
102 | stream,
103 | [ctypes.c_void_p(weight.data_ptr()), ctypes.c_void_p(out.data_ptr()), ctypes.c_int32(n), ctypes.c_int32(m)],
104 | )
105 | return out
106 |
107 |
108 | def extract_weight_to_half(weight: torch.Tensor, scale_list: torch.Tensor, source_bit_width: int):
109 | assert scale_list.dtype in [torch.half, torch.bfloat16]
110 | assert weight.dtype in [torch.int8]
111 | if source_bit_width == 8:
112 | return weight.to(scale_list.dtype) * scale_list[:, None]
113 | elif source_bit_width == 4:
114 | func = (
115 | kernels.int4WeightExtractionHalf if scale_list.dtype == torch.half else kernels.int4WeightExtractionBFloat16
116 | )
117 | else:
118 | assert False, "Unsupported bit-width"
119 |
120 | with torch.cuda.device(weight.device):
121 | n, m = weight.size(0), weight.size(1)
122 | out = torch.empty(n, m * (8 // source_bit_width), dtype=scale_list.dtype, device="cuda")
123 | stream = torch.cuda.current_stream()
124 |
125 | gridDim = (n, 1, 1)
126 | blockDim = (min(round_up(m, 32), 1024), 1, 1)
127 |
128 | func(
129 | gridDim,
130 | blockDim,
131 | 0,
132 | stream,
133 | [
134 | ctypes.c_void_p(weight.data_ptr()),
135 | ctypes.c_void_p(scale_list.data_ptr()),
136 | ctypes.c_void_p(out.data_ptr()),
137 | ctypes.c_int32(n),
138 | ctypes.c_int32(m),
139 | ],
140 | )
141 | return out
142 |
143 |
144 | class QuantizedLinear(torch.nn.Module):
145 | def __init__(self, weight_bit_width: int, weight, bias=None, device="cpu", dtype=None, empty_init=False, *args,
146 | **kwargs):
147 | super().__init__()
148 | self.weight_bit_width = weight_bit_width
149 |
150 | shape = weight.shape
151 |
152 | if weight is None or empty_init:
153 | self.weight = torch.empty(shape[0], shape[1] * weight_bit_width // 8, dtype=torch.int8, device=device)
154 | self.weight_scale = torch.empty(shape[0], dtype=dtype, device=device)
155 | else:
156 | self.weight_scale = weight.abs().max(dim=-1).values / ((2 ** (weight_bit_width - 1)) - 1)
157 | self.weight = torch.round(weight / self.weight_scale[:, None]).to(torch.int8)
158 | if weight_bit_width == 4:
159 | self.weight = compress_int4_weight(self.weight)
160 |
161 | try:
162 | self.weight = Parameter(self.weight.to(device), requires_grad=False)
163 | except:
164 | self.weight.to(device, dtype=self.weight.dtype)
165 | self.weight_scale = Parameter(self.weight_scale.to(device), requires_grad=False)
166 | self.bias = Parameter(bias.to(device), requires_grad=False) if bias is not None else None
167 |
168 | def forward(self, input):
169 | output = W8A16Linear.apply(input, self.weight, self.weight_scale, self.weight_bit_width)
170 | if self.bias is not None:
171 | output = output + self.bias
172 | return output
173 |
174 |
175 | def quantize(model, weight_bit_width, empty_init=False, device=None):
176 | """Replace fp16 linear with quantized linear"""
177 | for layer in model.layers:
178 | layer.self_attention.query_key_value = QuantizedLinear(
179 | weight_bit_width=weight_bit_width,
180 | weight=layer.self_attention.query_key_value.weight.to(torch.cuda.current_device()),
181 | bias=layer.self_attention.query_key_value.bias,
182 | dtype=layer.self_attention.query_key_value.weight.dtype,
183 | device=layer.self_attention.query_key_value.weight.device if device is None else device,
184 | empty_init=empty_init
185 | )
186 | layer.self_attention.dense = QuantizedLinear(
187 | weight_bit_width=weight_bit_width,
188 | weight=layer.self_attention.dense.weight.to(torch.cuda.current_device()),
189 | bias=layer.self_attention.dense.bias,
190 | dtype=layer.self_attention.dense.weight.dtype,
191 | device=layer.self_attention.dense.weight.device if device is None else device,
192 | empty_init=empty_init
193 | )
194 | layer.mlp.dense_h_to_4h = QuantizedLinear(
195 | weight_bit_width=weight_bit_width,
196 | weight=layer.mlp.dense_h_to_4h.weight.to(torch.cuda.current_device()),
197 | bias=layer.mlp.dense_h_to_4h.bias,
198 | dtype=layer.mlp.dense_h_to_4h.weight.dtype,
199 | device=layer.mlp.dense_h_to_4h.weight.device if device is None else device,
200 | empty_init=empty_init
201 | )
202 | layer.mlp.dense_4h_to_h = QuantizedLinear(
203 | weight_bit_width=weight_bit_width,
204 | weight=layer.mlp.dense_4h_to_h.weight.to(torch.cuda.current_device()),
205 | bias=layer.mlp.dense_4h_to_h.bias,
206 | dtype=layer.mlp.dense_4h_to_h.weight.dtype,
207 | device=layer.mlp.dense_4h_to_h.weight.device if device is None else device,
208 | empty_init=empty_init
209 | )
210 |
211 | return model
212 |
--------------------------------------------------------------------------------
/hook_comfyui_kolors_v2.py:
--------------------------------------------------------------------------------
1 | import os
2 | from types import MethodType
3 | import warnings
4 | from comfy.model_detection import *
5 | import comfy.model_detection as model_detection
6 | import comfy.supported_models
7 | import comfy.utils
8 |
9 | import torch
10 | from comfy import model_base
11 | from comfy.model_base import sdxl_pooled, CLIPEmbeddingNoiseAugmentation, Timestep, ModelType
12 |
13 |
14 | from comfy.ldm.modules.diffusionmodules.openaimodel import UNetModel
15 | from comfy.cldm.cldm import ControlNet
16 |
17 | # try:
18 | # import comfy.samplers as samplers
19 | # original_CFGGuider_inner_set_conds = samplers.CFGGuider.set_conds
20 |
21 | # def patched_set_conds(self, positive, negative):
22 | # if isinstance(self.model_patcher.model, KolorsSDXL):
23 | # import copy
24 | # if "control" in positive[0][1]:
25 | # if hasattr(positive[0][1]["control"], "control_model"):
26 | # if positive[0][1]["control"].control_model.label_emb.shape[1] == 5632:
27 | # return
28 |
29 |
30 | # warnings.warn("该方法不再维护")
31 | # positive = copy.deepcopy(positive)
32 | # negative = copy.deepcopy(negative)
33 | # hid_proj = self.model_patcher.model.encoder_hid_proj
34 | # if hid_proj is not None:
35 | # positive[0][0] = hid_proj(positive[0][0])
36 | # negative[0][0] = hid_proj(negative[0][0])
37 |
38 | # if "control" in positive[0][1]:
39 | # if hasattr(positive[0][1]["control"], "control_model"):
40 | # positive[0][1]["control"].control_model.label_emb = self.model_patcher.model.diffusion_model.label_emb
41 |
42 | # if "control" in negative[0][1]:
43 | # if hasattr(negative[0][1]["control"], "control_model"):
44 | # negative[0][1]["control"].control_model.label_emb = self.model_patcher.model.diffusion_model.label_emb
45 |
46 | # return original_CFGGuider_inner_set_conds(self, positive, negative)
47 |
48 | # samplers.CFGGuider.set_conds = patched_set_conds
49 | # except ImportError:
50 | # print("CFGGuider not found, skipping patching")
51 |
52 |
53 | class KolorsUNetModel(UNetModel):
54 | def __init__(self, *args, **kwargs):
55 | super().__init__(*args, **kwargs)
56 | self.encoder_hid_proj = nn.Linear(
57 | 4096, 2048, bias=True)
58 |
59 | def forward(self, *args, **kwargs):
60 | with torch.cuda.amp.autocast(enabled=True):
61 | if "context" in kwargs:
62 | kwargs["context"] = self.encoder_hid_proj(
63 | kwargs["context"])
64 |
65 | # if "y" in kwargs:
66 | # if kwargs["y"].shape[1] == 2816:
67 | # # 扩展至5632
68 | # kwargs["y"] = torch.cat(
69 | # torch.zeros(kwargs["y"].shape[0], 2816).to(kwargs["y"].device), kwargs["y"], dim=1)
70 |
71 | result = super().forward(*args, **kwargs)
72 | return result
73 |
74 |
75 | class KolorsSDXL(model_base.SDXL):
76 | def __init__(self, model_config, model_type=ModelType.EPS, device=None):
77 | model_config.sampling_settings["beta_schedule"] = "linear"
78 | model_config.sampling_settings["linear_start"] = 0.00085
79 | model_config.sampling_settings["linear_end"] = 0.014
80 | model_config.sampling_settings["timesteps"] = 1100
81 | model_type = ModelType.EPS
82 | model_base.BaseModel.__init__(
83 | self, model_config, model_type, device=device, unet_model=KolorsUNetModel)
84 | self.embedder = Timestep(256)
85 | self.noise_augmentor = CLIPEmbeddingNoiseAugmentation(
86 | **{"noise_schedule_config": {"timesteps": 1100, "beta_schedule": "linear", "linear_start": 0.00085, "linear_end": 0.014}, "timestep_dim": 1280})
87 |
88 | def encode_adm(self, **kwargs):
89 | clip_pooled = sdxl_pooled(kwargs, self.noise_augmentor)
90 | width = kwargs.get("width", 768)
91 | height = kwargs.get("height", 768)
92 | crop_w = kwargs.get("crop_w", 0)
93 | crop_h = kwargs.get("crop_h", 0)
94 | target_width = kwargs.get("target_width", width)
95 | target_height = kwargs.get("target_height", height)
96 |
97 | out = []
98 | out.append(self.embedder(torch.Tensor([height])))
99 | out.append(self.embedder(torch.Tensor([width])))
100 | out.append(self.embedder(torch.Tensor([crop_h])))
101 | out.append(self.embedder(torch.Tensor([crop_w])))
102 | out.append(self.embedder(torch.Tensor([target_height])))
103 | out.append(self.embedder(torch.Tensor([target_width])))
104 | flat = torch.flatten(torch.cat(out)).unsqueeze(
105 | dim=0).repeat(clip_pooled.shape[0], 1)
106 | return torch.cat((clip_pooled.to(flat.device), flat), dim=1)
107 |
108 |
109 | class KolorsSupported(comfy.supported_models.SDXL):
110 | unet_config = {
111 | "model_channels": 320,
112 | "use_linear_in_transformer": True,
113 | "transformer_depth": [0, 0, 2, 2, 10, 10],
114 | "context_dim": 2048,
115 | "adm_in_channels": 5632,
116 | "use_temporal_attention": False,
117 | }
118 |
119 | def get_model(self, state_dict, prefix="", device=None):
120 | out = KolorsSDXL(self, model_type=self.model_type(
121 | state_dict, prefix), device=device,)
122 | out.__class__ = model_base.SDXL
123 | if self.inpaint_model():
124 | out.set_inpaint()
125 | return out
126 |
127 |
128 | def kolors_unet_config_from_diffusers_unet(state_dict, dtype=None):
129 | match = {}
130 | transformer_depth = []
131 |
132 | attn_res = 1
133 | down_blocks = count_blocks(state_dict, "down_blocks.{}")
134 | for i in range(down_blocks):
135 | attn_blocks = count_blocks(
136 | state_dict, "down_blocks.{}.attentions.".format(i) + '{}')
137 | res_blocks = count_blocks(
138 | state_dict, "down_blocks.{}.resnets.".format(i) + '{}')
139 | for ab in range(attn_blocks):
140 | transformer_count = count_blocks(
141 | state_dict, "down_blocks.{}.attentions.{}.transformer_blocks.".format(i, ab) + '{}')
142 | transformer_depth.append(transformer_count)
143 | if transformer_count > 0:
144 | match["context_dim"] = state_dict["down_blocks.{}.attentions.{}.transformer_blocks.0.attn2.to_k.weight".format(
145 | i, ab)].shape[1]
146 |
147 | attn_res *= 2
148 | if attn_blocks == 0:
149 | for i in range(res_blocks):
150 | transformer_depth.append(0)
151 |
152 | match["transformer_depth"] = transformer_depth
153 |
154 | match["model_channels"] = state_dict["conv_in.weight"].shape[0]
155 | match["in_channels"] = state_dict["conv_in.weight"].shape[1]
156 | match["adm_in_channels"] = None
157 | if "class_embedding.linear_1.weight" in state_dict:
158 | match["adm_in_channels"] = state_dict["class_embedding.linear_1.weight"].shape[1]
159 | elif "add_embedding.linear_1.weight" in state_dict:
160 | match["adm_in_channels"] = state_dict["add_embedding.linear_1.weight"].shape[1]
161 |
162 | Kolors = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
163 | 'num_classes': 'sequential', 'adm_in_channels': 5632, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
164 | 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 2, 2, 10, 10], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 10,
165 | 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 2, 2, 2, 10, 10, 10],
166 | 'use_temporal_attention': False, 'use_temporal_resblock': False}
167 |
168 | Kolors_inpaint = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
169 | 'num_classes': 'sequential', 'adm_in_channels': 5632, 'dtype': dtype, 'in_channels': 9, 'model_channels': 320,
170 | 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 2, 2, 10, 10], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 10,
171 | 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 2, 2, 2, 10, 10, 10],
172 | 'use_temporal_attention': False, 'use_temporal_resblock': False}
173 |
174 | Kolors_ip2p = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
175 | 'num_classes': 'sequential', 'adm_in_channels': 5632, 'dtype': dtype, 'in_channels': 8, 'model_channels': 320,
176 | 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 2, 2, 10, 10], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 10,
177 | 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 2, 2, 2, 10, 10, 10],
178 | 'use_temporal_attention': False, 'use_temporal_resblock': False}
179 |
180 | SDXL = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
181 | 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
182 | 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 2, 2, 10, 10], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 10,
183 | 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 2, 2, 2, 10, 10, 10],
184 | 'use_temporal_attention': False, 'use_temporal_resblock': False}
185 |
186 | SDXL_mid_cnet = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
187 | 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
188 | 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 0, 0, 1, 1], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 1,
189 | 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 0, 0, 0, 1, 1, 1],
190 | 'use_temporal_attention': False, 'use_temporal_resblock': False}
191 |
192 | SDXL_small_cnet = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
193 | 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
194 | 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 0, 0, 0, 0], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 0,
195 | 'use_linear_in_transformer': True, 'num_head_channels': 64, 'context_dim': 1, 'transformer_depth_output': [0, 0, 0, 0, 0, 0, 0, 0, 0],
196 | 'use_temporal_attention': False, 'use_temporal_resblock': False}
197 |
198 | supported_models = [Kolors, Kolors_inpaint,
199 | Kolors_ip2p, SDXL, SDXL_mid_cnet, SDXL_small_cnet]
200 |
201 | for unet_config in supported_models:
202 | matches = True
203 | for k in match:
204 | if match[k] != unet_config[k]:
205 | print("key {} does not match".format(
206 | k), match[k], "||", unet_config[k])
207 | matches = False
208 | break
209 | if matches:
210 | return convert_config(unet_config)
211 | return None
212 |
213 |
214 | import comfy.ldm.modules.diffusionmodules.openaimodel
215 | from torch import nn
216 |
217 |
218 | def load_clipvision_336_from_sd(sd, prefix="", convert_keys=False):
219 | from comfy.clip_vision import ClipVisionModel, convert_to_transformers
220 |
221 | json_config = os.path.join(os.path.dirname(
222 | os.path.realpath(__file__)), "clip_vit_336", "config.json")
223 |
224 | clip = ClipVisionModel(json_config)
225 |
226 | m, u = clip.load_sd(sd)
227 | if len(m) > 0:
228 | logging.warning("missing clip vision: {}".format(m))
229 | u = set(u)
230 | keys = list(sd.keys())
231 | for k in keys:
232 | if k not in u:
233 | t = sd.pop(k)
234 | del t
235 |
236 | # def vis_forward(self, pixel_values, attention_mask=None, intermediate_output=None):
237 | # pixel_values = nn.functional.interpolate(
238 | # pixel_values, size=(336, 336), mode='bilinear', align_corners=False)
239 | # x = self.embeddings(pixel_values)
240 | # x = self.pre_layrnorm(x)
241 | # # TODO: attention_mask?
242 | # x, i = self.encoder(
243 | # x, mask=None, intermediate_output=intermediate_output)
244 | # pooled_output = self.post_layernorm(x[:, 0, :])
245 | # return x, i, pooled_output
246 |
247 | # clip.model.vision_model.forward = MethodType(
248 | # vis_forward, clip.model.vision_model
249 | # )
250 |
251 | return clip
252 |
253 |
254 | class KolorsControlNet(ControlNet):
255 | def __init__(self, *args, **kwargs):
256 | adm_in_channels = kwargs["adm_in_channels"]
257 | if adm_in_channels == 2816:
258 | # 异常: 该加载器不支持SDXL类型, 请使用ControlNet加载器+KolorsControlNetPatch节点
259 | raise Exception(
260 | "This loader does not support SDXL type, please use ControlNet loader + KolorsControlNetPatch node")
261 |
262 | super().__init__(*args, **kwargs)
263 | self.encoder_hid_proj = nn.Linear(
264 | 4096, 2048, bias=True)
265 |
266 | def forward(self, *args, **kwargs):
267 | with torch.cuda.amp.autocast(enabled=True):
268 | if "context" in kwargs:
269 | kwargs["context"] = self.encoder_hid_proj(
270 | kwargs["context"])
271 |
272 | result = super().forward(*args, **kwargs)
273 | return result
274 |
275 |
276 | class apply_kolors:
277 | def __enter__(self):
278 | import comfy.ldm.modules.diffusionmodules.openaimodel
279 | import comfy.cldm.cldm
280 | import comfy.utils
281 | import comfy.clip_vision
282 |
283 | self.original_load_clipvision_from_sd = comfy.clip_vision.load_clipvision_from_sd
284 | comfy.clip_vision.load_clipvision_from_sd = load_clipvision_336_from_sd
285 |
286 | self.original_UNET_MAP_BASIC = comfy.utils.UNET_MAP_BASIC.copy()
287 | comfy.utils.UNET_MAP_BASIC.add(
288 | ("encoder_hid_proj.weight", "encoder_hid_proj.weight"),
289 | )
290 | comfy.utils.UNET_MAP_BASIC.add(
291 | ("encoder_hid_proj.bias", "encoder_hid_proj.bias"),
292 | )
293 |
294 | self.original_unet_config_from_diffusers_unet = model_detection.unet_config_from_diffusers_unet
295 | model_detection.unet_config_from_diffusers_unet = kolors_unet_config_from_diffusers_unet
296 |
297 | import comfy.supported_models
298 | self.original_supported_models = comfy.supported_models.models
299 | comfy.supported_models.models = [KolorsSupported]
300 |
301 | self.original_controlnet = comfy.cldm.cldm.ControlNet
302 | comfy.cldm.cldm.ControlNet = KolorsControlNet
303 |
304 | def __exit__(self, type, value, traceback):
305 | import comfy.ldm.modules.diffusionmodules.openaimodel
306 | import comfy.cldm.cldm
307 | import comfy.utils
308 | comfy.utils.UNET_MAP_BASIC = self.original_UNET_MAP_BASIC
309 |
310 | model_detection.unet_config_from_diffusers_unet = self.original_unet_config_from_diffusers_unet
311 |
312 | import comfy.supported_models
313 | comfy.supported_models.models = self.original_supported_models
314 |
315 | import comfy.clip_vision
316 | comfy.clip_vision.load_clipvision_from_sd = self.original_load_clipvision_from_sd
317 |
318 | comfy.cldm.cldm.ControlNet = self.original_controlnet
319 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/mz_kolors_utils.py:
--------------------------------------------------------------------------------
1 |
2 | import json
3 | import os
4 | import shutil
5 | import subprocess
6 | import sys
7 | import threading
8 | import time
9 | import numpy as np
10 | import folder_paths
11 | import base64
12 | from PIL import Image, ImageFilter
13 | import io
14 | import torch
15 | import re
16 | import hashlib
17 | import cv2
18 | # sys.path.append(os.path.join(os.path.dirname(__file__)))
19 | temp_directory = folder_paths.get_temp_directory()
20 | from tqdm import tqdm
21 | import requests
22 | import comfy.utils
23 |
24 |
25 | CACHE_POOL = {}
26 |
27 |
28 | class Utils:
29 | def Md5(str):
30 | return hashlib.md5(str.encode('utf-8')).hexdigest()
31 |
32 | def check_frames_path(frames_path):
33 |
34 | if frames_path == "" or frames_path.startswith(".") or frames_path.startswith("/") or frames_path.endswith("/") or frames_path.endswith("\\"):
35 | return "frames_path不能为空"
36 |
37 | frames_path = os.path.join(
38 | folder_paths.get_output_directory(), frames_path)
39 |
40 | if frames_path == folder_paths.get_output_directory():
41 | return "frames_path不能为output目录"
42 |
43 | return ""
44 |
45 | def base64_to_pil_image(base64_str):
46 | if base64_str is None:
47 | return None
48 | if len(base64_str) == 0:
49 | return None
50 | if type(base64_str) not in [str, bytes]:
51 | return None
52 | if base64_str.startswith("data:image/png;base64,"):
53 | base64_str = base64_str.split(",")[-1]
54 | base64_str = base64_str.encode("utf-8")
55 | base64_str = base64.b64decode(base64_str)
56 | return Image.open(io.BytesIO(base64_str))
57 |
58 | def pil_image_to_base64(pil_image):
59 | buffered = io.BytesIO()
60 | pil_image.save(buffered, format="PNG")
61 | img_str = base64.b64encode(buffered.getvalue())
62 | img_str = str(img_str, encoding="utf-8")
63 | return f"data:image/png;base64,{img_str}"
64 |
65 | def listdir_png(path):
66 | try:
67 | files = os.listdir(path)
68 | new_files = []
69 | for file in files:
70 | if file.endswith(".png"):
71 | new_files.append(file)
72 | files = new_files
73 | files.sort(key=lambda x: int(os.path.basename(x).split(".")[0]))
74 | return files
75 | except Exception as e:
76 | return []
77 |
78 | def listdir_models(path):
79 | try:
80 | relative_paths = []
81 | for root, dirs, files in os.walk(path):
82 | for file in files:
83 | relative_paths.append(os.path.relpath(
84 | os.path.join(root, file), path))
85 | relative_paths = [f for f in relative_paths if f.endswith(".safetensors") or f.endswith(
86 | ".pt") or f.endswith(".pth") or f.endswith(".onnx")]
87 | return relative_paths
88 |
89 | except Exception as e:
90 |
91 | return []
92 |
93 | def tensor2pil(image):
94 | return Image.fromarray(np.clip(255.0 * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8))
95 |
96 | # Convert PIL to Tensor
97 |
98 | def pil2tensor(image):
99 | return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)[0]
100 |
101 | def pil2cv(image):
102 | return cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
103 |
104 | def cv2pil(image):
105 | return Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
106 |
107 | def list_tensor2tensor(data):
108 | result_tensor = torch.stack(data)
109 | return result_tensor
110 |
111 | def loadImage(path):
112 | img = Image.open(path)
113 | img = img.convert("RGB")
114 | return img
115 |
116 | def vae_encode_crop_pixels(pixels):
117 | x = (pixels.shape[1] // 8) * 8
118 | y = (pixels.shape[2] // 8) * 8
119 | if pixels.shape[1] != x or pixels.shape[2] != y:
120 | x_offset = (pixels.shape[1] % 8) // 2
121 | y_offset = (pixels.shape[2] % 8) // 2
122 | pixels = pixels[:, x_offset:x + x_offset, y_offset:y + y_offset, :]
123 | return pixels
124 |
125 | def native_vae_encode(vae, image):
126 | pixels = Utils.vae_encode_crop_pixels(image)
127 | t = vae.encode(pixels[:, :, :, :3])
128 | return {"samples": t}
129 |
130 | def native_vae_encode_for_inpaint(vae, pixels, mask):
131 | x = (pixels.shape[1] // 8) * 8
132 | y = (pixels.shape[2] // 8) * 8
133 | mask = torch.nn.functional.interpolate(mask.reshape(
134 | (-1, 1, mask.shape[-2], mask.shape[-1])), size=(pixels.shape[1], pixels.shape[2]), mode="bilinear")
135 |
136 | pixels = pixels.clone()
137 | if pixels.shape[1] != x or pixels.shape[2] != y:
138 | x_offset = (pixels.shape[1] % 8) // 2
139 | y_offset = (pixels.shape[2] % 8) // 2
140 | pixels = pixels[:, x_offset:x + x_offset, y_offset:y + y_offset, :]
141 | mask = mask[:, :, x_offset:x + x_offset, y_offset:y + y_offset]
142 |
143 | # grow mask by a few pixels to keep things seamless in latent space
144 |
145 | mask_erosion = mask
146 |
147 | m = (1.0 - mask.round()).squeeze(1)
148 | for i in range(3):
149 | pixels[:, :, :, i] -= 0.5
150 | pixels[:, :, :, i] *= m
151 | pixels[:, :, :, i] += 0.5
152 | t = vae.encode(pixels)
153 |
154 | return {"samples": t, "noise_mask": (mask_erosion[:, :, :x, :y].round())}
155 |
156 | def native_vae_decode(vae, samples):
157 | return vae.decode(samples["samples"])
158 |
159 | def native_clip_text_encode(clip, text):
160 | tokens = clip.tokenize(text)
161 | cond, pooled = clip.encode_from_tokens(tokens, return_pooled=True)
162 | return [[cond, {"pooled_output": pooled}]]
163 |
164 | def a1111_clip_text_encode(clip, text):
165 | try:
166 | from . import ADV_CLIP_emb_encode
167 | cond, pooled = ADV_CLIP_emb_encode.advanced_encode(
168 | clip, text, "none", "A1111", w_max=1.0, apply_to_pooled=False)
169 | return [[cond, {"pooled_output": pooled}]]
170 | except Exception as e:
171 | import nodes
172 | return nodes.CLIPTextEncode().encode(clip, text)[0]
173 |
174 | def cache_get(key):
175 | return CACHE_POOL.get(key, None)
176 |
177 | def cache_set(key, value):
178 | global CACHE_POOL
179 | CACHE_POOL[key] = value
180 | return True
181 |
182 | def get_models_path():
183 | return folder_paths.models_dir
184 |
185 | def get_gguf_models_path():
186 | models_path = os.path.join(
187 | folder_paths.models_dir, "gguf")
188 | os.makedirs(models_path, exist_ok=True)
189 | return models_path
190 |
191 | def get_translate_object(from_code, to_code):
192 | try:
193 | is_disabel_argostranslate = Utils.cache_get(
194 | "is_disabel_argostranslate")
195 |
196 | if is_disabel_argostranslate is not None:
197 | return None
198 |
199 | try:
200 | import argostranslate
201 | from argostranslate import translate, package
202 | except ImportError:
203 | subprocess.run([
204 | sys.executable, "-m",
205 | "pip", "install", "argostranslate"], check=True)
206 |
207 | try:
208 | import argostranslate
209 | from argostranslate import translate, package
210 | except ImportError:
211 | Utils.cache_set("is_disabel_argostranslate", True)
212 | print(
213 | "argostranslate not found and install failed , will disable it")
214 | return None
215 |
216 | packages = package.get_installed_packages()
217 | installed_packages = {}
218 | for p in packages:
219 | installed_packages[f"{p.from_code}_{p.to_code}"] = p
220 |
221 | argosmodel_dir = os.path.join(
222 | Utils.get_models_path(), "argosmodel")
223 | if not os.path.exists(argosmodel_dir):
224 | os.makedirs(argosmodel_dir)
225 |
226 | model_name = None
227 | if from_code == "zh" and to_code == "en":
228 | model_name = "zh_en"
229 | elif from_code == "en" and to_code == "zh":
230 | model_name = "en_zh"
231 | else:
232 | return None
233 |
234 | if Utils.cache_get(f"argostranslate_{model_name}") is not None:
235 | return Utils.cache_get(f"argostranslate_{model_name}")
236 |
237 | if installed_packages.get(model_name, None) is None:
238 | if not os.path.exists(os.path.join(argosmodel_dir, f"translate-{model_name}-1_9.argosmodel")):
239 | argosmodel_file = Utils.download_file(
240 | url=f"https://www.modelscope.cn/api/v1/models/wailovet/MinusZoneAIModels/repo?Revision=master&FilePath=argosmodel%2Ftranslate-{model_name}-1_9.argosmodel",
241 | filepath=os.path.join(
242 | argosmodel_dir, f"translate-{model_name}-1_9.argosmodel"),
243 | )
244 | else:
245 | argosmodel_file = os.path.join(
246 | argosmodel_dir, f"translate-{model_name}-1_9.argosmodel")
247 | package.install_from_path(argosmodel_file)
248 |
249 | translate_object = translate.get_translation_from_codes(
250 | from_code=from_code, to_code=to_code)
251 |
252 | Utils.cache_set(f"argostranslate_{model_name}", translate_object)
253 |
254 | return translate_object
255 | except Exception as e:
256 | Utils.cache_set("is_disabel_argostranslate", True)
257 | print(
258 | "argostranslate not found and install failed , will disable it")
259 | print(f"get_translate_object error: {e}")
260 | return None
261 |
262 | def translate_text(text, from_code, to_code):
263 | translation = Utils.get_translate_object(from_code, to_code)
264 | if translation is None:
265 | return text
266 |
267 | # Translate
268 | translatedText = translation.translate(
269 | text)
270 |
271 | return translatedText
272 |
273 | def zh2en(text):
274 | try:
275 | return Utils.translate_text(text, "zh", "en")
276 | except Exception as e:
277 | print(f"zh2en error: {e}")
278 | return text
279 |
280 | def en2zh(text):
281 | try:
282 | return Utils.translate_text(text, "en", "zh")
283 | except Exception as e:
284 | print(f"en2zh error: {e}")
285 | return text
286 |
287 | def prompt_zh_to_en(prompt):
288 | prompt = prompt.replace(",", ",")
289 | prompt = prompt.replace("。", ",")
290 | prompt = prompt.replace("\n", ",")
291 | tags = prompt.split(",")
292 | # 判断是否有中文
293 | for i, tag in enumerate(tags):
294 | if re.search(u'[\u4e00-\u9fff]', tag):
295 | tags[i] = Utils.zh2en(tag)
296 | # 如果第一个字母是大写,转为小写
297 | if tags[i][0].isupper():
298 | tags[i] = tags[i].lower().replace(".", "")
299 |
300 | return ",".join(tags)
301 |
302 | def mask_resize(mask, width, height):
303 | mask = mask.unsqueeze(0).unsqueeze(0)
304 | mask = torch.nn.functional.interpolate(
305 | mask, size=(height, width), mode="bilinear")
306 | mask = mask.squeeze(0).squeeze(0)
307 | return mask
308 |
309 | def mask_threshold(interested_mask):
310 | mask_image = Utils.tensor2pil(interested_mask)
311 | mask_image_cv2 = Utils.pil2cv(mask_image)
312 | ret, thresh1 = cv2.threshold(
313 | mask_image_cv2, 127, 255, cv2.THRESH_BINARY)
314 | thresh1 = Utils.cv2pil(thresh1)
315 | thresh1 = np.array(thresh1)
316 | thresh1 = thresh1[:, :, 0]
317 | return Utils.pil2tensor(thresh1)
318 |
319 | def mask_erode(interested_mask, value):
320 | value = int(value)
321 | mask_image = Utils.tensor2pil(interested_mask)
322 | mask_image_cv2 = Utils.pil2cv(mask_image)
323 | kernel = np.ones((5, 5), np.uint8)
324 | erosion = cv2.erode(mask_image_cv2, kernel, iterations=value)
325 | erosion = Utils.cv2pil(erosion)
326 | erosion = np.array(erosion)
327 | erosion = erosion[:, :, 0]
328 | return Utils.pil2tensor(erosion)
329 |
330 | def mask_dilate(interested_mask, value):
331 | value = int(value)
332 | mask_image = Utils.tensor2pil(interested_mask)
333 | mask_image_cv2 = Utils.pil2cv(mask_image)
334 | kernel = np.ones((5, 5), np.uint8)
335 | dilation = cv2.dilate(mask_image_cv2, kernel, iterations=value)
336 | dilation = Utils.cv2pil(dilation)
337 | dilation = np.array(dilation)
338 | dilation = dilation[:, :, 0]
339 | return Utils.pil2tensor(dilation)
340 |
341 | def mask_edge_opt(interested_mask, edge_feathering):
342 |
343 | mask_image = Utils.tensor2pil(interested_mask)
344 | mask_image_cv2 = Utils.pil2cv(mask_image)
345 |
346 | # 高斯模糊
347 | dilation2 = Utils.cv2pil(mask_image_cv2)
348 | dilation2 = mask_image.filter(
349 | ImageFilter.GaussianBlur(edge_feathering))
350 |
351 | # mask_image dilation2 图片蒙版叠加
352 | dilation2 = Utils.pil2cv(dilation2)
353 | # dilation2[mask_image_cv2 < 127] = 0
354 | dilation2 = Utils.cv2pil(dilation2)
355 | # to RGB
356 | dilation2 = np.array(dilation2)
357 | dilation2 = dilation2[:, :, 0]
358 | return Utils.pil2tensor(dilation2)
359 |
360 | def mask_composite(destination, source, x, y, mask=None, multiplier=8, resize_source=False):
361 | source = source.to(destination.device)
362 | if resize_source:
363 | source = torch.nn.functional.interpolate(source, size=(
364 | destination.shape[2], destination.shape[3]), mode="bilinear")
365 |
366 | source = comfy.utils.repeat_to_batch_size(source, destination.shape[0])
367 |
368 | x = max(-source.shape[3] * multiplier,
369 | min(x, destination.shape[3] * multiplier))
370 | y = max(-source.shape[2] * multiplier,
371 | min(y, destination.shape[2] * multiplier))
372 |
373 | left, top = (x // multiplier, y // multiplier)
374 | right, bottom = (left + source.shape[3], top + source.shape[2],)
375 |
376 | if mask is None:
377 | mask = torch.ones_like(source)
378 | else:
379 | mask = mask.to(destination.device, copy=True)
380 | mask = torch.nn.functional.interpolate(mask.reshape(
381 | (-1, 1, mask.shape[-2], mask.shape[-1])), size=(source.shape[2], source.shape[3]), mode="bilinear")
382 | mask = comfy.utils.repeat_to_batch_size(mask, source.shape[0])
383 |
384 | # calculate the bounds of the source that will be overlapping the destination
385 | # this prevents the source trying to overwrite latent pixels that are out of bounds
386 | # of the destination
387 | visible_width, visible_height = (
388 | destination.shape[3] - left + min(0, x), destination.shape[2] - top + min(0, y),)
389 |
390 | mask = mask[:, :, :visible_height, :visible_width]
391 | inverse_mask = torch.ones_like(mask) - mask
392 |
393 | source_portion = mask * source[:, :, :visible_height, :visible_width]
394 | destination_portion = inverse_mask * \
395 | destination[:, :, top:bottom, left:right]
396 |
397 | destination[:, :, top:bottom,
398 | left:right] = source_portion + destination_portion
399 | return destination
400 |
401 | def latent_upscale_by(samples, scale_by):
402 | s = samples.copy()
403 | width = round(samples["samples"].shape[3] * scale_by)
404 | height = round(samples["samples"].shape[2] * scale_by)
405 | s["samples"] = comfy.utils.common_upscale(
406 | samples["samples"], width, height, "nearest-exact", "disabled")
407 | return s
408 |
409 | def resize_by(image, percent):
410 | # 判断类型是否为PIL
411 | if not isinstance(image, Image.Image):
412 | image = Image.fromarray(image)
413 |
414 | width, height = image.size
415 | new_width = int(width * percent)
416 | new_height = int(height * percent)
417 | return image.resize((new_width, new_height), Image.LANCZOS)
418 |
419 | def resize_max(im, dst_w, dst_h):
420 | src_w, src_h = im.size
421 |
422 | if src_h < src_w:
423 | newWidth = dst_w
424 | newHeight = dst_w * src_h // src_w
425 | else:
426 | newWidth = dst_h * src_w // src_h
427 | newHeight = dst_h
428 |
429 | newHeight = newHeight // 8 * 8
430 | newWidth = newWidth // 8 * 8
431 |
432 | return im.resize((newWidth, newHeight), Image.Resampling.LANCZOS)
433 |
434 | def get_device():
435 | return comfy.model_management.get_torch_device()
436 |
437 | def download_small_file(url, filepath):
438 | response = requests.get(url)
439 | os.makedirs(os.path.dirname(filepath), exist_ok=True)
440 | with open(filepath, "wb") as f:
441 | f.write(response.content)
442 | return filepath
443 |
444 | def download_file(url, filepath, threads=8, retries=6):
445 |
446 | get_size_tmp = requests.get(url, stream=True)
447 | total_size = int(get_size_tmp.headers.get("content-length", 0))
448 |
449 | print(f"Downloading {url} to {filepath} with size {total_size} bytes")
450 |
451 | # 如果文件大小小于 50MB,使用download_small_file
452 | if total_size < 50 * 1024 * 1024:
453 | return Utils.download_small_file(url, filepath)
454 |
455 | base_filename = os.path.basename(filepath)
456 | cache_dir = os.path.join(os.path.dirname(
457 | filepath), f"{base_filename}.t_{threads}_cache")
458 | os.makedirs(cache_dir, exist_ok=True)
459 |
460 | def get_total_existing_size():
461 | fs = os.listdir(cache_dir)
462 | existing_size = 0
463 | for f in fs:
464 | if f.startswith("block_"):
465 | existing_size += os.path.getsize(
466 | os.path.join(cache_dir, f))
467 | return existing_size
468 |
469 | total_existing_size = get_total_existing_size()
470 |
471 | if total_size != 0 and total_existing_size != total_size:
472 |
473 | with tqdm(total=total_size, initial=total_existing_size, unit="B", unit_scale=True) as progress_bar:
474 | all_threads = []
475 |
476 | for i in range(threads):
477 | cache_filepath = os.path.join(cache_dir, f"block_{i}")
478 |
479 | start = total_size // threads * i
480 | end = total_size // threads * (i + 1) - 1
481 |
482 | if i == threads - 1:
483 | end = total_size
484 |
485 | # Check if the file already exists
486 | if os.path.exists(cache_filepath):
487 | # Get the size of the existing file
488 | existing_size = os.path.getsize(cache_filepath)
489 | else:
490 | existing_size = 0
491 |
492 | headers = {"Range": f"bytes={start + existing_size}-{end}"}
493 | if end == total_size:
494 | headers = {"Range": f"bytes={start + existing_size}-"}
495 | if start + existing_size >= end:
496 | continue
497 | # print(f"Downloading {cache_filepath} with headers bytes={start + existing_size}-{end}")
498 |
499 | # Streaming, so we can iterate over the response.
500 | response = requests.get(url, stream=True, headers=headers)
501 |
502 | def download_file_thread(response, cache_filepath):
503 | block_size = 1024
504 | if end - (start + existing_size) < block_size:
505 | block_size = end - (start + existing_size)
506 | with open(cache_filepath, "ab") as file:
507 | for data in response.iter_content(block_size):
508 | file.write(data)
509 | progress_bar.update(
510 | len(data)
511 | )
512 |
513 | t = threading.Thread(
514 | target=download_file_thread, args=(response, cache_filepath))
515 |
516 | all_threads.append(t)
517 |
518 | t.start()
519 |
520 | for t in all_threads:
521 | t.join()
522 |
523 | if total_size != 0 and get_total_existing_size() > total_size:
524 | # 文件下载失败
525 | shutil.rmtree(cache_dir)
526 | raise RuntimeError("Download failed, file is incomplete")
527 |
528 | if total_size != 0 and total_size != get_total_existing_size():
529 | if retries > 0:
530 | retries -= 1
531 | print(
532 | f"Download failed: {total_size} != {get_total_existing_size()}, retrying... {retries} retries left")
533 | return Utils.download_file(url, filepath, threads, retries)
534 |
535 | # 文件损坏
536 | raise RuntimeError(
537 | f"Download failed: {total_size} != {get_total_existing_size()}")
538 |
539 | if os.path.exists(filepath):
540 | shutil.move(filepath, filepath + ".old." +
541 | time.strftime("%Y%m%d%H%M%S"))
542 |
543 | # merge the files
544 | with open(filepath, "wb") as f:
545 | for i in range(threads):
546 | cache_filepath = os.path.join(cache_dir, f"block_{i}")
547 | with open(cache_filepath, "rb") as cf:
548 | f.write(cf.read())
549 |
550 | shutil.rmtree(cache_dir)
551 | return filepath
552 |
553 | def hf_download_model(url, only_get_path=False):
554 | if not url.startswith("https://"):
555 | raise ValueError("URL must start with https://")
556 | if url.startswith("https://huggingface.co/") or url.startswith("https://hf-mirror.com/"):
557 | base_model_path = os.path.abspath(os.path.join(
558 | Utils.get_models_path(), "transformers_models"))
559 | # https://huggingface.co/FaradayDotDev/llama-3-8b-Instruct-GGUF/resolve/main/llama-3-8b-Instruct.Q2_K.gguf?download=true
560 | texts = url.split("?")[0].split("/")
561 | file_name = texts[-1]
562 | zone_path = f"{texts[3]}/{texts[4]}"
563 |
564 | save_path = os.path.join(base_model_path, zone_path, file_name)
565 |
566 | if os.path.exists(save_path) is False:
567 | if only_get_path:
568 | return None
569 | os.makedirs(os.path.join(
570 | base_model_path, zone_path), exist_ok=True)
571 | Utils.download_file(url, save_path)
572 |
573 | # Utils.print_log(
574 | # f"File {save_path} => {os.path.getsize(save_path)} ")
575 |
576 | # 获取大小
577 | if os.path.getsize(save_path) == 0:
578 | if only_get_path:
579 | return None
580 | os.remove(save_path)
581 | raise ValueError(f"Download failed: {url}")
582 | return save_path
583 | else:
584 | texts = url.split("?")[0].split("/")
585 | host = texts[2].replace(".", "_")
586 | base_model_path = os.path.abspath(os.path.join(
587 | Utils.get_models_path(), f"{host}_models"))
588 |
589 | file_name = texts[-1]
590 | file_name_no_ext = os.path.splitext(file_name)[0]
591 | file_ext = os.path.splitext(file_name)[1]
592 | md5_hash = Utils.Md5(url)
593 |
594 | save_path = os.path.join(
595 | base_model_path, f"{file_name_no_ext}.{md5_hash}{file_ext}")
596 |
597 | if os.path.exists(save_path) is False:
598 | if only_get_path:
599 | return None
600 | os.makedirs(base_model_path, exist_ok=True)
601 | Utils.download_file(url, save_path)
602 |
603 | return save_path
604 |
605 | def print_log(*args):
606 | if os.environ.get("MZ_DEV", None) is not None:
607 | print(*args)
608 |
609 | def modelscope_download_model(model_type, model_name, only_get_path=False):
610 | if model_type not in modelscope_models_map:
611 | if only_get_path:
612 | return None
613 | raise ValueError(f"模型类型 {model_type} 不支持")
614 |
615 | if model_name not in modelscope_models_map[model_type]:
616 | if only_get_path:
617 | return None
618 | error_info = "魔搭可选模型名称列表:\n"
619 | for key in modelscope_models_map[model_type].keys():
620 | error_info += f"> {key}\n"
621 | raise ValueError(error_info)
622 |
623 | model_info = modelscope_models_map[model_type][model_name]
624 | url = model_info["url"]
625 | output = model_info["output"]
626 | save_path = os.path.abspath(
627 | os.path.join(Utils.get_models_path(), output))
628 | if not os.path.exists(save_path):
629 | if only_get_path:
630 | return None
631 | save_path = Utils.download_file(url, save_path)
632 | return save_path
633 |
634 | def progress_bar(steps):
635 | class pb:
636 | def __init__(self, steps):
637 | self.steps = steps
638 | self.pbar = comfy.utils.ProgressBar(steps)
639 |
640 | def update(self, step, total_steps, pil_img):
641 | if pil_img is None:
642 | self.pbar.update(step, total_steps)
643 |
644 | else:
645 | if pil_img.mode != "RGB":
646 | pil_img = pil_img.convert("RGB")
647 | self.pbar.update_absolute(
648 | step, total_steps, ("JPEG", pil_img, 512))
649 |
650 | return pb(steps)
651 |
652 | def split_en_to_zh(text: str):
653 | if text.find("(") != -1 and text.find(")") != -1:
654 | sentences = [
655 | "",
656 | ]
657 | for word_index in range(len(text)):
658 | if text[word_index] == "(" or text[word_index] == ")":
659 | sentences.append(str(text[word_index]))
660 | sentences.append("")
661 | else:
662 | sentences[-1] += str(text[word_index])
663 |
664 | Utils.print_log("not_translated:", sentences)
665 | for i in range(len(sentences)):
666 | if sentences[i] != "(" and sentences[i] != ")":
667 | sentences[i] = Utils.split_en_to_zh(sentences[i])
668 |
669 | Utils.print_log("translated:", sentences)
670 |
671 | return "".join(sentences)
672 |
673 | # 中文标点转英文标点
674 | text = text.replace(",", ",")
675 | text = text.replace("。", ".")
676 | text = text.replace("?", "?")
677 | text = text.replace("!", "!")
678 | text = text.replace(";", ";")
679 |
680 | result = []
681 | if text.find("\n") != -1:
682 | text = text.split("\n")
683 | for t in text:
684 | if t != "":
685 | result.append(Utils.split_en_to_zh(t))
686 | else:
687 | result.append(t)
688 | return "\n".join(result)
689 |
690 | if text.find(".") != -1:
691 | text = text.split(".")
692 | for t in text:
693 | if t != "":
694 | result.append(Utils.split_en_to_zh(t))
695 | else:
696 | result.append(t)
697 | return ".".join(result)
698 |
699 | if text.find("?") != -1:
700 | text = text.split("?")
701 | for t in text:
702 | if t != "":
703 | result.append(Utils.split_en_to_zh(t))
704 | else:
705 | result.append(t)
706 | return "?".join(result)
707 |
708 | if text.find("!") != -1:
709 | text = text.split("!")
710 | for t in text:
711 | if t != "":
712 | result.append(Utils.split_en_to_zh(t))
713 | else:
714 | result.append(t)
715 | return "!".join(result)
716 |
717 | if text.find(";") != -1:
718 | text = text.split(";")
719 | for t in text:
720 | if t != "":
721 | result.append(Utils.split_en_to_zh(t))
722 | else:
723 | result.append(t)
724 | return ";".join(result)
725 |
726 | if text.find(",") != -1:
727 | text = text.split(",")
728 | for t in text:
729 | if t != "":
730 | result.append(Utils.split_en_to_zh(t))
731 | else:
732 | result.append(t)
733 | return ",".join(result)
734 |
735 | if text.find(":") != -1:
736 | text = text.split(":")
737 | for t in text:
738 | if t != "":
739 | result.append(Utils.split_en_to_zh(t))
740 | else:
741 | result.append(t)
742 | return ":".join(result)
743 |
744 | # 如果是纯数字,不翻译
745 | if text.isdigit() or text.replace(".", "").isdigit() or text.replace(" ", "").isdigit() or text.replace("-", "").isdigit():
746 | return text
747 |
748 | return Utils.en2zh(text)
749 |
750 | def to_debug_prompt(p):
751 | if p is None:
752 | return ""
753 | zh = Utils.en2zh(p)
754 | if p == zh:
755 | return p
756 | zh = Utils.split_en_to_zh(p)
757 | p = p.strip()
758 | return f"""
759 | 原文:
760 | {p}
761 |
762 | 中文翻译:
763 | {zh}
764 | """
765 |
766 | def get_gguf_files():
767 | gguf_dir = Utils.get_gguf_models_path()
768 | if not os.path.exists(gguf_dir):
769 | os.makedirs(gguf_dir)
770 | gguf_files = []
771 | # walk gguf_dir
772 | for root, dirs, files in os.walk(gguf_dir):
773 | for file in files:
774 | if file.endswith(".gguf"):
775 | gguf_files.append(
776 | os.path.relpath(os.path.join(root, file), gguf_dir))
777 |
778 | return gguf_files
779 |
780 | def get_comfyui_models_path():
781 | return folder_paths.models_dir
782 |
783 | def download_model(model_info, only_get_path=False):
784 |
785 | url = model_info["url"]
786 | output = model_info["output"]
787 | save_path = os.path.abspath(
788 | os.path.join(Utils.get_comfyui_models_path(), output))
789 | if not os.path.exists(save_path):
790 | if only_get_path:
791 | return None
792 | save_path = Utils.download_file(url, save_path)
793 | return save_path
794 |
795 | def file_hash(file_path, hash_method):
796 | if not os.path.isfile(file_path):
797 | return ''
798 | h = hash_method()
799 | with open(file_path, 'rb') as f:
800 | while b := f.read(8192):
801 | h.update(b)
802 | return h.hexdigest()
803 |
804 | def get_cache_by_local(key):
805 | try:
806 | cache_json_file = os.path.join(
807 | Utils.get_models_path(), f"caches.json")
808 |
809 | if not os.path.exists(cache_json_file):
810 | return None
811 |
812 | with open(cache_json_file, "r", encoding="utf-8") as f:
813 | cache_json = json.load(f)
814 | return cache_json.get(key, None)
815 | except:
816 | return None
817 |
818 | def set_cache_by_local(key, value):
819 | try:
820 | cache_json_file = os.path.join(
821 | Utils.get_models_path(), f"caches.json")
822 |
823 | if not os.path.exists(cache_json_file):
824 | cache_json = {}
825 | else:
826 | with open(cache_json_file, "r", encoding="utf-8") as f:
827 | cache_json = json.load(f)
828 |
829 | cache_json[key] = value
830 |
831 | with open(cache_json_file, "w", encoding="utf-8") as f:
832 | json.dump(cache_json, f, indent=4)
833 | except:
834 | pass
835 |
836 | def file_sha256(file_path):
837 | # 获取文件的更新时间
838 | file_stat = os.stat(file_path)
839 | file_mtime = file_stat.st_mtime
840 | file_size = file_stat.st_size
841 | cache_key = f"{file_path}_{file_mtime}_{file_size}"
842 | cache_value = Utils.get_cache_by_local(cache_key)
843 | if cache_value is not None:
844 | return cache_value
845 |
846 | sha256 = Utils.file_hash(file_path, hashlib.sha256)
847 | Utils.set_cache_by_local(cache_key, sha256)
848 | return sha256
849 |
850 | def get_auto_model_fullpath(model_name):
851 | fullpath = Utils.cache_get(f"get_auto_model_fullpath_{model_name}")
852 | Utils.print_log(f"get_auto_model_fullpath_{model_name} => {fullpath}")
853 | if fullpath is not None:
854 | if os.path.exists(fullpath):
855 | return fullpath
856 |
857 | find_paths = []
858 | target_sha256 = ""
859 | file_path = ""
860 | download_url = ""
861 |
862 | MODEL_ZOO = Utils.get_model_zoo()
863 | for model in MODEL_ZOO:
864 | if model["model"] == model_name:
865 | find_paths = model["find_path"]
866 | target_sha256 = model["SHA256"]
867 | file_path = model["file_path"]
868 | download_url = model["url"]
869 | break
870 |
871 | if target_sha256 == "":
872 | raise ValueError(f"Model {model_name} not found in MODEL_ZOO")
873 |
874 | if os.path.exists(file_path):
875 | if Utils.file_sha256(file_path) != target_sha256:
876 | print(f"Model {model_name} file hash not match...")
877 | return file_path
878 |
879 | for find_path in find_paths:
880 | find_fullpath = os.path.join(
881 | Utils.get_comfyui_models_path(), find_path)
882 |
883 | if os.path.exists(find_fullpath):
884 | for root, dirs, files in os.walk(find_fullpath):
885 | for file in files:
886 | if target_sha256 == Utils.file_sha256(os.path.join(root, file)):
887 | Utils.cache_set(
888 | f"get_auto_model_fullpath_{model_name}", os.path.join(root, file))
889 | return os.path.join(root, file)
890 | else:
891 | Utils.print_log(
892 | f"Model {os.path.join(root, file)} file hash not match, {target_sha256} != {Utils.file_sha256(os.path.join(root, file))}")
893 |
894 | result = Utils.download_model(
895 | {"url": download_url, "output": file_path})
896 | Utils.cache_set(f"get_auto_model_fullpath_{model_name}", result)
897 | return result
898 |
899 | def testDownloadSpeed(url):
900 | try:
901 | print(f"Testing download speed for {url}")
902 | start = time.time()
903 | # 下载2M数据
904 | headers = {"Range": "bytes=0-2097151"}
905 | _ = requests.get(url, headers=headers, timeout=5)
906 | end = time.time()
907 | print(
908 | f"Download speed: {round(5.00 / (float(end) - float(start)) / 1024, 2)} KB/s")
909 | return float(end) - float(start) < 4
910 | except Exception as e:
911 | print(f"Test download speed failed: {e}")
912 | return False
913 |
914 | def get_model_zoo(tags_filter=None):
915 | source_model_zoo_file = os.path.join(
916 | os.path.dirname(__file__), "configs", "model_zoo.json")
917 | source_model_zoo_json = []
918 | try:
919 | with open(source_model_zoo_file, "r", encoding="utf-8") as f:
920 | source_model_zoo_json = json.load(f)
921 | except:
922 | pass
923 |
924 | # Utils.print_log(f"source_model_zoo_json: {json.dumps(source_model_zoo_json, indent=4)}")
925 | if tags_filter is not None:
926 | source_model_zoo_json = [
927 | m for m in source_model_zoo_json if tags_filter in m["tags"]]
928 |
929 | return source_model_zoo_json
930 |
931 |
932 |
933 | modelscope_models_map = {
934 |
935 | }
936 |
--------------------------------------------------------------------------------