15 Commits
Author SHA1 Message Date
City 0f567fc4a7 Gemma first implementation 2024-12-13 01:04:31 +01:00
City c52d82758a Rename/move 2024-12-12 19:51:17 +01:00
City 7b3f2ced4e Add fast rgb preview to Sana 2024-12-12 06:59:37 +01:00
City 4a11543beb Add switch for new xformers
#86 - patch provided by @SaiZyca
2024-12-11 22:48:51 +01:00
City ee982c5d73 Remove timm as a dependency 2024-12-11 22:44:09 +01:00
City ca2bc8bc65 Make mlp args match the one from timm 2024-12-11 22:37:13 +01:00
City d1f751677a Patch size logic from common dit 2024-12-11 22:34:31 +01:00
City 2beff5a4aa Faster model initialization
don't initialize base Sana model for SanaMS
2024-12-11 22:33:57 +01:00
City 7e19ac5e43 Use native ops for sana 2024-12-11 22:01:11 +01:00
City 5505ab4f40 Sana loader logic 2024-12-11 18:55:17 +01:00
City 06a936813f Consolidate loader logic 2024-12-11 17:32:57 +01:00
City 6a88140002 Unused 2024-12-11 17:24:18 +01:00
City d5a47fa3e5 Use native ops for PixArt 2024-12-11 00:52:48 +01:00
City 45423d9673 Remove HyDiT - supported in main 2024-12-10 22:24:37 +01:00
City 3f844cac42 PixArt initial rewrite 2024-12-10 22:19:02 +01:00
66 changed files with 3277 additions and 53176 deletions
+1 -5
View File
@@ -33,7 +33,7 @@ class GemmaLoader:
devices.append(f"cuda:{k}")
return {
"required": {
"model_name": (["Efficient-Large-Model/gemma-2-2b-it", "google/gemma-2-2b-it", "unsloth/gemma-2-2b-it-bnb-4bit"],),
"model_name": (["google/gemma-2-2b-it", "unsloth/gemma-2-2b-it-bnb-4bit"],),
"device": (devices, {"default":"cpu"}),
"dtype": (dtypes,),
}
@@ -56,10 +56,6 @@ class GemmaLoader:
text_encoder_dir = os.path.join(folder_paths.models_dir, 'text_encoders', 'models--unsloth--gemma-2-2b-it-bnb-4bit')
if not os.path.exists(os.path.join(text_encoder_dir, 'model.safetensors')):
snapshot_download('unsloth/gemma-2-2b-it-bnb-4bit', local_dir=text_encoder_dir)
elif model_name == 'Efficient-Large-Model/gemma-2-2b-it':
text_encoder_dir = os.path.join(folder_paths.models_dir, 'text_encoders', 'models--Efficient-Large-Model--gemma-2-2b-it')
if not os.path.exists(os.path.join(text_encoder_dir, 'model.safetensors')):
snapshot_download('Efficient-Large-Model/gemma-2-2b-it', local_dir=text_encoder_dir)
else:
raise ValueError('Not implemented!')
-74
View File
@@ -1,74 +0,0 @@
TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT
Tencent Hunyuan Release Date: 2024/5/14
By clicking to agree or by using, reproducing, modifying, distributing, performing or displaying any portion or element of the Tencent Hunyuan Works, including via any Hosted Service, You will be deemed to have recognized and accepted the content of this Agreement, which is effective immediately.
1. DEFINITIONS.
a. “Acceptable Use Policy” shall mean the policy made available by Tencent as set forth in the Exhibit A.
b. “Agreement” shall mean the terms and conditions for use, reproduction, distribution, modification, performance and displaying of the Hunyuan Works or any portion or element thereof set forth herein.
c. “Documentation” shall mean the specifications, manuals and documentation for Tencent Hunyuan made publicly available by Tencent.
d. “Hosted Service” shall mean a hosted service offered via an application programming interface (API), web access, or any other electronic or remote means.
e. “Licensee,” “You” or “Your” shall mean a natural person or legal entity exercising the rights granted by this Agreement and/or using the Tencent Hunyuan Works for any purpose and in any field of use.
f. “Materials” shall mean, collectively, Tencent’s proprietary Tencent Hunyuan and Documentation (and any portion thereof) as made available by Tencent under this Agreement.
g. “Model Derivatives” shall mean all: (i) modifications to Tencent Hunyuan or any Model Derivative of Tencent Hunyuan; (ii) works based on Tencent Hunyuan or any Model Derivative of Tencent Hunyuan; or (iii) any other machine learning model which is created by transfer of patterns of the weights, parameters, operations, or Output of Tencent Hunyuan or any Model Derivative of Tencent Hunyuan, to that model in order to cause that model to perform similarly to Tencent Hunyuan or a Model Derivative of Tencent Hunyuan, including distillation methods, methods that use intermediate data representations, or methods based on the generation of synthetic data Outputs by Tencent Hunyuan or a Model Derivative of Tencent Hunyuan for training that model. For clarity, Outputs by themselves are not deemed Model Derivatives.
h. “Output” shall mean the information and/or content output of Tencent Hunyuan or a Model Derivative that results from operating or otherwise using Tencent Hunyuan or a Model Derivative, including via a Hosted Service.
i. “Tencent,” “We” or “Us” shall mean THL A29 Limited.
j. “Tencent Hunyuan” shall mean the large language models, image/video/audio/3D generation models, and multimodal large language models and their software and algorithms, including trained model weights, parameters (including optimizer states), machine-learning model code, inference-enabling code, training-enabling code, fine-tuning enabling code and other elements of the foregoing made publicly available by Us at https://huggingface.co/Tencent-Hunyuan/HunyuanDiT and https://github.com/Tencent/HunyuanDiT .
k. “Tencent Hunyuan Works” shall mean: (i) the Materials; (ii) Model Derivatives; and (iii) all derivative works thereof.
l. “Third Party” or “Third Parties” shall mean individuals or legal entities that are not under common control with Us or You.
m. “including” shall mean including but not limited to.
2. GRANT OF RIGHTS.
We grant You a non-exclusive, worldwide, non-transferable and royalty-free limited license under Tencent’s intellectual property or other rights owned by Us embodied in or utilized by the Materials to use, reproduce, distribute, create derivative works of (including Model Derivatives), and make modifications to the Materials, only in accordance with the terms of this Agreement and the Acceptable Use Policy, and You must not violate (or encourage or permit anyone else to violate) any term of this Agreement or the Acceptable Use Policy.
3. DISTRIBUTION.
You may, subject to Your compliance with this Agreement, distribute or make available to Third Parties the Tencent Hunyuan Works, provided that You meet all of the following conditions:
a. You must provide all such Third Party recipients of the Tencent Hunyuan Works or products or services using them a copy of this Agreement;
b. You must cause any modified files to carry prominent notices stating that You changed the files;
c. You are encouraged to: (i) publish at least one technology introduction blogpost or one public statement expressing Your experience of using the Tencent Hunyuan Works; and (ii) mark the products or services developed by using the Tencent Hunyuan Works to indicate that the product/service is “Powered by Tencent Hunyuan”; and
d. All distributions to Third Parties (other than through a Hosted Service) must be accompanied by a “Notice” text file that contains the following notice: “Tencent Hunyuan is licensed under the Tencent Hunyuan Community License Agreement, Copyright © 2024 Tencent. All Rights Reserved. The trademark rights of “Tencent Hunyuan” are owned by Tencent or its affiliate.”
You may add Your own copyright statement to Your modifications and, except as set forth in this Section and in Section 5, may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Model Derivatives as a whole, provided Your use, reproduction, modification, distribution, performance and display of the work otherwise complies with the terms and conditions of this Agreement. If You receive Tencent Hunyuan Works from a Licensee as part of an integrated end user product, then this Section 3 of this Agreement will not apply to You.
4. ADDITIONAL COMMERCIAL TERMS.
If, on the Tencent Hunyuan version release date, the monthly active users of all products or services made available by or for Licensee is greater than 100 million monthly active users in the preceding calendar month, You must request a license from Tencent, which Tencent may grant to You in its sole discretion, and You are not authorized to exercise any of the rights under this Agreement unless or until Tencent otherwise expressly grants You such rights.
5. RULES OF USE.
a. Your use of the Tencent Hunyuan Works must comply with applicable laws and regulations (including trade compliance laws and regulations) and adhere to the Acceptable Use Policy for the Tencent Hunyuan Works, which is hereby incorporated by reference into this Agreement. You must include the use restrictions referenced in these Sections 5(a) and 5(b) as an enforceable provision in any agreement (e.g., license agreement, terms of use, etc.) governing the use and/or distribution of Tencent Hunyuan Works and You must provide notice to subsequent users to whom You distribute that Tencent Hunyuan Works are subject to the use restrictions in these Sections 5(a) and 5(b).
b. You must not use the Tencent Hunyuan Works or any Output or results of the Tencent Hunyuan Works to improve any other large language model (other than Tencent Hunyuan or Model Derivatives thereof).
6. INTELLECTUAL PROPERTY.
a. Subject to Tencent’s ownership of Tencent Hunyuan Works made by or for Tencent and intellectual property rights therein, conditioned upon Your compliance with the terms and conditions of this Agreement, as between You and Tencent, You will be the owner of any derivative works and modifications of the Materials and any Model Derivatives that are made by or for You.
b. No trademark licenses are granted under this Agreement, and in connection with the Tencent Hunyuan Works, Licensee may not use any name or mark owned by or associated with Tencent or any of its affiliates, except as required for reasonable and customary use in describing and distributing the Tencent Hunyuan Works. Tencent hereby grants You a license to use “Tencent Hunyuan” (the “Mark”) solely as required to comply with the provisions of Section 3(c), provided that You comply with any applicable laws related to trademark protection. All goodwill arising out of Your use of the Mark will inure to the benefit of Tencent.
c. If You commence a lawsuit or other proceedings (including a cross-claim or counterclaim in a lawsuit) against Us or any person or entity alleging that the Materials or any Output, or any portion of any of the foregoing, infringe any intellectual property or other right owned or licensable by You, then all licenses granted to You under this Agreement shall terminate as of the date such lawsuit or other proceeding is filed. You will defend, indemnify and hold harmless Us from and against any claim by any Third Party arising out of or related to Your or the Third Party’s use or distribution of the Tencent Hunyuan Works.
d. Tencent claims no rights in Outputs You generate. You and Your users are solely responsible for Outputs and their subsequent uses.
7. DISCLAIMERS OF WARRANTY AND LIMITATIONS OF LIABILITY.
a. We are not obligated to support, update, provide training for, or develop any further version of the Tencent Hunyuan Works or to grant any license thereto.
b. UNLESS AND ONLY TO THE EXTENT REQUIRED BY APPLICABLE LAW, THE TENCENT HUNYUAN WORKS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED “AS IS” WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES OF ANY KIND INCLUDING ANY WARRANTIES OF TITLE, MERCHANTABILITY, NONINFRINGEMENT, COURSE OF DEALING, USAGE OF TRADE, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING, REPRODUCING, MODIFYING, PERFORMING, DISPLAYING OR DISTRIBUTING ANY OF THE TENCENT HUNYUAN WORKS OR OUTPUTS AND ASSUME ANY AND ALL RISKS ASSOCIATED WITH YOUR OR A THIRD PARTY’S USE OR DISTRIBUTION OF ANY OF THE TENCENT HUNYUAN WORKS OR OUTPUTS AND YOUR EXERCISE OF RIGHTS AND PERMISSIONS UNDER THIS AGREEMENT.
c. TO THE FULLEST EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL TENCENT OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, CONSEQUENTIAL OR PUNITIVE DAMAGES, OR LOST PROFITS OF ANY KIND ARISING FROM THIS AGREEMENT OR RELATED TO ANY OF THE TENCENT HUNYUAN WORKS OR OUTPUTS, EVEN IF TENCENT OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
8. SURVIVAL AND TERMINATION.
a. The term of this Agreement shall commence upon Your acceptance of this Agreement or access to the Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein.
b. We may terminate this Agreement if You breach any of the terms or conditions of this Agreement. Upon termination of this Agreement, You must promptly delete and cease use of the Tencent Hunyuan Works. Sections 6(a), 6(c), 7 and 9 shall survive the termination of this Agreement.
9. GOVERNING LAW AND JURISDICTION.
a. This Agreement and any dispute arising out of or relating to it will be governed by the laws of the Hong Kong Special Administrative Region of the People’s Republic of China, without regard to conflict of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement.
b. Exclusive jurisdiction and venue for any dispute arising out of or relating to this Agreement will be a court of competent jurisdiction in the Hong Kong Special Administrative Region of the People’s Republic of China, and Tencent and Licensee consent to the exclusive jurisdiction of such court with respect to any such dispute.
 
EXHIBIT A
ACCEPTABLE USE POLICY
Tencent reserves the right to update this Acceptable Use Policy from time to time.
Last modified: 2024/5/14
Tencent endeavors to promote safe and fair use of its tools and features, including Tencent Hunyuan. You agree not to use Tencent Hunyuan or Model Derivatives:
1. In any way that violates any applicable national, federal, state, local, international or any other law or regulation;
2. To harm Yourself or others;
3. To repurpose or distribute output from Tencent Hunyuan or any Model Derivatives to harm Yourself or others;
4. To override or circumvent the safety guardrails and safeguards We have put in place;
5. For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;
6. To generate or disseminate verifiably false information and/or content with the purpose of harming others or influencing elections;
7. To generate or facilitate false online engagement, including fake reviews and other means of fake online engagement;
8. To intentionally defame, disparage or otherwise harass others;
9. To generate and/or disseminate malware (including ransomware) or any other content to be used for the purpose of harming electronic systems;
10. To generate or disseminate personal identifiable information with the purpose of harming others;
11. To generate or disseminate information (including images, code, posts, articles), and place the information in any public context (including –through the use of bot generated tweets), without expressly and conspicuously identifying that the information and/or content is machine generated;
12. To impersonate another individual without consent, authorization, or legal right;
13. To make high-stakes automated decisions in domains that affect an individual’s safety, rights or wellbeing (e.g., law enforcement, migration, medicine/health, management of critical infrastructure, safety components of products, essential services, credit, employment, housing, education, social scoring, or insurance);
14. In a manner that violates or disrespects the social ethics and moral standards of other countries or regions;
15. To perform, facilitate, threaten, incite, plan, promote or encourage violent extremism or terrorism;
16. For any use intended to discriminate against or harm individuals or groups based on protected characteristics or categories, online or offline social behavior or known or predicted personal or personality characteristics;
17. To intentionally exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;
18. For military purposes;
19. To engage in the unauthorized or unlicensed practice of any profession including, but not limited to, financial, legal, medical/health, or other professional practices.
-61
View File
@@ -1,61 +0,0 @@
"""
List of all HYDiT model types / settings
"""
from argparse import Namespace
hydit_args = Namespace(**{ # normally from argparse
"infer_mode": "torch",
"norm": "layer",
"learn_sigma": True,
"text_states_dim": 1024,
"text_states_dim_t5": 2048,
"text_len": 77,
"text_len_t5": 256,
})
hydit_conf = {
"G/2": { # Seems to be the main one
"unet_config": {
"depth" : 40,
"num_heads" : 16,
"patch_size" : 2,
"hidden_size" : 1408,
"mlp_ratio" : 4.3637,
"input_size": (1024//8, 1024//8),
"args": hydit_args,
},
"sampling_settings" : {
"beta_schedule" : "linear",
"linear_start" : 0.00085,
"linear_end" : 0.03,
"timesteps" : 1000,
},
},
"G/2-1.2": {
"unet_config": {
"depth" : 40,
"num_heads" : 16,
"patch_size" : 2,
"hidden_size" : 1408,
"mlp_ratio" : 4.3637,
"input_size": (1024//8, 1024//8),
"cond_style": False,
"cond_res" : False,
"args": hydit_args,
},
"sampling_settings" : {
"beta_schedule" : "linear",
"linear_start" : 0.00085,
"linear_end" : 0.018,
"timesteps" : 1000,
},
}
}
# these are the same as regular DiT, I think
from ..DiT.conf import dit_conf
for name in ["XL/2", "L/2", "B/2"]:
hydit_conf[name] = {
"unet_config": dit_conf[name]["unet_config"].copy(),
"sampling_settings": hydit_conf["G/2"]["sampling_settings"],
}
hydit_conf[name]["unet_config"]["args"] = hydit_args
-34
View File
@@ -1,34 +0,0 @@
{
"_name_or_path": "hfl/chinese-roberta-wwm-ext-large",
"architectures": [
"BertModel"
],
"attention_probs_dropout_prob": 0.1,
"bos_token_id": 0,
"classifier_dropout": null,
"directionality": "bidi",
"eos_token_id": 2,
"hidden_act": "gelu",
"hidden_dropout_prob": 0.1,
"hidden_size": 1024,
"initializer_range": 0.02,
"intermediate_size": 4096,
"layer_norm_eps": 1e-12,
"max_position_embeddings": 512,
"model_type": "bert",
"num_attention_heads": 16,
"num_hidden_layers": 24,
"output_past": true,
"pad_token_id": 0,
"pooler_fc_size": 768,
"pooler_num_attention_heads": 12,
"pooler_num_fc_layers": 3,
"pooler_size_per_head": 128,
"pooler_type": "first_token_transform",
"position_embedding_type": "absolute",
"torch_dtype": "float32",
"transformers_version": "4.22.1",
"type_vocab_size": 2,
"use_cache": true,
"vocab_size": 47020
}
-33
View File
@@ -1,33 +0,0 @@
{
"_name_or_path": "mt5",
"architectures": [
"MT5EncoderModel"
],
"classifier_dropout": 0.0,
"d_ff": 5120,
"d_kv": 64,
"d_model": 2048,
"decoder_start_token_id": 0,
"dense_act_fn": "gelu_new",
"dropout_rate": 0.1,
"eos_token_id": 1,
"feed_forward_proj": "gated-gelu",
"initializer_factor": 1.0,
"is_encoder_decoder": true,
"is_gated_act": true,
"layer_norm_epsilon": 1e-06,
"model_type": "mt5",
"num_decoder_layers": 24,
"num_heads": 32,
"num_layers": 24,
"output_past": true,
"pad_token_id": 0,
"relative_attention_max_distance": 128,
"relative_attention_num_buckets": 32,
"tie_word_embeddings": false,
"tokenizer_class": "T5Tokenizer",
"torch_dtype": "float16",
"transformers_version": "4.40.2",
"use_cache": true,
"vocab_size": 250112
}
-80
View File
@@ -1,80 +0,0 @@
import comfy.supported_models_base
import comfy.latent_formats
import comfy.model_patcher
import comfy.model_base
import comfy.utils
import comfy.conds
import torch
from comfy import model_management
from tqdm import tqdm
class EXM_HYDiT(comfy.supported_models_base.BASE):
unet_config = {}
unet_extra_config = {}
latent_format = comfy.latent_formats.SDXL
def __init__(self, model_conf):
self.unet_config = model_conf.get("unet_config", {})
self.sampling_settings = model_conf.get("sampling_settings", {})
self.latent_format = self.latent_format()
# UNET is handled by extension
self.unet_config["disable_unet_model_creation"] = True
def model_type(self, state_dict, prefix=""):
return comfy.model_base.ModelType.V_PREDICTION
class EXM_HYDiT_Model(comfy.model_base.BaseModel):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def extra_conds(self, **kwargs):
out = super().extra_conds(**kwargs)
for name in ["context_t5", "context_mask", "context_t5_mask"]:
out[name] = comfy.conds.CONDRegular(kwargs[name])
src_size_cond = kwargs.get("src_size_cond", None)
if src_size_cond is not None:
out["src_size_cond"] = comfy.conds.CONDRegular(torch.tensor(src_size_cond))
return out
def load_hydit(model_path, model_conf):
state_dict = comfy.utils.load_torch_file(model_path)
state_dict = state_dict.get("model", state_dict)
parameters = comfy.utils.calculate_parameters(state_dict)
unet_dtype = model_management.unet_dtype(model_params=parameters)
load_device = comfy.model_management.get_torch_device()
offload_device = comfy.model_management.unet_offload_device()
# ignore fp8/etc and use directly for now
manual_cast_dtype = model_management.unet_manual_cast(unet_dtype, load_device)
if manual_cast_dtype:
print(f"HunYuanDiT: falling back to {manual_cast_dtype}")
unet_dtype = manual_cast_dtype
model_conf = EXM_HYDiT(model_conf)
model = EXM_HYDiT_Model(
model_conf,
model_type=comfy.model_base.ModelType.V_PREDICTION,
device=model_management.get_torch_device()
)
from .models.models import HunYuanDiT
model.diffusion_model = HunYuanDiT(
**model_conf.unet_config,
log_fn=tqdm.write,
)
model.diffusion_model.load_state_dict(state_dict)
model.diffusion_model.dtype = unet_dtype
model.diffusion_model.eval()
model.diffusion_model.to(unet_dtype)
model_patcher = comfy.model_patcher.ModelPatcher(
model,
load_device = load_device,
offload_device = offload_device,
)
return model_patcher
-374
View File
@@ -1,374 +0,0 @@
import torch
import torch.nn as nn
from typing import Tuple, Union, Optional
try:
import flash_attn
if hasattr(flash_attn, '__version__') and int(flash_attn.__version__[0]) == 2:
from flash_attn.flash_attn_interface import flash_attn_kvpacked_func
from flash_attn.modules.mha import FlashSelfAttention, FlashCrossAttention
else:
from flash_attn.flash_attn_interface import flash_attn_unpadded_kvpacked_func
from flash_attn.modules.mha import FlashSelfAttention, FlashCrossAttention
except Exception as e:
print(f'flash_attn import failed: {e}')
def reshape_for_broadcast(freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor]], x: torch.Tensor, head_first=False):
"""
Reshape frequency tensor for broadcasting it with another tensor.
This function reshapes the frequency tensor to have the same shape as the target tensor 'x'
for the purpose of broadcasting the frequency tensor during element-wise operations.
Args:
freqs_cis (Union[torch.Tensor, Tuple[torch.Tensor]]): Frequency tensor to be reshaped.
x (torch.Tensor): Target tensor for broadcasting compatibility.
head_first (bool): head dimension first (except batch dim) or not.
Returns:
torch.Tensor: Reshaped frequency tensor.
Raises:
AssertionError: If the frequency tensor doesn't match the expected shape.
AssertionError: If the target tensor 'x' doesn't have the expected number of dimensions.
"""
ndim = x.ndim
assert 0 <= 1 < ndim
if isinstance(freqs_cis, tuple):
# freqs_cis: (cos, sin) in real space
if head_first:
assert freqs_cis[0].shape == (x.shape[-2], x.shape[-1]), f'freqs_cis shape {freqs_cis[0].shape} does not match x shape {x.shape}'
shape = [d if i == ndim - 2 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
else:
assert freqs_cis[0].shape == (x.shape[1], x.shape[-1]), f'freqs_cis shape {freqs_cis[0].shape} does not match x shape {x.shape}'
shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
return freqs_cis[0].view(*shape), freqs_cis[1].view(*shape)
else:
# freqs_cis: values in complex space
if head_first:
assert freqs_cis.shape == (x.shape[-2], x.shape[-1]), f'freqs_cis shape {freqs_cis.shape} does not match x shape {x.shape}'
shape = [d if i == ndim - 2 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
else:
assert freqs_cis.shape == (x.shape[1], x.shape[-1]), f'freqs_cis shape {freqs_cis.shape} does not match x shape {x.shape}'
shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
return freqs_cis.view(*shape)
def rotate_half(x):
x_real, x_imag = x.float().reshape(*x.shape[:-1], -1, 2).unbind(-1) # [B, S, H, D//2]
return torch.stack([-x_imag, x_real], dim=-1).flatten(3)
def apply_rotary_emb(
xq: torch.Tensor,
xk: Optional[torch.Tensor],
freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor]],
head_first: bool = False,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Apply rotary embeddings to input tensors using the given frequency tensor.
This function applies rotary embeddings to the given query 'xq' and key 'xk' tensors using the provided
frequency tensor 'freqs_cis'. The input tensors are reshaped as complex numbers, and the frequency tensor
is reshaped for broadcasting compatibility. The resulting tensors contain rotary embeddings and are
returned as real tensors.
Args:
xq (torch.Tensor): Query tensor to apply rotary embeddings. [B, S, H, D]
xk (torch.Tensor): Key tensor to apply rotary embeddings. [B, S, H, D]
freqs_cis (Union[torch.Tensor, Tuple[torch.Tensor]]): Precomputed frequency tensor for complex exponentials.
head_first (bool): head dimension first (except batch dim) or not.
Returns:
Tuple[torch.Tensor, torch.Tensor]: Tuple of modified query tensor and key tensor with rotary embeddings.
"""
xk_out = None
if isinstance(freqs_cis, tuple):
cos, sin = reshape_for_broadcast(freqs_cis, xq, head_first) # [S, D]
cos, sin = cos.to(xq.device), sin.to(xq.device)
xq_out = (xq.float() * cos + rotate_half(xq.float()) * sin).type_as(xq)
if xk is not None:
xk_out = (xk.float() * cos + rotate_half(xk.float()) * sin).type_as(xk)
else:
xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2)) # [B, S, H, D//2]
freqs_cis = reshape_for_broadcast(freqs_cis, xq_, head_first).to(xq.device) # [S, D//2] --> [1, S, 1, D//2]
xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3).type_as(xq)
if xk is not None:
xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2)) # [B, S, H, D//2]
xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3).type_as(xk)
return xq_out, xk_out
class FlashSelfMHAModified(nn.Module):
"""
Use QK Normalization.
"""
def __init__(self,
dim,
num_heads,
qkv_bias=True,
qk_norm=False,
attn_drop=0.0,
proj_drop=0.0,
device=None,
dtype=None,
norm_layer=nn.LayerNorm,
):
factory_kwargs = {'device': device, 'dtype': dtype}
super().__init__()
self.dim = dim
self.num_heads = num_heads
assert self.dim % num_heads == 0, "self.kdim must be divisible by num_heads"
self.head_dim = self.dim // num_heads
assert self.head_dim % 8 == 0 and self.head_dim <= 128, "Only support head_dim <= 128 and divisible by 8"
self.Wqkv = nn.Linear(dim, 3 * dim, bias=qkv_bias, **factory_kwargs)
# TODO: eps should be 1 / 65530 if using fp16
self.q_norm = norm_layer(self.head_dim, elementwise_affine=True, eps=1e-6) if qk_norm else nn.Identity()
self.k_norm = norm_layer(self.head_dim, elementwise_affine=True, eps=1e-6) if qk_norm else nn.Identity()
self.inner_attn = FlashSelfAttention(attention_dropout=attn_drop)
self.out_proj = nn.Linear(dim, dim, bias=qkv_bias, **factory_kwargs)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x, freqs_cis_img=None):
"""
Parameters
----------
x: torch.Tensor
(batch, seqlen, hidden_dim) (where hidden_dim = num heads * head dim)
freqs_cis_img: torch.Tensor
(batch, hidden_dim // 2), RoPE for image
"""
b, s, d = x.shape
qkv = self.Wqkv(x)
qkv = qkv.view(b, s, 3, self.num_heads, self.head_dim) # [b, s, 3, h, d]
q, k, v = qkv.unbind(dim=2) # [b, s, h, d]
q = self.q_norm(q).half() # [b, s, h, d]
k = self.k_norm(k).half()
# Apply RoPE if needed
if freqs_cis_img is not None:
qq, kk = apply_rotary_emb(q, k, freqs_cis_img)
assert qq.shape == q.shape and kk.shape == k.shape, f'qq: {qq.shape}, q: {q.shape}, kk: {kk.shape}, k: {k.shape}'
q, k = qq, kk
qkv = torch.stack([q, k, v], dim=2) # [b, s, 3, h, d]
context = self.inner_attn(qkv)
out = self.out_proj(context.view(b, s, d))
out = self.proj_drop(out)
out_tuple = (out,)
return out_tuple
class FlashCrossMHAModified(nn.Module):
"""
Use QK Normalization.
"""
def __init__(self,
qdim,
kdim,
num_heads,
qkv_bias=True,
qk_norm=False,
attn_drop=0.0,
proj_drop=0.0,
device=None,
dtype=None,
norm_layer=nn.LayerNorm,
):
factory_kwargs = {'device': device, 'dtype': dtype}
super().__init__()
self.qdim = qdim
self.kdim = kdim
self.num_heads = num_heads
assert self.qdim % num_heads == 0, "self.qdim must be divisible by num_heads"
self.head_dim = self.qdim // num_heads
assert self.head_dim % 8 == 0 and self.head_dim <= 128, "Only support head_dim <= 128 and divisible by 8"
self.scale = self.head_dim ** -0.5
self.q_proj = nn.Linear(qdim, qdim, bias=qkv_bias, **factory_kwargs)
self.kv_proj = nn.Linear(kdim, 2 * qdim, bias=qkv_bias, **factory_kwargs)
# TODO: eps should be 1 / 65530 if using fp16
self.q_norm = norm_layer(self.head_dim, elementwise_affine=True, eps=1e-6) if qk_norm else nn.Identity()
self.k_norm = norm_layer(self.head_dim, elementwise_affine=True, eps=1e-6) if qk_norm else nn.Identity()
self.inner_attn = FlashCrossAttention(attention_dropout=attn_drop)
self.out_proj = nn.Linear(qdim, qdim, bias=qkv_bias, **factory_kwargs)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x, y, freqs_cis_img=None):
"""
Parameters
----------
x: torch.Tensor
(batch, seqlen1, hidden_dim) (where hidden_dim = num_heads * head_dim)
y: torch.Tensor
(batch, seqlen2, hidden_dim2)
freqs_cis_img: torch.Tensor
(batch, hidden_dim // num_heads), RoPE for image
"""
b, s1, _ = x.shape # [b, s1, D]
_, s2, _ = y.shape # [b, s2, 1024]
q = self.q_proj(x).view(b, s1, self.num_heads, self.head_dim) # [b, s1, h, d]
kv = self.kv_proj(y).view(b, s2, 2, self.num_heads, self.head_dim) # [b, s2, 2, h, d]
k, v = kv.unbind(dim=2) # [b, s2, h, d]
q = self.q_norm(q).half() # [b, s1, h, d]
k = self.k_norm(k).half() # [b, s2, h, d]
# Apply RoPE if needed
if freqs_cis_img is not None:
qq, _ = apply_rotary_emb(q, None, freqs_cis_img)
assert qq.shape == q.shape, f'qq: {qq.shape}, q: {q.shape}'
q = qq # [b, s1, h, d]
kv = torch.stack([k, v], dim=2) # [b, s1, 2, h, d]
context = self.inner_attn(q, kv) # [b, s1, h, d]
context = context.view(b, s1, -1) # [b, s1, D]
out = self.out_proj(context)
out = self.proj_drop(out)
out_tuple = (out,)
return out_tuple
class CrossAttention(nn.Module):
"""
Use QK Normalization.
"""
def __init__(self,
qdim,
kdim,
num_heads,
qkv_bias=True,
qk_norm=False,
attn_drop=0.0,
proj_drop=0.0,
device=None,
dtype=None,
norm_layer=nn.LayerNorm,
):
factory_kwargs = {'device': device, 'dtype': dtype}
super().__init__()
self.qdim = qdim
self.kdim = kdim
self.num_heads = num_heads
assert self.qdim % num_heads == 0, "self.qdim must be divisible by num_heads"
self.head_dim = self.qdim // num_heads
assert self.head_dim % 8 == 0 and self.head_dim <= 128, "Only support head_dim <= 128 and divisible by 8"
self.scale = self.head_dim ** -0.5
self.q_proj = nn.Linear(qdim, qdim, bias=qkv_bias, **factory_kwargs)
self.kv_proj = nn.Linear(kdim, 2 * qdim, bias=qkv_bias, **factory_kwargs)
# TODO: eps should be 1 / 65530 if using fp16
self.q_norm = norm_layer(self.head_dim, elementwise_affine=True, eps=1e-6) if qk_norm else nn.Identity()
self.k_norm = norm_layer(self.head_dim, elementwise_affine=True, eps=1e-6) if qk_norm else nn.Identity()
self.attn_drop = nn.Dropout(attn_drop)
self.out_proj = nn.Linear(qdim, qdim, bias=qkv_bias, **factory_kwargs)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x, y, freqs_cis_img=None):
"""
Parameters
----------
x: torch.Tensor
(batch, seqlen1, hidden_dim) (where hidden_dim = num heads * head dim)
y: torch.Tensor
(batch, seqlen2, hidden_dim2)
freqs_cis_img: torch.Tensor
(batch, hidden_dim // 2), RoPE for image
"""
b, s1, c = x.shape # [b, s1, D]
_, s2, c = y.shape # [b, s2, 1024]
q = self.q_proj(x).view(b, s1, self.num_heads, self.head_dim) # [b, s1, h, d]
kv = self.kv_proj(y).view(b, s2, 2, self.num_heads, self.head_dim) # [b, s2, 2, h, d]
k, v = kv.unbind(dim=2) # [b, s, h, d]
q = self.q_norm(q)
k = self.k_norm(k)
# Apply RoPE if needed
if freqs_cis_img is not None:
qq, _ = apply_rotary_emb(q, None, freqs_cis_img)
assert qq.shape == q.shape, f'qq: {qq.shape}, q: {q.shape}'
q = qq
q = q * self.scale
q = q.transpose(-2, -3).contiguous() # q -> B, L1, H, C - B, H, L1, C
k = k.permute(0, 2, 3, 1).contiguous() # k -> B, L2, H, C - B, H, C, L2
attn = q @ k # attn -> B, H, L1, L2
attn = attn.softmax(dim=-1) # attn -> B, H, L1, L2
attn = self.attn_drop(attn)
x = attn @ v.transpose(-2, -3) # v -> B, L2, H, C - B, H, L2, C x-> B, H, L1, C
context = x.transpose(1, 2) # context -> B, H, L1, C - B, L1, H, C
context = context.contiguous().view(b, s1, -1)
out = self.out_proj(context) # context.reshape - B, L1, -1
out = self.proj_drop(out)
out_tuple = (out,)
return out_tuple
class Attention(nn.Module):
"""
We rename some layer names to align with flash attention
"""
def __init__(self, dim, num_heads, qkv_bias=True, qk_norm=False, attn_drop=0., proj_drop=0.,
norm_layer=nn.LayerNorm,
):
super().__init__()
self.dim = dim
self.num_heads = num_heads
assert self.dim % num_heads == 0, 'dim should be divisible by num_heads'
self.head_dim = self.dim // num_heads
# This assertion is aligned with flash attention
assert self.head_dim % 8 == 0 and self.head_dim <= 128, "Only support head_dim <= 128 and divisible by 8"
self.scale = self.head_dim ** -0.5
# qkv --> Wqkv
self.Wqkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
# TODO: eps should be 1 / 65530 if using fp16
self.q_norm = norm_layer(self.head_dim, elementwise_affine=True, eps=1e-6) if qk_norm else nn.Identity()
self.k_norm = norm_layer(self.head_dim, elementwise_affine=True, eps=1e-6) if qk_norm else nn.Identity()
self.attn_drop = nn.Dropout(attn_drop)
self.out_proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x, freqs_cis_img=None):
B, N, C = x.shape
qkv = self.Wqkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) # [3, b, h, s, d]
q, k, v = qkv.unbind(0) # [b, h, s, d]
q = self.q_norm(q) # [b, h, s, d]
k = self.k_norm(k) # [b, h, s, d]
# Apply RoPE if needed
if freqs_cis_img is not None:
qq, kk = apply_rotary_emb(q, k, freqs_cis_img, head_first=True)
assert qq.shape == q.shape and kk.shape == k.shape, \
f'qq: {qq.shape}, q: {q.shape}, kk: {kk.shape}, k: {k.shape}'
q, k = qq, kk
# just use SDP here for now
x = torch.nn.functional.scaled_dot_product_attention(
q, k, v,
).permute(0, 2, 1, 3).contiguous().reshape(B, N, C)
x = self.out_proj(x)
x = self.proj_drop(x)
out_tuple = (x,)
return out_tuple
-111
View File
@@ -1,111 +0,0 @@
import math
import torch
import torch.nn as nn
from einops import repeat
from timm.models.layers import to_2tuple
class PatchEmbed(nn.Module):
""" 2D Image to Patch Embedding
Image to Patch Embedding using Conv2d
A convolution based approach to patchifying a 2D image w/ embedding projection.
Based on the impl in https://github.com/google-research/vision_transformer
Hacked together by / Copyright 2020 Ross Wightman
Remove the _assert function in forward function to be compatible with multi-resolution images.
"""
def __init__(
self,
img_size=224,
patch_size=16,
in_chans=3,
embed_dim=768,
norm_layer=None,
flatten=True,
bias=True,
):
super().__init__()
if isinstance(img_size, int):
img_size = to_2tuple(img_size)
elif isinstance(img_size, (tuple, list)) and len(img_size) == 2:
img_size = tuple(img_size)
else:
raise ValueError(f"img_size must be int or tuple/list of length 2. Got {img_size}")
patch_size = to_2tuple(patch_size)
self.img_size = img_size
self.patch_size = patch_size
self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
self.num_patches = self.grid_size[0] * self.grid_size[1]
self.flatten = flatten
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def update_image_size(self, img_size):
self.img_size = img_size
self.grid_size = (img_size[0] // self.patch_size[0], img_size[1] // self.patch_size[1])
self.num_patches = self.grid_size[0] * self.grid_size[1]
def forward(self, x):
# B, C, H, W = x.shape
# _assert(H == self.img_size[0], f"Input image height ({H}) doesn't match model ({self.img_size[0]}).")
# _assert(W == self.img_size[1], f"Input image width ({W}) doesn't match model ({self.img_size[1]}).")
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
def timestep_embedding(t, dim, max_period=10000, repeat_only=False):
"""
Create sinusoidal timestep embeddings.
:param t: a 1-D Tensor of N indices, one per batch element.
These may be fractional.
:param dim: the dimension of the output.
:param max_period: controls the minimum frequency of the embeddings.
:return: an (N, D) Tensor of positional embeddings.
"""
# https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
if not repeat_only:
half = dim // 2
freqs = torch.exp(
-math.log(max_period)
* torch.arange(start=0, end=half, dtype=torch.float32)
/ half
).to(device=t.device) # size: [dim/2], 一个指数衰减的曲线
args = t[:, None].float() * freqs[None]
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
if dim % 2:
embedding = torch.cat(
[embedding, torch.zeros_like(embedding[:, :1])], dim=-1
)
else:
embedding = repeat(t, "b -> b d", d=dim)
return embedding
class TimestepEmbedder(nn.Module):
"""
Embeds scalar timesteps into vector representations.
"""
def __init__(self, hidden_size, frequency_embedding_size=256, out_size=None):
super().__init__()
if out_size is None:
out_size = hidden_size
self.mlp = nn.Sequential(
nn.Linear(frequency_embedding_size, hidden_size, bias=True),
nn.SiLU(),
nn.Linear(hidden_size, out_size, bias=True),
)
self.frequency_embedding_size = frequency_embedding_size
def forward(self, t):
t_freq = timestep_embedding(t, self.frequency_embedding_size).type(self.mlp[0].weight.dtype)
t_emb = self.mlp(t_freq)
return t_emb
-439
View File
@@ -1,439 +0,0 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.models.vision_transformer import Mlp
from .attn_layers import Attention, FlashCrossMHAModified, FlashSelfMHAModified, CrossAttention
from .embedders import TimestepEmbedder, PatchEmbed, timestep_embedding
from .norm_layers import RMSNorm
from .poolers import AttentionPool
from .posemb_layers import get_2d_rotary_pos_embed, get_fill_resize_and_crop
def modulate(x, shift, scale):
return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
class FP32_Layernorm(nn.LayerNorm):
def forward(self, inputs: torch.Tensor) -> torch.Tensor:
origin_dtype = inputs.dtype
return F.layer_norm(inputs.float(), self.normalized_shape, self.weight.float(), self.bias.float(),
self.eps).to(origin_dtype)
class FP32_SiLU(nn.SiLU):
def forward(self, inputs: torch.Tensor) -> torch.Tensor:
return torch.nn.functional.silu(inputs.float(), inplace=False).to(inputs.dtype)
class HunYuanDiTBlock(nn.Module):
"""
A HunYuanDiT block with `add` conditioning.
"""
def __init__(self,
hidden_size,
c_emb_size,
num_heads,
mlp_ratio=4.0,
text_states_dim=1024,
use_flash_attn=False,
qk_norm=False,
norm_type="layer",
skip=False,
):
super().__init__()
self.use_flash_attn = use_flash_attn
use_ele_affine = True
if norm_type == "layer":
norm_layer = FP32_Layernorm
elif norm_type == "rms":
norm_layer = RMSNorm
else:
raise ValueError(f"Unknown norm_type: {norm_type}")
# ========================= Self-Attention =========================
self.norm1 = norm_layer(hidden_size, elementwise_affine=use_ele_affine, eps=1e-6)
if use_flash_attn:
self.attn1 = FlashSelfMHAModified(hidden_size, num_heads=num_heads, qkv_bias=True, qk_norm=qk_norm)
else:
self.attn1 = Attention(hidden_size, num_heads=num_heads, qkv_bias=True, qk_norm=qk_norm)
# ========================= FFN =========================
self.norm2 = norm_layer(hidden_size, elementwise_affine=use_ele_affine, eps=1e-6)
mlp_hidden_dim = int(hidden_size * mlp_ratio)
approx_gelu = lambda: nn.GELU(approximate="tanh")
self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=approx_gelu, drop=0)
# ========================= Add =========================
# Simply use add like SDXL.
self.default_modulation = nn.Sequential(
FP32_SiLU(),
nn.Linear(c_emb_size, hidden_size, bias=True)
)
# ========================= Cross-Attention =========================
if use_flash_attn:
self.attn2 = FlashCrossMHAModified(hidden_size, text_states_dim, num_heads=num_heads, qkv_bias=True,
qk_norm=qk_norm)
else:
self.attn2 = CrossAttention(hidden_size, text_states_dim, num_heads=num_heads, qkv_bias=True,
qk_norm=qk_norm)
self.norm3 = norm_layer(hidden_size, elementwise_affine=True, eps=1e-6)
# ========================= Skip Connection =========================
if skip:
self.skip_norm = norm_layer(2 * hidden_size, elementwise_affine=True, eps=1e-6)
self.skip_linear = nn.Linear(2 * hidden_size, hidden_size)
else:
self.skip_linear = None
def forward(self, x, c=None, text_states=None, freq_cis_img=None, skip=None):
# Long Skip Connection
if self.skip_linear is not None:
cat = torch.cat([x, skip], dim=-1)
cat = self.skip_norm(cat)
x = self.skip_linear(cat)
# Self-Attention
shift_msa = self.default_modulation(c).unsqueeze(dim=1)
attn_inputs = (
self.norm1(x) + shift_msa, freq_cis_img,
)
x = x + self.attn1(*attn_inputs)[0]
# Cross-Attention
cross_inputs = (
self.norm3(x), text_states, freq_cis_img
)
x = x + self.attn2(*cross_inputs)[0]
# FFN Layer
mlp_inputs = self.norm2(x)
x = x + self.mlp(mlp_inputs)
return x
class FinalLayer(nn.Module):
"""
The final layer of HunYuanDiT.
"""
def __init__(self, final_hidden_size, c_emb_size, patch_size, out_channels):
super().__init__()
self.norm_final = nn.LayerNorm(final_hidden_size, elementwise_affine=False, eps=1e-6)
self.linear = nn.Linear(final_hidden_size, patch_size * patch_size * out_channels, bias=True)
self.adaLN_modulation = nn.Sequential(
FP32_SiLU(),
nn.Linear(c_emb_size, 2 * final_hidden_size, bias=True)
)
def forward(self, x, c):
shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
x = modulate(self.norm_final(x), shift, scale)
x = self.linear(x)
return x
class HunYuanDiT(nn.Module):
"""
HunYuanDiT: Diffusion model with a Transformer backbone.
Parameters
----------
args: argparse.Namespace
The arguments parsed by argparse.
input_size: tuple
The size of the input image.
patch_size: int
The size of the patch.
in_channels: int
The number of input channels.
hidden_size: int
The hidden size of the transformer backbone.
depth: int
The number of transformer blocks.
num_heads: int
The number of attention heads.
mlp_ratio: float
The ratio of the hidden size of the MLP in the transformer block.
log_fn: callable
The logging function.
"""
def __init__(
self, args,
input_size=(32, 32),
patch_size=2,
in_channels=4,
hidden_size=1152,
depth=28,
num_heads=16,
mlp_ratio=4.0,
log_fn=print,
cond_style=True,
cond_res=True,
**kwargs,
):
super().__init__()
self.args = args
self.log_fn = log_fn
self.depth = depth
self.learn_sigma = args.learn_sigma
self.in_channels = in_channels
self.out_channels = in_channels * 2 if args.learn_sigma else in_channels
self.patch_size = patch_size
self.num_heads = num_heads
self.hidden_size = hidden_size
self.head_size = hidden_size // num_heads
self.text_states_dim = args.text_states_dim
self.text_states_dim_t5 = args.text_states_dim_t5
self.text_len = args.text_len
self.text_len_t5 = args.text_len_t5
self.norm = args.norm
self.cond_res = cond_res
self.cond_style = cond_style
use_flash_attn = args.infer_mode == 'fa'
if use_flash_attn:
log_fn(f" Enable Flash Attention.")
qk_norm = True # See http://arxiv.org/abs/2302.05442 for details.
self.mlp_t5 = nn.Sequential(
nn.Linear(self.text_states_dim_t5, self.text_states_dim_t5 * 4, bias=True),
FP32_SiLU(),
nn.Linear(self.text_states_dim_t5 * 4, self.text_states_dim, bias=True),
)
# learnable replace
self.text_embedding_padding = nn.Parameter(
torch.randn(self.text_len + self.text_len_t5, self.text_states_dim, dtype=torch.float32))
# Attention pooling
self.pooler = AttentionPool(self.text_len_t5, self.text_states_dim_t5, num_heads=8, output_dim=1024)
self.extra_in_dim = 0
if self.cond_res:
# Image size and crop size conditions
self.extra_in_dim += 256 * 6
if self.cond_style:
# Here we use a default learned embedder layer for future extension.
self.style_embedder = nn.Embedding(1, hidden_size)
self.extra_in_dim += hidden_size
# Text embedding for `add`
self.last_size = input_size
self.x_embedder = PatchEmbed(input_size, patch_size, in_channels, hidden_size)
self.t_embedder = TimestepEmbedder(hidden_size)
self.extra_in_dim += 1024
self.extra_embedder = nn.Sequential(
nn.Linear(self.extra_in_dim, hidden_size * 4),
FP32_SiLU(),
nn.Linear(hidden_size * 4, hidden_size, bias=True),
)
# Image embedding
num_patches = self.x_embedder.num_patches
log_fn(f" Number of tokens: {num_patches}")
# HUnYuanDiT Blocks
self.blocks = nn.ModuleList([
HunYuanDiTBlock(hidden_size=hidden_size,
c_emb_size=hidden_size,
num_heads=num_heads,
mlp_ratio=mlp_ratio,
text_states_dim=self.text_states_dim,
use_flash_attn=use_flash_attn,
qk_norm=qk_norm,
norm_type=self.norm,
skip=layer > depth // 2,
)
for layer in range(depth)
])
self.final_layer = FinalLayer(hidden_size, hidden_size, patch_size, self.out_channels)
self.unpatchify_channels = self.out_channels
def forward_raw(self,
x,
t,
encoder_hidden_states=None,
text_embedding_mask=None,
encoder_hidden_states_t5=None,
text_embedding_mask_t5=None,
image_meta_size=None,
style=None,
cos_cis_img=None,
sin_cis_img=None,
return_dict=False,
):
"""
Forward pass of the encoder.
Parameters
----------
x: torch.Tensor
(B, D, H, W)
t: torch.Tensor
(B)
encoder_hidden_states: torch.Tensor
CLIP text embedding, (B, L_clip, D)
text_embedding_mask: torch.Tensor
CLIP text embedding mask, (B, L_clip)
encoder_hidden_states_t5: torch.Tensor
T5 text embedding, (B, L_t5, D)
text_embedding_mask_t5: torch.Tensor
T5 text embedding mask, (B, L_t5)
image_meta_size: torch.Tensor
(B, 6)
style: torch.Tensor
(B)
cos_cis_img: torch.Tensor
sin_cis_img: torch.Tensor
return_dict: bool
Whether to return a dictionary.
"""
text_states = encoder_hidden_states # 2,77,1024
text_states_t5 = encoder_hidden_states_t5 # 2,256,2048
text_states_mask = text_embedding_mask.bool() # 2,77
text_states_t5_mask = text_embedding_mask_t5.bool() # 2,256
b_t5, l_t5, c_t5 = text_states_t5.shape
text_states_t5 = self.mlp_t5(text_states_t5.view(-1, c_t5))
text_states = torch.cat([text_states, text_states_t5.view(b_t5, l_t5, -1)], dim=1) # 2,205,1024
clip_t5_mask = torch.cat([text_states_mask, text_states_t5_mask], dim=-1)
clip_t5_mask = clip_t5_mask
text_states = torch.where(clip_t5_mask.unsqueeze(2), text_states, self.text_embedding_padding.to(text_states))
_, _, oh, ow = x.shape
th, tw = oh // self.patch_size, ow // self.patch_size
# ========================= Build time and image embedding =========================
t = self.t_embedder(t)
x = self.x_embedder(x)
# Get image RoPE embedding according to `reso`lution.
freqs_cis_img = (cos_cis_img, sin_cis_img)
# ========================= Concatenate all extra vectors =========================
# Build text tokens with pooling
extra_vec = self.pooler(encoder_hidden_states_t5)
if self.cond_res:
# Build image meta size tokens
image_meta_size = timestep_embedding(image_meta_size.view(-1), 256) # [B * 6, 256]
# if self.args.use_fp16:
# image_meta_size = image_meta_size.half()
image_meta_size = image_meta_size.view(-1, 6 * 256)
extra_vec = torch.cat([extra_vec, image_meta_size], dim=1) # [B, D + 6 * 256]
if self.cond_style:
# Build style tokens
style_embedding = self.style_embedder(style)
extra_vec = torch.cat([extra_vec, style_embedding], dim=1)
# Concatenate all extra vectors
c = t + self.extra_embedder(extra_vec.to(self.dtype)) # [B, D]
# ========================= Forward pass through HunYuanDiT blocks =========================
skips = []
for layer, block in enumerate(self.blocks):
if layer > self.depth // 2:
skip = skips.pop()
x = block(x, c, text_states, freqs_cis_img, skip) # (N, L, D)
else:
x = block(x, c, text_states, freqs_cis_img) # (N, L, D)
if layer < (self.depth // 2 - 1):
skips.append(x)
# ========================= Final layer =========================
x = self.final_layer(x, c) # (N, L, patch_size ** 2 * out_channels)
x = self.unpatchify(x, th, tw) # (N, out_channels, H, W)
if return_dict:
return {'x': x}
return x
def calc_rope(self, height, width):
"""
Probably not the best in terms of perf to have this here
"""
th = height // 8 // self.patch_size
tw = width // 8 // self.patch_size
base_size = 512 // 8 // self.patch_size
start, stop = get_fill_resize_and_crop((th, tw), base_size)
sub_args = [start, stop, (th, tw)]
rope = get_2d_rotary_pos_embed(self.head_size, *sub_args)
return rope
def forward(self, x, timesteps, context, context_mask=None, context_t5=None, context_t5_mask=None, src_size_cond=(1024,1024), **kwargs):
"""
Forward pass that adapts comfy input to original forward function
x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images)
timesteps: (N,) tensor of diffusion timesteps
context: (N, 1, 77, C) CLIP conditioning
context_t5: (N, 1, 256, C) MT5 conditioning
"""
# context_mask = torch.zeros(x.shape[0], 77, device=x.device)
# context_t5_mask = torch.zeros(x.shape[0], 256, device=x.device)
# style
style = torch.as_tensor([0] * (x.shape[0]), device=x.device)
# image size - todo separate for cond/uncond when batched
if torch.is_tensor(src_size_cond):
src_size_cond = (int(src_size_cond[0][0]), int(src_size_cond[0][1]))
image_size = (x.shape[2]//2*16, x.shape[3]//2*16)
size_cond = list(src_size_cond) + [image_size[1], image_size[0], 0, 0]
image_meta_size = torch.as_tensor([size_cond] * x.shape[0], device=x.device)
# RoPE
rope = self.calc_rope(*image_size)
# Update x_embedder if image size changed
if self.last_size != image_size:
from tqdm import tqdm
tqdm.write(f"HyDiT: New image size {image_size}")
self.x_embedder.update_image_size(
(image_size[0]//8, image_size[1]//8),
)
self.last_size = image_size
# Run original forward pass
out = self.forward_raw(
x = x.to(self.dtype),
t = timesteps.to(self.dtype),
encoder_hidden_states = context.to(self.dtype),
text_embedding_mask = context_mask.to(self.dtype),
encoder_hidden_states_t5 = context_t5.to(self.dtype),
text_embedding_mask_t5 = context_t5_mask.to(self.dtype),
image_meta_size = image_meta_size.to(self.dtype),
style = style,
cos_cis_img = rope[0],
sin_cis_img = rope[1],
)
# return
out = out.to(torch.float)
if self.learn_sigma:
eps, rest = out[:, :self.in_channels], out[:, self.in_channels:]
return eps
else:
return out
def unpatchify(self, x, h, w):
"""
x: (N, T, patch_size**2 * C)
imgs: (N, H, W, C)
"""
c = self.unpatchify_channels
p = self.x_embedder.patch_size[0]
# h = w = int(x.shape[1] ** 0.5)
assert h * w == x.shape[1]
x = x.reshape(shape=(x.shape[0], h, w, p, p, c))
x = torch.einsum('nhwpqc->nchpwq', x)
imgs = x.reshape(shape=(x.shape[0], c, h * p, w * p))
return imgs
-68
View File
@@ -1,68 +0,0 @@
import torch
import torch.nn as nn
class RMSNorm(nn.Module):
def __init__(self, dim: int, elementwise_affine=True, eps: float = 1e-6):
"""
Initialize the RMSNorm normalization layer.
Args:
dim (int): The dimension of the input tensor.
eps (float, optional): A small value added to the denominator for numerical stability. Default is 1e-6.
Attributes:
eps (float): A small value added to the denominator for numerical stability.
weight (nn.Parameter): Learnable scaling parameter.
"""
super().__init__()
self.eps = eps
if elementwise_affine:
self.weight = nn.Parameter(torch.ones(dim))
def _norm(self, x):
"""
Apply the RMSNorm normalization to the input tensor.
Args:
x (torch.Tensor): The input tensor.
Returns:
torch.Tensor: The normalized tensor.
"""
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x):
"""
Forward pass through the RMSNorm layer.
Args:
x (torch.Tensor): The input tensor.
Returns:
torch.Tensor: The output tensor after applying RMSNorm.
"""
output = self._norm(x.float()).type_as(x)
if hasattr(self, "weight"):
output = output * self.weight
return output
class GroupNorm32(nn.GroupNorm):
def __init__(self, num_groups, num_channels, eps=1e-5, dtype=None):
super().__init__(num_groups=num_groups, num_channels=num_channels, eps=eps, dtype=dtype)
def forward(self, x):
y = super().forward(x).to(x.dtype)
return y
def normalization(channels, dtype=None):
"""
Make a standard normalization layer.
:param channels: number of input channels.
:return: an nn.Module for normalization.
"""
return GroupNorm32(num_channels=channels, num_groups=32, dtype=dtype)
-39
View File
@@ -1,39 +0,0 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
class AttentionPool(nn.Module):
def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
super().__init__()
self.positional_embedding = nn.Parameter(torch.randn(spacial_dim + 1, embed_dim) / embed_dim ** 0.5)
self.k_proj = nn.Linear(embed_dim, embed_dim)
self.q_proj = nn.Linear(embed_dim, embed_dim)
self.v_proj = nn.Linear(embed_dim, embed_dim)
self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
self.num_heads = num_heads
def forward(self, x):
x = x.permute(1, 0, 2) # NLC -> LNC
x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (L+1)NC
x = x + self.positional_embedding[:, None, :].to(x.dtype) # (L+1)NC
x, _ = F.multi_head_attention_forward(
query=x[:1], key=x, value=x,
embed_dim_to_check=x.shape[-1],
num_heads=self.num_heads,
q_proj_weight=self.q_proj.weight,
k_proj_weight=self.k_proj.weight,
v_proj_weight=self.v_proj.weight,
in_proj_weight=None,
in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
bias_k=None,
bias_v=None,
add_zero_attn=False,
dropout_p=0,
out_proj_weight=self.c_proj.weight,
out_proj_bias=self.c_proj.bias,
use_separate_proj_weight=True,
training=self.training,
need_weights=False
)
return x.squeeze(0)
-225
View File
@@ -1,225 +0,0 @@
import torch
import numpy as np
from typing import Union
def _to_tuple(x):
if isinstance(x, int):
return x, x
else:
return x
def get_fill_resize_and_crop(src, tgt): # src 来源的分辨率 tgt base 分辨率
th, tw = _to_tuple(tgt)
h, w = _to_tuple(src)
tr = th / tw # base 分辨率
r = h / w # 目标分辨率
# resize
if r > tr:
resize_height = th
resize_width = int(round(th / h * w))
else:
resize_width = tw
resize_height = int(round(tw / w * h)) # 根据base分辨率,将目标分辨率resize下来
crop_top = int(round((th - resize_height) / 2.0))
crop_left = int(round((tw - resize_width) / 2.0))
return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width)
def get_meshgrid(start, *args):
if len(args) == 0:
# start is grid_size
num = _to_tuple(start)
start = (0, 0)
stop = num
elif len(args) == 1:
# start is start, args[0] is stop, step is 1
start = _to_tuple(start)
stop = _to_tuple(args[0])
num = (stop[0] - start[0], stop[1] - start[1])
elif len(args) == 2:
# start is start, args[0] is stop, args[1] is num
start = _to_tuple(start) # 左上角 eg: 12,0
stop = _to_tuple(args[0]) # 右下角 eg: 20,32
num = _to_tuple(args[1]) # 目标大小 eg: 32,124
else:
raise ValueError(f"len(args) should be 0, 1 or 2, but got {len(args)}")
grid_h = np.linspace(start[0], stop[0], num[0], endpoint=False, dtype=np.float32) # 12-20 中间差值32份 0-32 中间差值124份
grid_w = np.linspace(start[1], stop[1], num[1], endpoint=False, dtype=np.float32)
grid = np.meshgrid(grid_w, grid_h) # here w goes first
grid = np.stack(grid, axis=0) # [2, W, H]
return grid
#################################################################################
# Sine/Cosine Positional Embedding Functions #
#################################################################################
# https://github.com/facebookresearch/mae/blob/main/util/pos_embed.py
def get_2d_sincos_pos_embed(embed_dim, start, *args, cls_token=False, extra_tokens=0):
"""
grid_size: int of the grid height and width
return:
pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
"""
grid = get_meshgrid(start, *args) # [2, H, w]
# grid_h = np.arange(grid_size, dtype=np.float32)
# grid_w = np.arange(grid_size, dtype=np.float32)
# grid = np.meshgrid(grid_w, grid_h) # here w goes first
# grid = np.stack(grid, axis=0) # [2, W, H]
grid = grid.reshape([2, 1, *grid.shape[1:]])
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
if cls_token and extra_tokens > 0:
pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
return pos_embed
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
assert embed_dim % 2 == 0
# use half of dimensions to encode grid_h
emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
return emb
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
"""
embed_dim: output dimension for each position
pos: a list of positions to be encoded: size (W,H)
out: (M, D)
"""
assert embed_dim % 2 == 0
omega = np.arange(embed_dim // 2, dtype=np.float64)
omega /= embed_dim / 2.
omega = 1. / 10000**omega # (D/2,)
pos = pos.reshape(-1) # (M,)
out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
emb_sin = np.sin(out) # (M, D/2)
emb_cos = np.cos(out) # (M, D/2)
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
return emb
#################################################################################
# Rotary Positional Embedding Functions #
#################################################################################
# https://github.com/facebookresearch/llama/blob/main/llama/model.py#L443
def get_2d_rotary_pos_embed(embed_dim, start, *args, use_real=True):
"""
This is a 2d version of precompute_freqs_cis, which is a RoPE for image tokens with 2d structure.
Parameters
----------
embed_dim: int
embedding dimension size
start: int or tuple of int
If len(args) == 0, start is num; If len(args) == 1, start is start, args[0] is stop, step is 1;
If len(args) == 2, start is start, args[0] is stop, args[1] is num.
use_real: bool
If True, return real part and imaginary part separately. Otherwise, return complex numbers.
Returns
-------
pos_embed: torch.Tensor
[HW, D/2]
"""
grid = get_meshgrid(start, *args) # [2, H, w]
grid = grid.reshape([2, 1, *grid.shape[1:]]) # 返回一个采样矩阵 分辨率与目标分辨率一致
pos_embed = get_2d_rotary_pos_embed_from_grid(embed_dim, grid, use_real=use_real)
return pos_embed
def get_2d_rotary_pos_embed_from_grid(embed_dim, grid, use_real=False):
assert embed_dim % 4 == 0
# use half of dimensions to encode grid_h
emb_h = get_1d_rotary_pos_embed(embed_dim // 2, grid[0].reshape(-1), use_real=use_real) # (H*W, D/4)
emb_w = get_1d_rotary_pos_embed(embed_dim // 2, grid[1].reshape(-1), use_real=use_real) # (H*W, D/4)
if use_real:
cos = torch.cat([emb_h[0], emb_w[0]], dim=1) # (H*W, D/2)
sin = torch.cat([emb_h[1], emb_w[1]], dim=1) # (H*W, D/2)
return cos, sin
else:
emb = torch.cat([emb_h, emb_w], dim=1) # (H*W, D/2)
return emb
def get_1d_rotary_pos_embed(dim: int, pos: Union[np.ndarray, int], theta: float = 10000.0, use_real=False):
"""
Precompute the frequency tensor for complex exponentials (cis) with given dimensions.
This function calculates a frequency tensor with complex exponentials using the given dimension 'dim'
and the end index 'end'. The 'theta' parameter scales the frequencies.
The returned tensor contains complex values in complex64 data type.
Args:
dim (int): Dimension of the frequency tensor.
pos (np.ndarray, int): Position indices for the frequency tensor. [S] or scalar
theta (float, optional): Scaling factor for frequency computation. Defaults to 10000.0.
use_real (bool, optional): If True, return real part and imaginary part separately.
Otherwise, return complex numbers.
Returns:
torch.Tensor: Precomputed frequency tensor with complex exponentials. [S, D/2]
"""
if isinstance(pos, int):
pos = np.arange(pos)
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)) # [D/2]
t = torch.from_numpy(pos).to(freqs.device) # type: ignore # [S]
freqs = torch.outer(t, freqs).float() # type: ignore # [S, D/2]
if use_real:
freqs_cos = freqs.cos().repeat_interleave(2, dim=1) # [S, D]
freqs_sin = freqs.sin().repeat_interleave(2, dim=1) # [S, D]
return freqs_cos, freqs_sin
else:
freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64 # [S, D/2]
return freqs_cis
def calc_sizes(rope_img, patch_size, th, tw):
""" 计算 RoPE 的尺寸. """
if rope_img == 'extend':
# 拓展模式
sub_args = [(th, tw)]
elif rope_img.startswith('base'):
# 基于一个尺寸, 其他尺寸插值获得.
base_size = int(rope_img[4:]) // 8 // patch_size # 基于512作为base,其他根据512差值得到
start, stop = get_fill_resize_and_crop((th, tw), base_size) # 需要在32x32里面 crop的左上角和右下角
sub_args = [start, stop, (th, tw)]
else:
raise ValueError(f"Unknown rope_img: {rope_img}")
return sub_args
def init_image_posemb(rope_img,
resolutions,
patch_size,
hidden_size,
num_heads,
log_fn,
rope_real=True,
):
freqs_cis_img = {}
for reso in resolutions:
th, tw = reso.height // 8 // patch_size, reso.width // 8 // patch_size
sub_args = calc_sizes(rope_img, patch_size, th, tw) # [左上角, 右下角, 目标高宽] 需要在32x32里面 crop的左上角和右下角
freqs_cis_img[str(reso)] = get_2d_rotary_pos_embed(hidden_size // num_heads, *sub_args, use_real=rope_real)
log_fn(f" Using image RoPE ({rope_img}) ({'real' if rope_real else 'complex'}): {sub_args} | ({reso}) "
f"{freqs_cis_img[str(reso)][0].shape if rope_real else freqs_cis_img[str(reso)].shape}")
return freqs_cis_img
-33
View File
@@ -1,33 +0,0 @@
{
"_name_or_path": "mt5",
"architectures": [
"MT5ForConditionalGeneration"
],
"classifier_dropout": 0.0,
"d_ff": 5120,
"d_kv": 64,
"d_model": 2048,
"decoder_start_token_id": 0,
"dense_act_fn": "gelu_new",
"dropout_rate": 0.1,
"eos_token_id": 1,
"feed_forward_proj": "gated-gelu",
"initializer_factor": 1.0,
"is_encoder_decoder": true,
"is_gated_act": true,
"layer_norm_epsilon": 1e-06,
"model_type": "mt5",
"num_decoder_layers": 24,
"num_heads": 32,
"num_layers": 24,
"output_past": true,
"pad_token_id": 0,
"relative_attention_max_distance": 128,
"relative_attention_num_buckets": 32,
"tie_word_embeddings": false,
"tokenizer_class": "T5Tokenizer",
"torch_dtype": "float16",
"transformers_version": "4.40.2",
"use_cache": true,
"vocab_size": 250112
}
@@ -1 +0,0 @@
{"eos_token": "</s>", "unk_token": "<unk>", "pad_token": "<pad>"}
@@ -1 +0,0 @@
{"eos_token": "</s>", "unk_token": "<unk>", "pad_token": "<pad>", "extra_ids": 0, "additional_special_tokens": null, "special_tokens_map_file": "/home/patrick/.cache/torch/transformers/685ac0ca8568ec593a48b61b0a3c272beee9bc194a3c7241d15dcadb5f875e53.f76030f3ec1b96a8199b2593390c610e76ca8028ef3d24680000619ffb646276", "tokenizer_file": null, "name_or_path": "google/mt5-small"}
-198
View File
@@ -1,198 +0,0 @@
import os
import folder_paths
from copy import deepcopy
from .conf import hydit_conf
from .loader import load_hydit
class HYDiTCheckpointLoader:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"ckpt_name": (folder_paths.get_filename_list("checkpoints"),),
"model": (list(hydit_conf.keys()),{"default":"G/2"}),
}
}
RETURN_TYPES = ("MODEL",)
RETURN_NAMES = ("model",)
FUNCTION = "load_checkpoint"
CATEGORY = "ExtraModels/HunyuanDiT"
TITLE = "Hunyuan DiT Checkpoint Loader"
def load_checkpoint(self, ckpt_name, model):
ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
model_conf = hydit_conf[model]
model = load_hydit(
model_path = ckpt_path,
model_conf = model_conf,
)
return (model,)
#### temp stuff for the text encoder ####
import torch
from .tenc import load_clip, load_t5
from ..utils.dtype import string_to_dtype
dtypes = [
"default",
"auto (comfy)",
"FP32",
"FP16",
"BF16"
]
class HYDiTTextEncoderLoader:
@classmethod
def INPUT_TYPES(s):
devices = ["auto", "cpu", "gpu"]
# hack for using second GPU as offload
for k in range(1, torch.cuda.device_count()):
devices.append(f"cuda:{k}")
return {
"required": {
"clip_name": (folder_paths.get_filename_list("clip"),),
"mt5_name": (folder_paths.get_filename_list("t5"),),
"device": (devices, {"default":"cpu"}),
"dtype": (dtypes,),
}
}
RETURN_TYPES = ("CLIP", "T5")
FUNCTION = "load_model"
CATEGORY = "ExtraModels/HunyuanDiT"
TITLE = "Hunyuan DiT Text Encoder Loader"
def load_model(self, clip_name, mt5_name, device, dtype):
dtype = string_to_dtype(dtype, "text_encoder")
if device == "cpu":
assert dtype in [None, torch.float32, torch.bfloat16], f"Can't use dtype '{dtype}' with CPU! Set dtype to 'default' or 'bf16'."
clip = load_clip(
model_path = folder_paths.get_full_path("clip", clip_name),
device = device,
dtype = dtype,
)
t5 = load_t5(
model_path = folder_paths.get_full_path("t5", mt5_name),
device = device,
dtype = dtype,
)
return(clip, t5)
class HYDiTTextEncode:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"text": ("STRING", {"multiline": True}),
"text_t5": ("STRING", {"multiline": True}),
"CLIP": ("CLIP",),
"T5": ("T5",),
}
}
RETURN_TYPES = ("CONDITIONING",)
FUNCTION = "encode"
CATEGORY = "ExtraModels/HunyuanDiT"
TITLE = "Hunyuan DiT Text Encode"
def encode(self, text, text_t5, CLIP, T5):
# T5
T5.load_model()
t5_pre = T5.tokenizer(
text_t5,
max_length = T5.cond_stage_model.max_length,
padding = 'max_length',
truncation = True,
return_attention_mask = True,
add_special_tokens = True,
return_tensors = 'pt'
)
t5_mask = t5_pre["attention_mask"]
with torch.no_grad():
t5_outs = T5.cond_stage_model.transformer(
input_ids = t5_pre["input_ids"].to(T5.load_device),
attention_mask = t5_mask.to(T5.load_device),
output_hidden_states = True,
)
# to-do: replace -1 for clip skip
t5_embs = t5_outs["hidden_states"][-1].float().cpu()
# "clip"
CLIP.load_model()
clip_pre = CLIP.tokenizer(
text,
max_length = CLIP.cond_stage_model.max_length,
padding = 'max_length',
truncation = True,
return_attention_mask = True,
add_special_tokens = True,
return_tensors = 'pt'
)
clip_mask = clip_pre["attention_mask"]
with torch.no_grad():
clip_outs = CLIP.cond_stage_model.transformer(
input_ids = clip_pre["input_ids"].to(CLIP.load_device),
attention_mask = clip_mask.to(CLIP.load_device),
)
# to-do: add hidden states
clip_embs = clip_outs[0].float().cpu()
# combined cond
return ([[
clip_embs, {
"context_t5": t5_embs,
"context_mask": clip_mask.float(),
"context_t5_mask": t5_mask.float()
}
]],)
class HYDiTTextEncodeSimple(HYDiTTextEncode):
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"text": ("STRING", {"multiline": True}),
"CLIP": ("CLIP",),
"T5": ("T5",),
}
}
FUNCTION = "encode_simple"
TITLE = "Hunyuan DiT Text Encode (simple)"
def encode_simple(self, text, **args):
return self.encode(text=text, text_t5=text, **args)
class HYDiTSrcSizeCond:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"cond": ("CONDITIONING", ),
"width": ("INT", {"default": 1024.0, "min": 0, "max": 8192, "step": 16}),
"height": ("INT", {"default": 1024.0, "min": 0, "max": 8192, "step": 16}),
}
}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("cond",)
FUNCTION = "add_cond"
CATEGORY = "ExtraModels/HunyuanDiT"
TITLE = "Hunyuan DiT Size Conditioning (advanced)"
def add_cond(self, cond, width, height):
cond = deepcopy(cond)
for c in range(len(cond)):
cond[c][1].update({
"src_size_cond": [[height, width]],
})
return (cond,)
NODE_CLASS_MAPPINGS = {
"HYDiTCheckpointLoader": HYDiTCheckpointLoader,
"HYDiTTextEncoderLoader": HYDiTTextEncoderLoader,
"HYDiTTextEncode": HYDiTTextEncode,
"HYDiTTextEncodeSimple": HYDiTTextEncodeSimple,
"HYDiTSrcSizeCond": HYDiTSrcSizeCond,
}
-180
View File
@@ -1,180 +0,0 @@
# This is for loading the CLIP (bert?) + mT5 encoder for HunYuanDiT
import os
import torch
from transformers import AutoTokenizer, modeling_utils
from transformers import T5Config, T5EncoderModel, BertConfig, BertModel
from comfy import model_management
import comfy.model_patcher
import comfy.utils
class mT5Model(torch.nn.Module):
def __init__(self, textmodel_json_config=None, device="cpu", max_length=256, freeze=True, dtype=None):
super().__init__()
self.device = device
self.dtype = dtype
self.max_length = max_length
if textmodel_json_config is None:
textmodel_json_config = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
f"config_mt5.json"
)
config = T5Config.from_json_file(textmodel_json_config)
with modeling_utils.no_init_weights():
self.transformer = T5EncoderModel(config)
self.to(dtype)
if freeze:
self.freeze()
def freeze(self):
self.transformer = self.transformer.eval()
for param in self.parameters():
param.requires_grad = False
def load_sd(self, sd):
return self.transformer.load_state_dict(sd, strict=False)
def to(self, *args, **kwargs):
return self.transformer.to(*args, **kwargs)
class hyCLIPModel(torch.nn.Module):
def __init__(self, textmodel_json_config=None, device="cpu", max_length=77, freeze=True, dtype=None):
super().__init__()
self.device = device
self.dtype = dtype
self.max_length = max_length
if textmodel_json_config is None:
textmodel_json_config = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
f"config_clip.json"
)
config = BertConfig.from_json_file(textmodel_json_config)
with modeling_utils.no_init_weights():
self.transformer = BertModel(config)
self.to(dtype)
if freeze:
self.freeze()
def freeze(self):
self.transformer = self.transformer.eval()
for param in self.parameters():
param.requires_grad = False
def load_sd(self, sd):
return self.transformer.load_state_dict(sd, strict=False)
def to(self, *args, **kwargs):
return self.transformer.to(*args, **kwargs)
class EXM_HyDiT_Tenc_Temp:
def __init__(self, no_init=False, device="cpu", dtype=None, model_class="mT5", *kwargs):
if no_init:
return
size = 8 if model_class == "mT5" else 2
if dtype == torch.float32:
size *= 2
size *= (1024**3)
if device == "auto":
self.load_device = model_management.text_encoder_device()
self.offload_device = model_management.text_encoder_offload_device()
self.init_device = "cpu"
elif device == "cpu":
size = 0 # doesn't matter
self.load_device = "cpu"
self.offload_device = "cpu"
self.init_device="cpu"
elif device.startswith("cuda"):
print("Direct CUDA device override!\nVRAM will not be freed by default.")
size = 0 # not used
self.load_device = device
self.offload_device = device
self.init_device = device
else:
self.load_device = model_management.get_torch_device()
self.offload_device = "cpu"
self.init_device="cpu"
self.dtype = dtype
self.device = self.load_device
if model_class == "mT5":
self.cond_stage_model = mT5Model(
device = self.load_device,
dtype = self.dtype,
)
tokenizer_args = {"subfolder": "t2i/mt5"} # web
tokenizer_path = os.path.join( # local
os.path.dirname(os.path.realpath(__file__)),
"mt5_tokenizer",
)
else:
self.cond_stage_model = hyCLIPModel(
device = self.load_device,
dtype = self.dtype,
)
tokenizer_args = {"subfolder": "t2i/tokenizer",} # web
tokenizer_path = os.path.join( # local
os.path.dirname(os.path.realpath(__file__)),
"tokenizer",
)
# self.tokenizer = AutoTokenizer.from_pretrained(
# "Tencent-Hunyuan/HunyuanDiT",
# **tokenizer_args
# )
self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
self.patcher = comfy.model_patcher.ModelPatcher(
self.cond_stage_model,
load_device = self.load_device,
offload_device = self.offload_device,
size = size,
)
def clone(self):
n = EXM_HyDiT_Tenc_Temp(no_init=True)
n.patcher = self.patcher.clone()
n.cond_stage_model = self.cond_stage_model
n.tokenizer = self.tokenizer
return n
def load_sd(self, sd):
return self.cond_stage_model.load_sd(sd)
def get_sd(self):
return self.cond_stage_model.state_dict()
def load_model(self):
if self.load_device != "cpu":
model_management.load_model_gpu(self.patcher)
return self.patcher
def add_patches(self, patches, strength_patch=1.0, strength_model=1.0):
return self.patcher.add_patches(patches, strength_patch, strength_model)
def get_key_patches(self):
return self.patcher.get_key_patches()
def load_clip(model_path, **kwargs):
model = EXM_HyDiT_Tenc_Temp(model_class="clip", **kwargs)
sd = comfy.utils.load_torch_file(model_path)
prefix = "bert."
state_dict = {}
for key in sd:
nkey = key
if key.startswith(prefix):
nkey = key[len(prefix):]
state_dict[nkey] = sd[key]
m, e = model.load_sd(state_dict)
if len(m) > 0 or len(e) > 0:
print(f"HYDiT: clip missing {len(m)} keys ({len(e)} extra)")
return model
def load_t5(model_path, **kwargs):
model = EXM_HyDiT_Tenc_Temp(model_class="mT5", **kwargs)
sd = comfy.utils.load_torch_file(model_path)
m, e = model.load_sd(sd)
if len(m) > 0 or len(e) > 0:
print(f"HYDiT: mT5 missing {len(m)} keys ({len(e)} extra)")
return model
-34
View File
@@ -1,34 +0,0 @@
{
"_name_or_path": "hfl/chinese-roberta-wwm-ext-large",
"architectures": [
"BertModel"
],
"attention_probs_dropout_prob": 0.1,
"bos_token_id": 0,
"classifier_dropout": null,
"directionality": "bidi",
"eos_token_id": 2,
"hidden_act": "gelu",
"hidden_dropout_prob": 0.1,
"hidden_size": 1024,
"initializer_range": 0.02,
"intermediate_size": 4096,
"layer_norm_eps": 1e-12,
"max_position_embeddings": 512,
"model_type": "bert",
"num_attention_heads": 16,
"num_hidden_layers": 24,
"output_past": true,
"pad_token_id": 0,
"pooler_fc_size": 768,
"pooler_num_attention_heads": 12,
"pooler_num_fc_layers": 3,
"pooler_size_per_head": 128,
"pooler_type": "first_token_transform",
"position_embedding_type": "absolute",
"torch_dtype": "float32",
"transformers_version": "4.22.1",
"type_vocab_size": 2,
"use_cache": true,
"vocab_size": 47020
}
@@ -1,7 +0,0 @@
{
"cls_token": "[CLS]",
"mask_token": "[MASK]",
"pad_token": "[PAD]",
"sep_token": "[SEP]",
"unk_token": "[UNK]"
}
@@ -1,16 +0,0 @@
{
"cls_token": "[CLS]",
"do_basic_tokenize": true,
"do_lower_case": true,
"mask_token": "[MASK]",
"name_or_path": "hfl/chinese-roberta-wwm-ext",
"never_split": null,
"pad_token": "[PAD]",
"sep_token": "[SEP]",
"special_tokens_map_file": "/home/chenweifeng/.cache/huggingface/hub/models--hfl--chinese-roberta-wwm-ext/snapshots/5c58d0b8ec1d9014354d691c538661bf00bfdb44/special_tokens_map.json",
"strip_accents": null,
"tokenize_chinese_chars": true,
"tokenizer_class": "BertTokenizer",
"unk_token": "[UNK]",
"model_max_length": 77
}
File diff suppressed because it is too large Load Diff
-661
View File
@@ -1,661 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
-140
View File
@@ -1,140 +0,0 @@
"""
List of all PixArt model types / settings
"""
sampling_settings = {
"beta_schedule" : "sqrt_linear",
"linear_start" : 0.0001,
"linear_end" : 0.02,
"timesteps" : 1000,
}
pixart_conf = {
"PixArtMS_XL_2": { # models/PixArtMS
"target": "PixArtMS",
"unet_config": {
"input_size" : 1024//8,
"depth" : 28,
"num_heads" : 16,
"patch_size" : 2,
"hidden_size" : 1152,
"pe_interpolation": 2,
},
"sampling_settings" : sampling_settings,
},
"PixArtMS_Sigma_XL_2": {
"target": "PixArtMSSigma",
"unet_config": {
"input_size" : 1024//8,
"token_num" : 300,
"depth" : 28,
"num_heads" : 16,
"patch_size" : 2,
"hidden_size" : 1152,
"micro_condition": False,
"pe_interpolation": 2,
"model_max_length": 300,
},
"sampling_settings" : sampling_settings,
},
"PixArtMS_Sigma_XL_2_900M": {
"target": "PixArtMSSigma",
"unet_config": {
"input_size": 1024 // 8,
"token_num": 300,
"depth": 42,
"num_heads": 16,
"patch_size": 2,
"hidden_size": 1152,
"micro_condition": False,
"pe_interpolation": 2,
"model_max_length": 300,
},
"sampling_settings": sampling_settings,
},
"PixArtMS_Sigma_XL_2_2K": {
"target": "PixArtMSSigma",
"unet_config": {
"input_size" : 2048//8,
"token_num" : 300,
"depth" : 28,
"num_heads" : 16,
"patch_size" : 2,
"hidden_size" : 1152,
"micro_condition": False,
"pe_interpolation": 4,
"model_max_length": 300,
},
"sampling_settings" : sampling_settings,
},
"PixArt_XL_2": { # models/PixArt
"target": "PixArt",
"unet_config": {
"input_size" : 512//8,
"token_num" : 120,
"depth" : 28,
"num_heads" : 16,
"patch_size" : 2,
"hidden_size" : 1152,
"pe_interpolation": 1,
},
"sampling_settings" : sampling_settings,
},
}
pixart_conf.update({ # controlnet models
"ControlPixArtHalf": {
"target": "ControlPixArtHalf",
"unet_config": pixart_conf["PixArt_XL_2"]["unet_config"],
"sampling_settings": pixart_conf["PixArt_XL_2"]["sampling_settings"],
},
"ControlPixArtMSHalf": {
"target": "ControlPixArtMSHalf",
"unet_config": pixart_conf["PixArtMS_XL_2"]["unet_config"],
"sampling_settings": pixart_conf["PixArtMS_XL_2"]["sampling_settings"],
}
})
pixart_res = {
"PixArtMS_XL_2": { # models/PixArtMS 1024x1024
'0.25': [512, 2048], '0.26': [512, 1984], '0.27': [512, 1920], '0.28': [512, 1856],
'0.32': [576, 1792], '0.33': [576, 1728], '0.35': [576, 1664], '0.40': [640, 1600],
'0.42': [640, 1536], '0.48': [704, 1472], '0.50': [704, 1408], '0.52': [704, 1344],
'0.57': [768, 1344], '0.60': [768, 1280], '0.68': [832, 1216], '0.72': [832, 1152],
'0.78': [896, 1152], '0.82': [896, 1088], '0.88': [960, 1088], '0.94': [960, 1024],
'1.00': [1024,1024], '1.07': [1024, 960], '1.13': [1088, 960], '1.21': [1088, 896],
'1.29': [1152, 896], '1.38': [1152, 832], '1.46': [1216, 832], '1.67': [1280, 768],
'1.75': [1344, 768], '2.00': [1408, 704], '2.09': [1472, 704], '2.40': [1536, 640],
'2.50': [1600, 640], '2.89': [1664, 576], '3.00': [1728, 576], '3.11': [1792, 576],
'3.62': [1856, 512], '3.75': [1920, 512], '3.88': [1984, 512], '4.00': [2048, 512],
},
"PixArt_XL_2": { # models/PixArt 512x512
'0.25': [256,1024], '0.26': [256, 992], '0.27': [256, 960], '0.28': [256, 928],
'0.32': [288, 896], '0.33': [288, 864], '0.35': [288, 832], '0.40': [320, 800],
'0.42': [320, 768], '0.48': [352, 736], '0.50': [352, 704], '0.52': [352, 672],
'0.57': [384, 672], '0.60': [384, 640], '0.68': [416, 608], '0.72': [416, 576],
'0.78': [448, 576], '0.82': [448, 544], '0.88': [480, 544], '0.94': [480, 512],
'1.00': [512, 512], '1.07': [512, 480], '1.13': [544, 480], '1.21': [544, 448],
'1.29': [576, 448], '1.38': [576, 416], '1.46': [608, 416], '1.67': [640, 384],
'1.75': [672, 384], '2.00': [704, 352], '2.09': [736, 352], '2.40': [768, 320],
'2.50': [800, 320], '2.89': [832, 288], '3.00': [864, 288], '3.11': [896, 288],
'3.62': [928, 256], '3.75': [960, 256], '3.88': [992, 256], '4.00': [1024,256]
},
"PixArtMS_Sigma_XL_2_2K": {
'0.25': [1024, 4096], '0.26': [1024, 3968], '0.27': [1024, 3840], '0.28': [1024, 3712],
'0.32': [1152, 3584], '0.33': [1152, 3456], '0.35': [1152, 3328], '0.40': [1280, 3200],
'0.42': [1280, 3072], '0.48': [1408, 2944], '0.50': [1408, 2816], '0.52': [1408, 2688],
'0.57': [1536, 2688], '0.60': [1536, 2560], '0.68': [1664, 2432], '0.72': [1664, 2304],
'0.78': [1792, 2304], '0.82': [1792, 2176], '0.88': [1920, 2176], '0.94': [1920, 2048],
'1.00': [2048, 2048], '1.07': [2048, 1920], '1.13': [2176, 1920], '1.21': [2176, 1792],
'1.29': [2304, 1792], '1.38': [2304, 1664], '1.46': [2432, 1664], '1.67': [2560, 1536],
'1.75': [2688, 1536], '2.00': [2816, 1408], '2.09': [2944, 1408], '2.40': [3072, 1280],
'2.50': [3200, 1280], '2.89': [3328, 1152], '3.00': [3456, 1152], '3.11': [3584, 1152],
'3.62': [3712, 1024], '3.75': [3840, 1024], '3.88': [3968, 1024], '4.00': [4096, 1024]
}
}
# These should be the same
pixart_res.update({
"PixArtMS_Sigma_XL_2": pixart_res["PixArtMS_XL_2"],
"PixArtMS_Sigma_XL_2_512": pixart_res["PixArt_XL_2"],
})
-104
View File
@@ -117,107 +117,3 @@ def convert_state_dict(state_dict):
print(missing)
return new_state_dict
# Same as above but for LoRA weights:
def convert_lora_state_dict(state_dict, peft=True):
# koyha
rep_ak = lambda x: x.replace(".weight", ".lora_down.weight")
rep_bk = lambda x: x.replace(".weight", ".lora_up.weight")
rep_pk = lambda x: x.replace(".weight", ".alpha")
if peft: # peft
rep_ap = lambda x: x.replace(".weight", ".lora_A.weight")
rep_bp = lambda x: x.replace(".weight", ".lora_B.weight")
rep_pp = lambda x: x.replace(".weight", ".alpha")
prefix = find_prefix(state_dict, "adaln_single.linear.lora_A.weight")
state_dict = {k[len(prefix):]:v for k,v in state_dict.items()}
else: # OneTrainer
rep_ap = lambda x: x.replace(".", "_")[:-7] + ".lora_down.weight"
rep_bp = lambda x: x.replace(".", "_")[:-7] + ".lora_up.weight"
rep_pp = lambda x: x.replace(".", "_")[:-7] + ".alpha"
prefix = "lora_transformer_"
t5_marker = "lora_te_encoder"
t5_keys = []
for key in list(state_dict.keys()):
if key.startswith(prefix):
state_dict[key[len(prefix):]] = state_dict.pop(key)
elif t5_marker in key:
t5_keys.append(state_dict.pop(key))
if len(t5_keys) > 0:
print(f"Text Encoder not supported for PixArt LoRA, ignoring {len(t5_keys)} keys")
cmap = []
cmap_unet = get_conversion_map(state_dict) + conversion_map_ms # todo: 512 model
for k, v in cmap_unet:
if v.endswith(".weight"):
cmap.append((rep_ak(k), rep_ap(v)))
cmap.append((rep_bk(k), rep_bp(v)))
if not peft:
cmap.append((rep_pk(k), rep_pp(v)))
missing = [k for k,v in cmap if v not in state_dict]
new_state_dict = {k: state_dict[v] for k,v in cmap if k not in missing}
matched = list(v for k,v in cmap if v in state_dict.keys())
lora_depth = get_lora_depth(state_dict)
for fp, fk in ((rep_ap, rep_ak),(rep_bp, rep_bk)):
for depth in range(lora_depth):
# Self Attention
key = lambda a: fp(f"transformer_blocks.{depth}.attn1.to_{a}.weight")
new_state_dict[fk(f"blocks.{depth}.attn.qkv.weight")] = torch.cat((
state_dict[key('q')], state_dict[key('k')], state_dict[key('v')]
), dim=0)
matched += [key('q'), key('k'), key('v')]
if not peft:
akey = lambda a: rep_pp(f"transformer_blocks.{depth}.attn1.to_{a}.weight")
new_state_dict[rep_pk((f"blocks.{depth}.attn.qkv.weight"))] = state_dict[akey("q")]
matched += [akey('q'), akey('k'), akey('v')]
# Self Attention projection?
key = lambda a: fp(f"transformer_blocks.{depth}.attn1.to_{a}.weight")
new_state_dict[fk(f"blocks.{depth}.attn.proj.weight")] = state_dict[key('out.0')]
matched += [key('out.0')]
# Cross-attention (linear)
key = lambda a: fp(f"transformer_blocks.{depth}.attn2.to_{a}.weight")
new_state_dict[fk(f"blocks.{depth}.cross_attn.q_linear.weight")] = state_dict[key('q')]
new_state_dict[fk(f"blocks.{depth}.cross_attn.kv_linear.weight")] = torch.cat((
state_dict[key('k')], state_dict[key('v')]
), dim=0)
matched += [key('q'), key('k'), key('v')]
if not peft:
akey = lambda a: rep_pp(f"transformer_blocks.{depth}.attn2.to_{a}.weight")
new_state_dict[rep_pk((f"blocks.{depth}.cross_attn.q_linear.weight"))] = state_dict[akey("q")]
new_state_dict[rep_pk((f"blocks.{depth}.cross_attn.kv_linear.weight"))] = state_dict[akey("k")]
matched += [akey('q'), akey('k'), akey('v')]
# Cross Attention projection?
key = lambda a: fp(f"transformer_blocks.{depth}.attn2.to_{a}.weight")
new_state_dict[fk(f"blocks.{depth}.cross_attn.proj.weight")] = state_dict[key('out.0')]
matched += [key('out.0')]
try:
key = fp(f"transformer_blocks.{depth}.ff.net.0.proj.weight")
new_state_dict[fk(f"blocks.{depth}.mlp.fc1.weight")] = state_dict[key]
matched += [key]
except KeyError:
pass
try:
key = fp(f"transformer_blocks.{depth}.ff.net.2.weight")
new_state_dict[fk(f"blocks.{depth}.mlp.fc2.weight")] = state_dict[key]
matched += [key]
except KeyError:
pass
if len(matched) < len(state_dict):
print(f"PixArt: LoRA conversion has leftover keys! ({len(matched)} vs {len(state_dict)})")
print(list( set(state_dict.keys()) - set(matched) ))
if len(missing) > 0:
print(f"PixArt: LoRA conversion has missing keys! (probably)")
print(missing)
return new_state_dict
+93 -118
View File
@@ -1,126 +1,69 @@
import comfy.supported_models_base
import comfy.latent_formats
import comfy.model_patcher
import comfy.model_base
import comfy.utils
import comfy.conds
import torch
import math
from comfy import model_management
from .diffusers_convert import convert_state_dict
import logging
class EXM_PixArt(comfy.supported_models_base.BASE):
import comfy.utils
import comfy.model_base
import comfy.model_detection
import comfy.supported_models_base
import comfy.supported_models
import comfy.latent_formats
from .models.pixart import PixArt
from .models.pixartms import PixArtMS
from .diffusers_convert import convert_state_dict
from ..utils.loader import load_state_dict_from_config
from ..text_encoders.pixart.tenc import PixArtTokenizer, PixArtT5XXL
class PixArtConfig(comfy.supported_models_base.BASE):
unet_class = PixArtMS
unet_config = {}
unet_extra_config = {}
latent_format = comfy.latent_formats.SD15
def __init__(self, model_conf):
self.model_target = model_conf.get("target")
self.unet_config = model_conf.get("unet_config", {})
self.sampling_settings = model_conf.get("sampling_settings", {})
self.latent_format = self.latent_format()
# UNET is handled by extension
self.unet_config["disable_unet_model_creation"] = True
latent_format = comfy.latent_formats.SD15
sampling_settings = {
"beta_schedule" : "sqrt_linear",
"linear_start" : 0.0001,
"linear_end" : 0.02,
"timesteps" : 1000,
}
def model_type(self, state_dict, prefix=""):
return comfy.model_base.ModelType.EPS
class EXM_PixArt_Model(comfy.model_base.BaseModel):
def get_model(self, state_dict, prefix="", device=None):
return PixArtModel(model_config=self, unet_model=self.unet_class, device=device)
def clip_target(self, state_dict={}):
return comfy.supported_models_base.ClipTarget(PixArtTokenizer, PixArtT5XXL)
class PixArtModel(comfy.model_base.BaseModel):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def extra_conds(self, **kwargs):
out = super().extra_conds(**kwargs)
img_hw = kwargs.get("img_hw", None)
if img_hw is not None:
out["img_hw"] = comfy.conds.CONDRegular(torch.tensor(img_hw))
aspect_ratio = kwargs.get("aspect_ratio", None)
if aspect_ratio is not None:
out["aspect_ratio"] = comfy.conds.CONDRegular(torch.tensor(aspect_ratio))
cn_hint = kwargs.get("cn_hint", None)
if cn_hint is not None:
out["cn_hint"] = comfy.conds.CONDRegular(cn_hint)
return out
def load_pixart(model_path, model_conf=None):
state_dict = comfy.utils.load_torch_file(model_path)
state_dict = state_dict.get("model", state_dict)
def load_pixart_state_dict(sd, model_options={}):
# prefix / format
sd = sd.get("model", sd) # ref ckpt
diffusion_model_prefix = comfy.model_detection.unet_prefix_from_state_dict(sd)
temp_sd = comfy.utils.state_dict_prefix_replace(sd, {diffusion_model_prefix: ""}, filter_keys=True)
if len(temp_sd) > 0:
sd = temp_sd
# prefix
for prefix in ["model.diffusion_model.",]:
if any(True for x in state_dict if x.startswith(prefix)):
state_dict = {k[len(prefix):]:v for k,v in state_dict.items()}
# diffusers convert
if "adaln_single.linear.weight" in sd:
sd = convert_state_dict(sd)
# diffusers
if "adaln_single.linear.weight" in state_dict:
state_dict = convert_state_dict(state_dict) # Diffusers
# model config
model_config = model_config_from_unet(sd)
return load_state_dict_from_config(model_config, sd, model_options)
# guess auto config
if model_conf is None:
model_conf = guess_pixart_config(state_dict)
parameters = comfy.utils.calculate_parameters(state_dict)
unet_dtype = model_management.unet_dtype(model_params=parameters)
load_device = comfy.model_management.get_torch_device()
offload_device = comfy.model_management.unet_offload_device()
# ignore fp8/etc and use directly for now
manual_cast_dtype = model_management.unet_manual_cast(unet_dtype, load_device)
if manual_cast_dtype:
print(f"PixArt: falling back to {manual_cast_dtype}")
unet_dtype = manual_cast_dtype
model_conf = EXM_PixArt(model_conf) # convert to object
model = EXM_PixArt_Model( # same as comfy.model_base.BaseModel
model_conf,
model_type=comfy.model_base.ModelType.EPS,
device=model_management.get_torch_device()
)
if model_conf.model_target == "PixArtMS":
from .models.PixArtMS import PixArtMS
model.diffusion_model = PixArtMS(**model_conf.unet_config)
elif model_conf.model_target == "PixArt":
from .models.PixArt import PixArt
model.diffusion_model = PixArt(**model_conf.unet_config)
elif model_conf.model_target == "PixArtMSSigma":
from .models.PixArtMS import PixArtMS
model.diffusion_model = PixArtMS(**model_conf.unet_config)
model.latent_format = comfy.latent_formats.SDXL()
elif model_conf.model_target == "ControlPixArtMSHalf":
from .models.PixArtMS import PixArtMS
from .models.pixart_controlnet import ControlPixArtMSHalf
model.diffusion_model = PixArtMS(**model_conf.unet_config)
model.diffusion_model = ControlPixArtMSHalf(model.diffusion_model)
elif model_conf.model_target == "ControlPixArtHalf":
from .models.PixArt import PixArt
from .models.pixart_controlnet import ControlPixArtHalf
model.diffusion_model = PixArt(**model_conf.unet_config)
model.diffusion_model = ControlPixArtHalf(model.diffusion_model)
else:
raise NotImplementedError(f"Unknown model target '{model_conf.model_target}'")
m, u = model.diffusion_model.load_state_dict(state_dict, strict=False)
if len(m) > 0: print("Missing UNET keys", m)
if len(u) > 0: print("Leftover UNET keys", u)
model.diffusion_model.dtype = unet_dtype
model.diffusion_model.eval()
model.diffusion_model.to(unet_dtype)
model_patcher = comfy.model_patcher.ModelPatcher(
model,
load_device = load_device,
offload_device = offload_device,
)
return model_patcher
def guess_pixart_config(sd):
def model_config_from_unet(sd):
"""
Guess config based on converted state dict.
Guess config based on (converted) state dict.
"""
# Shared settings based on DiT_XL_2 - could be enumerated
config = {
@@ -141,40 +84,72 @@ def guess_pixart_config(sd):
config["input_size"] = int(math.sqrt(sd["pos_embed"].shape[1])) * config["patch_size"]
config["pe_interpolation"] = config["input_size"] // (512//8) # dumb guess
target_arch = "PixArtMS"
model_config = PixArtModel
if config["model_max_length"] == 300:
# Sigma
target_arch = "PixArtMSSigma"
model_class = PixArtMS
model_config.latent_format = comfy.latent_formats.SDXL
config["micro_condition"] = False
if "input_size" not in config:
# The diffusers weights for 1K/2K are exactly the same...?
# replace patch embed logic with HyDiT?
print(f"PixArt: diffusers weights - 2K model will be broken, use manual loading!")
logging.warn(f"PixArt: diffusers weights - 2K model will be broken, use manual loading!")
config["input_size"] = 1024//8
else:
# Alpha
if "csize_embedder.mlp.0.weight" in sd:
# MS (microconds)
target_arch = "PixArtMS"
model_class = PixArtMS
config["micro_condition"] = True
if "input_size" not in config:
config["input_size"] = 1024//8
config["pe_interpolation"] = 2
else:
# PixArt
target_arch = "PixArt"
model_class = PixArt
if "input_size" not in config:
config["input_size"] = 512//8
config["pe_interpolation"] = 1
model_config = PixArtConfig(config)
model_config.unet_class = model_class
logging.debug(f"PixArt config: {model_class}\n{config}")
return model_config
print("PixArt guessed config:", target_arch, config)
return {
"target": target_arch,
"unet_config": config,
"sampling_settings": {
"beta_schedule" : "sqrt_linear",
"linear_start" : 0.0001,
"linear_end" : 0.02,
"timesteps" : 1000,
}
resolutions = {
"PixArt 512": {
0.25: [256,1024], 0.26: [256, 992], 0.27: [256, 960], 0.28: [256, 928],
0.32: [288, 896], 0.33: [288, 864], 0.35: [288, 832], 0.40: [320, 800],
0.42: [320, 768], 0.48: [352, 736], 0.50: [352, 704], 0.52: [352, 672],
0.57: [384, 672], 0.60: [384, 640], 0.68: [416, 608], 0.72: [416, 576],
0.78: [448, 576], 0.82: [448, 544], 0.88: [480, 544], 0.94: [480, 512],
1.00: [512, 512], 1.07: [512, 480], 1.13: [544, 480], 1.21: [544, 448],
1.29: [576, 448], 1.38: [576, 416], 1.46: [608, 416], 1.67: [640, 384],
1.75: [672, 384], 2.00: [704, 352], 2.09: [736, 352], 2.40: [768, 320],
2.50: [800, 320], 2.89: [832, 288], 3.00: [864, 288], 3.11: [896, 288],
3.62: [928, 256], 3.75: [960, 256], 3.88: [992, 256], 4.00: [1024,256]
},
"PixArt 1024": {
0.25: [512, 2048], 0.26: [512, 1984], 0.27: [512, 1920], 0.28: [512, 1856],
0.32: [576, 1792], 0.33: [576, 1728], 0.35: [576, 1664], 0.40: [640, 1600],
0.42: [640, 1536], 0.48: [704, 1472], 0.50: [704, 1408], 0.52: [704, 1344],
0.57: [768, 1344], 0.60: [768, 1280], 0.68: [832, 1216], 0.72: [832, 1152],
0.78: [896, 1152], 0.82: [896, 1088], 0.88: [960, 1088], 0.94: [960, 1024],
1.00: [1024,1024], 1.07: [1024, 960], 1.13: [1088, 960], 1.21: [1088, 896],
1.29: [1152, 896], 1.38: [1152, 832], 1.46: [1216, 832], 1.67: [1280, 768],
1.75: [1344, 768], 2.00: [1408, 704], 2.09: [1472, 704], 2.40: [1536, 640],
2.50: [1600, 640], 2.89: [1664, 576], 3.00: [1728, 576], 3.11: [1792, 576],
3.62: [1856, 512], 3.75: [1920, 512], 3.88: [1984, 512], 4.00: [2048, 512],
},
"PixArt 2K": {
0.25: [1024, 4096], 0.26: [1024, 3968], 0.27: [1024, 3840], 0.28: [1024, 3712],
0.32: [1152, 3584], 0.33: [1152, 3456], 0.35: [1152, 3328], 0.40: [1280, 3200],
0.42: [1280, 3072], 0.48: [1408, 2944], 0.50: [1408, 2816], 0.52: [1408, 2688],
0.57: [1536, 2688], 0.60: [1536, 2560], 0.68: [1664, 2432], 0.72: [1664, 2304],
0.78: [1792, 2304], 0.82: [1792, 2176], 0.88: [1920, 2176], 0.94: [1920, 2048],
1.00: [2048, 2048], 1.07: [2048, 1920], 1.13: [2176, 1920], 1.21: [2176, 1792],
1.29: [2304, 1792], 1.38: [2304, 1664], 1.46: [2432, 1664], 1.67: [2560, 1536],
1.75: [2688, 1536], 2.00: [2816, 1408], 2.09: [2944, 1408], 2.40: [3072, 1280],
2.50: [3200, 1280], 2.89: [3328, 1152], 3.00: [3456, 1152], 3.11: [3584, 1152],
3.62: [3712, 1024], 3.75: [3840, 1024], 3.88: [3968, 1024], 4.00: [4096, 1024]
}
}
-146
View File
@@ -1,146 +0,0 @@
import os
import copy
import json
import torch
import comfy.lora
import comfy.model_management
from comfy.model_patcher import ModelPatcher
from .diffusers_convert import convert_lora_state_dict
class EXM_PixArt_ModelPatcher(ModelPatcher):
def calculate_weight(self, patches, weight, key):
"""
This is almost the same as the comfy function, but stripped down to just the LoRA patch code.
The problem with the original code is the q/k/v keys being combined into one for the attention.
In the diffusers code, they're treated as separate keys, but in the reference code they're recombined (q+kv|qkv).
This means, for example, that the [1152,1152] weights become [3456,1152] in the state dict.
The issue with this is that the LoRA weights are [128,1152],[1152,128] and become [384,1162],[3456,128] instead.
This is the best thing I could think of that would fix that, but it's very fragile.
- Check key shape to determine if it needs the fallback logic
- Cut the input into parts based on the shape (undoing the torch.cat)
- Do the matrix multiplication logic
- Recombine them to match the expected shape
"""
for p in patches:
alpha = p[0]
v = p[1]
strength_model = p[2]
if strength_model != 1.0:
weight *= strength_model
if isinstance(v, list):
v = (self.calculate_weight(v[1:], v[0].clone(), key), )
if len(v) == 2:
patch_type = v[0]
v = v[1]
if patch_type == "lora":
mat1 = comfy.model_management.cast_to_device(v[0], weight.device, torch.float32)
mat2 = comfy.model_management.cast_to_device(v[1], weight.device, torch.float32)
if v[2] is not None:
alpha *= v[2] / mat2.shape[0]
try:
mat1 = mat1.flatten(start_dim=1)
mat2 = mat2.flatten(start_dim=1)
ch1 = mat1.shape[0] // mat2.shape[1]
ch2 = mat2.shape[0] // mat1.shape[1]
### Fallback logic for shape mismatch ###
if mat1.shape[0] != mat2.shape[1] and ch1 == ch2 and (mat1.shape[0]/mat2.shape[1])%1 == 0:
mat1 = mat1.chunk(ch1, dim=0)
mat2 = mat2.chunk(ch1, dim=0)
weight += torch.cat(
[alpha * torch.mm(mat1[x], mat2[x]) for x in range(ch1)],
dim=0,
).reshape(weight.shape).type(weight.dtype)
else:
weight += (alpha * torch.mm(mat1, mat2)).reshape(weight.shape).type(weight.dtype)
except Exception as e:
print("ERROR", key, e)
return weight
def clone(self):
n = EXM_PixArt_ModelPatcher(self.model, self.load_device, self.offload_device, self.size, self.current_device, weight_inplace_update=self.weight_inplace_update)
n.patches = {}
for k in self.patches:
n.patches[k] = self.patches[k][:]
n.object_patches = self.object_patches.copy()
n.model_options = copy.deepcopy(self.model_options)
n.model_keys = self.model_keys
return n
def replace_model_patcher(model):
n = EXM_PixArt_ModelPatcher(
model = model.model,
size = model.size,
load_device = model.load_device,
offload_device = model.offload_device,
weight_inplace_update = model.weight_inplace_update,
)
n.patches = {}
for k in model.patches:
n.patches[k] = model.patches[k][:]
n.object_patches = model.object_patches.copy()
n.model_options = copy.deepcopy(model.model_options)
return n
def find_peft_alpha(path):
def load_json(json_path):
with open(json_path) as f:
data = json.load(f)
alpha = data.get("lora_alpha")
alpha = alpha or data.get("alpha")
if not alpha:
print(" Found config but `lora_alpha` is missing!")
else:
print(f" Found config at {json_path} [alpha:{alpha}]")
return alpha
# For some weird reason peft doesn't include the alpha in the actual model
print("PixArt: Warning! This is a PEFT LoRA. Trying to find config...")
files = [
f"{os.path.splitext(path)[0]}.json",
f"{os.path.splitext(path)[0]}.config.json",
os.path.join(os.path.dirname(path),"adapter_config.json"),
]
for file in files:
if os.path.isfile(file):
return load_json(file)
print(" Missing config/alpha! assuming alpha of 8. Consider converting it/adding a config json to it.")
return 8.0
def load_pixart_lora(model, lora, lora_path, strength):
k_back = lambda x: x.replace(".lora_up.weight", "")
# need to convert the actual weights for this to work.
if any(True for x in lora.keys() if x.endswith("adaln_single.linear.lora_A.weight")):
lora = convert_lora_state_dict(lora, peft=True)
alpha = find_peft_alpha(lora_path)
lora.update({f"{k_back(x)}.alpha":torch.tensor(alpha) for x in lora.keys() if "lora_up" in x})
else: # OneTrainer
lora = convert_lora_state_dict(lora, peft=False)
key_map = {k_back(x):f"diffusion_model.{k_back(x)}.weight" for x in lora.keys() if "lora_up" in x} # fake
loaded = comfy.lora.load_lora(lora, key_map)
if model is not None:
# switch to custom model patcher when using LoRAs
if isinstance(model, EXM_PixArt_ModelPatcher):
new_modelpatcher = model.clone()
else:
new_modelpatcher = replace_model_patcher(model)
k = new_modelpatcher.add_patches(loaded, strength)
else:
k = ()
new_modelpatcher = None
k = set(k)
for x in loaded:
if (x not in k):
print("NOT LOADED", x)
return new_modelpatcher
+1 -1
View File
@@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Copyright 2024 Junsong Chen, Jincheng Yu, Enze Xie
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
View File
@@ -12,9 +12,11 @@ import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.models.vision_transformer import Mlp, Attention as Attention_
from einops import rearrange
import comfy.ldm.common_dit
from .utils import to_2tuple
sdpa_32b = None
Q_4GB_LIMIT = 32000000
"""If q is greater than this, the operation will likely require >4GB VRAM, which will fail on Intel Arc Alchemist GPUs without a workaround."""
@@ -24,11 +26,14 @@ Q_4GB_LIMIT = 32000000
from comfy import model_management
if model_management.xformers_enabled():
import xformers
import xformers.ops
if int((xformers.__version__).split(".")[2]) >= 28:
block_diagonal_mask_from_seqlens = xformers.ops.fmha.attn_bias.BlockDiagonalMask.from_seqlens
else:
block_diagonal_mask_from_seqlens = xformers.ops.fmha.BlockDiagonalMask.from_seqlens
else:
if model_management.xpu_available:
import intel_extension_for_pytorch as ipex
import intel_extension_for_pytorch as ipex # type: ignore
import os
if not torch.xpu.has_fp64_dtype() and not os.environ.get('IPEX_FORCE_ATTENTION_SLICE', None):
from ...utils.IPEX.attention import scaled_dot_product_attention_32_bit
@@ -44,7 +49,7 @@ def t2i_modulate(x, shift, scale):
return x * (1 + scale) + shift
class MultiHeadCrossAttention(nn.Module):
def __init__(self, d_model, num_heads, attn_drop=0., proj_drop=0., **block_kwargs):
def __init__(self, d_model, num_heads, attn_drop=0., proj_drop=0., dtype=None, device=None, operations=None, **block_kwargs):
super(MultiHeadCrossAttention, self).__init__()
assert d_model % num_heads == 0, "d_model must be divisible by num_heads"
@@ -52,10 +57,10 @@ class MultiHeadCrossAttention(nn.Module):
self.num_heads = num_heads
self.head_dim = d_model // num_heads
self.q_linear = nn.Linear(d_model, d_model)
self.kv_linear = nn.Linear(d_model, d_model*2)
self.q_linear = operations.Linear(d_model, d_model, dtype=dtype, device=device)
self.kv_linear = operations.Linear(d_model, d_model*2, dtype=dtype, device=device)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(d_model, d_model)
self.proj = operations.Linear(d_model, d_model, dtype=dtype, device=device)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x, cond, mask=None):
@@ -69,7 +74,7 @@ class MultiHeadCrossAttention(nn.Module):
if model_management.xformers_enabled():
attn_bias = None
if mask is not None:
attn_bias = xformers.ops.fmha.BlockDiagonalMask.from_seqlens([N] * B, mask)
attn_bias = block_diagonal_mask_from_seqlens([N] * B, mask)
x = xformers.ops.memory_efficient_attention(
q, k, v,
p=self.attn_drop.p,
@@ -111,7 +116,7 @@ class MultiHeadCrossAttention(nn.Module):
return x
class AttentionKVCompress(Attention_):
class AttentionKVCompress(nn.Module):
"""Multi-head Attention block with KV token compression and qk norm."""
def __init__(
@@ -122,6 +127,9 @@ class AttentionKVCompress(Attention_):
sampling='conv',
sr_ratio=1,
qk_norm=False,
dtype=None,
device=None,
operations=None,
**block_kwargs,
):
"""
@@ -130,19 +138,26 @@ class AttentionKVCompress(Attention_):
num_heads (int): Number of attention heads.
qkv_bias (bool: If True, add a learnable bias to query, key, value.
"""
super().__init__(dim, num_heads=num_heads, qkv_bias=qkv_bias, **block_kwargs)
super().__init__()
assert dim % num_heads == 0, 'dim should be divisible by num_heads'
self.num_heads = num_heads
self.head_dim = dim // num_heads
self.scale = self.head_dim ** -0.5
self.qkv = operations.Linear(dim, dim * 3, bias=qkv_bias, dtype=dtype, device=device)
self.proj = operations.Linear(dim, dim, dtype=dtype, device=device)
self.sampling=sampling # ['conv', 'ave', 'uniform', 'uniform_every']
self.sr_ratio = sr_ratio
if sr_ratio > 1 and sampling == 'conv':
# Avg Conv Init.
self.sr = nn.Conv2d(dim, dim, groups=dim, kernel_size=sr_ratio, stride=sr_ratio)
self.sr.weight.data.fill_(1/sr_ratio**2)
self.sr.bias.data.zero_()
self.norm = nn.LayerNorm(dim)
self.sr = operations.Conv2d(dim, dim, groups=dim, kernel_size=sr_ratio, stride=sr_ratio, dtype=dtype, device=device)
# self.sr.weight.data.fill_(1/sr_ratio**2)
# self.sr.bias.data.zero_()
self.norm = operations.LayerNorm(dim, dtype=dtype, device=device)
if qk_norm:
self.q_norm = nn.LayerNorm(dim)
self.k_norm = nn.LayerNorm(dim)
self.q_norm = operations.LayerNorm(dim, dtype=dtype, device=device)
self.k_norm = operations.LayerNorm(dim, dtype=dtype, device=device)
else:
self.q_norm = nn.Identity()
self.k_norm = nn.Identity()
@@ -204,14 +219,12 @@ class AttentionKVCompress(Attention_):
if model_management.xformers_enabled():
x = xformers.ops.memory_efficient_attention(
q, k, v,
p=self.attn_drop.p,
p=0,
attn_bias=attn_bias
)
else:
q, k, v = map(lambda t: t.transpose(1, 2),(q, k, v),)
p = getattr(self.attn_drop, "p", 0) # IPEX.optimize() will turn attn_drop into an Identity()
p = 0
if sdpa_32b is not None and (q.element_size() * q.nelement()) > Q_4GB_LIMIT:
sdpa = sdpa_32b
else:
@@ -224,30 +237,6 @@ class AttentionKVCompress(Attention_):
).transpose(1, 2).contiguous()
x = x.view(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
#################################################################################
# AMP attention with fp32 softmax to fix loss NaN problem during training #
#################################################################################
class Attention(Attention_):
def forward(self, x):
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
use_fp32_attention = getattr(self, 'fp32_attention', False)
if use_fp32_attention:
q, k = q.float(), k.float()
with torch.cuda.amp.autocast(enabled=not use_fp32_attention):
attn = (q @ k.transpose(-2, -1)) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
@@ -256,13 +245,13 @@ class FinalLayer(nn.Module):
The final layer of PixArt.
"""
def __init__(self, hidden_size, patch_size, out_channels):
def __init__(self, hidden_size, patch_size, out_channels, dtype=None, device=None, operations=None):
super().__init__()
self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
self.norm_final = operations.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
self.linear = operations.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True, dtype=dtype, device=device)
self.adaLN_modulation = nn.Sequential(
nn.SiLU(),
nn.Linear(hidden_size, 2 * hidden_size, bias=True)
operations.Linear(hidden_size, 2 * hidden_size, bias=True, dtype=dtype, device=device)
)
def forward(self, x, c):
@@ -271,23 +260,23 @@ class FinalLayer(nn.Module):
x = self.linear(x)
return x
class T2IFinalLayer(nn.Module):
"""
The final layer of PixArt.
"""
def __init__(self, hidden_size, patch_size, out_channels):
def __init__(self, hidden_size, patch_size, out_channels, dtype=None, device=None, operations=None):
super().__init__()
self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
self.norm_final = operations.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
self.linear = operations.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True, dtype=dtype, device=device)
self.scale_shift_table = nn.Parameter(torch.randn(2, hidden_size) / hidden_size ** 0.5)
self.out_channels = out_channels
def forward(self, x, t):
dtype = x.dtype
shift, scale = (self.scale_shift_table[None] + t[:, None]).chunk(2, dim=1)
x = t2i_modulate(self.norm_final(x), shift, scale)
x = self.linear(x)
x = self.linear(x.to(dtype))
return x
@@ -296,13 +285,13 @@ class MaskFinalLayer(nn.Module):
The final layer of PixArt.
"""
def __init__(self, final_hidden_size, c_emb_size, patch_size, out_channels):
def __init__(self, final_hidden_size, c_emb_size, patch_size, out_channels, dtype=None, device=None, operations=None):
super().__init__()
self.norm_final = nn.LayerNorm(final_hidden_size, elementwise_affine=False, eps=1e-6)
self.linear = nn.Linear(final_hidden_size, patch_size * patch_size * out_channels, bias=True)
self.norm_final = operations.LayerNorm(final_hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
self.linear = operations.Linear(final_hidden_size, patch_size * patch_size * out_channels, bias=True, dtype=dtype, device=device)
self.adaLN_modulation = nn.Sequential(
nn.SiLU(),
nn.Linear(c_emb_size, 2 * final_hidden_size, bias=True)
operations.Linear(c_emb_size, 2 * final_hidden_size, bias=True, dtype=dtype, device=device)
)
def forward(self, x, t):
shift, scale = self.adaLN_modulation(t).chunk(2, dim=1)
@@ -316,13 +305,13 @@ class DecoderLayer(nn.Module):
The final layer of PixArt.
"""
def __init__(self, hidden_size, decoder_hidden_size):
def __init__(self, hidden_size, decoder_hidden_size, dtype=None, device=None, operations=None):
super().__init__()
self.norm_decoder = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
self.linear = nn.Linear(hidden_size, decoder_hidden_size, bias=True)
self.norm_decoder = operations.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
self.linear = operations.Linear(hidden_size, decoder_hidden_size, bias=True, dtype=dtype, device=device)
self.adaLN_modulation = nn.Sequential(
nn.SiLU(),
nn.Linear(hidden_size, 2 * hidden_size, bias=True)
operations.Linear(hidden_size, 2 * hidden_size, bias=True, dtype=dtype, device=device)
)
def forward(self, x, t):
shift, scale = self.adaLN_modulation(t).chunk(2, dim=1)
@@ -339,12 +328,12 @@ class TimestepEmbedder(nn.Module):
Embeds scalar timesteps into vector representations.
"""
def __init__(self, hidden_size, frequency_embedding_size=256):
def __init__(self, hidden_size, frequency_embedding_size=256, dtype=None, device=None, operations=None):
super().__init__()
self.mlp = nn.Sequential(
nn.Linear(frequency_embedding_size, hidden_size, bias=True),
operations.Linear(frequency_embedding_size, hidden_size, bias=True, dtype=dtype, device=device),
nn.SiLU(),
nn.Linear(hidden_size, hidden_size, bias=True),
operations.Linear(hidden_size, hidden_size, bias=True, dtype=dtype, device=device),
)
self.frequency_embedding_size = frequency_embedding_size
@@ -368,9 +357,9 @@ class TimestepEmbedder(nn.Module):
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
return embedding
def forward(self, t):
def forward(self, t, dtype):
t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
t_emb = self.mlp(t_freq.to(t.dtype))
t_emb = self.mlp(t_freq.to(dtype))
return t_emb
@@ -379,12 +368,12 @@ class SizeEmbedder(TimestepEmbedder):
Embeds scalar timesteps into vector representations.
"""
def __init__(self, hidden_size, frequency_embedding_size=256):
super().__init__(hidden_size=hidden_size, frequency_embedding_size=frequency_embedding_size)
def __init__(self, hidden_size, frequency_embedding_size=256, dtype=None, device=None, operations=None):
super().__init__(hidden_size=hidden_size, frequency_embedding_size=frequency_embedding_size, operations=operations)
self.mlp = nn.Sequential(
nn.Linear(frequency_embedding_size, hidden_size, bias=True),
operations.Linear(frequency_embedding_size, hidden_size, bias=True, dtype=dtype, device=device),
nn.SiLU(),
nn.Linear(hidden_size, hidden_size, bias=True),
operations.Linear(hidden_size, hidden_size, bias=True, dtype=dtype, device=device),
)
self.frequency_embedding_size = frequency_embedding_size
self.outdim = hidden_size
@@ -409,10 +398,10 @@ class LabelEmbedder(nn.Module):
Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance.
"""
def __init__(self, num_classes, hidden_size, dropout_prob):
def __init__(self, num_classes, hidden_size, dropout_prob, dtype=None, device=None, operations=None):
super().__init__()
use_cfg_embedding = dropout_prob > 0
self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size)
self.embedding_table = operations.Embedding(num_classes + use_cfg_embedding, hidden_size, dtype=dtype, device=device),
self.num_classes = num_classes
self.dropout_prob = dropout_prob
@@ -435,14 +424,35 @@ class LabelEmbedder(nn.Module):
return embeddings
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, bias=True, drop=None, dtype=None, device=None, operations=None) -> None:
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = operations.Linear(in_features, hidden_features, bias=bias, dtype=dtype, device=device)
self.act = act_layer()
self.fc2 = operations.Linear(hidden_features, out_features, bias=bias, dtype=dtype, device=device)
self.drop1 = nn.Identity()
self.drop2 = nn.Identity()
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.act(self.fc1(x))
return self.fc2(x)
class CaptionEmbedder(nn.Module):
"""
Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance.
"""
def __init__(self, in_channels, hidden_size, uncond_prob, act_layer=nn.GELU(approximate='tanh'), token_num=120):
def __init__(self, in_channels, hidden_size, uncond_prob, act_layer=nn.GELU(approximate='tanh'), token_num=120, dtype=None, device=None, operations=None):
super().__init__()
self.y_proj = Mlp(in_features=in_channels, hidden_features=hidden_size, out_features=hidden_size, act_layer=act_layer, drop=0)
self.y_proj = Mlp(
in_features=in_channels, hidden_features=hidden_size, out_features=hidden_size, act_layer=act_layer,
dtype=dtype, device=device, operations=operations,
)
self.register_buffer("y_embedding", nn.Parameter(torch.randn(token_num, in_channels) / in_channels ** 0.5))
self.uncond_prob = uncond_prob
@@ -472,9 +482,12 @@ class CaptionEmbedderDoubleBr(nn.Module):
Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance.
"""
def __init__(self, in_channels, hidden_size, uncond_prob, act_layer=nn.GELU(approximate='tanh'), token_num=120):
def __init__(self, in_channels, hidden_size, uncond_prob, act_layer=nn.GELU(approximate='tanh'), token_num=120, dtype=None, device=None, operations=None):
super().__init__()
self.proj = Mlp(in_features=in_channels, hidden_features=hidden_size, out_features=hidden_size, act_layer=act_layer, drop=0)
self.proj = Mlp(
in_features=in_channels, hidden_features=hidden_size, out_features=hidden_size, act_layer=act_layer,
dtype=dtype, device=device, operations=operations,
)
self.embedding = nn.Parameter(torch.randn(1, in_channels) / 10 ** 0.5)
self.y_embedding = nn.Parameter(torch.randn(token_num, in_channels) / 10 ** 0.5)
self.uncond_prob = uncond_prob
@@ -8,17 +8,23 @@
# GLIDE: https://github.com/openai/glide-text2im
# MAE: https://github.com/facebookresearch/mae/blob/main/models_mae.py
# --------------------------------------------------------
import math
import torch
import torch.nn as nn
import os
import numpy as np
from timm.models.layers import DropPath
from timm.models.vision_transformer import PatchEmbed, Mlp
from .utils import auto_grad_checkpoint, to_2tuple
from .PixArt_blocks import t2i_modulate, CaptionEmbedder, AttentionKVCompress, MultiHeadCrossAttention, T2IFinalLayer, TimestepEmbedder, LabelEmbedder, FinalLayer
from .blocks import (
t2i_modulate,
CaptionEmbedder,
AttentionKVCompress,
MultiHeadCrossAttention,
T2IFinalLayer,
TimestepEmbedder,
LabelEmbedder,
FinalLayer,
Mlp
)
from comfy.ldm.modules.diffusionmodules.mmdit import PatchEmbed
class PixArtBlock(nn.Module):
@@ -37,7 +43,7 @@ class PixArtBlock(nn.Module):
# to be compatible with lower version pytorch
approx_gelu = lambda: nn.GELU(approximate="tanh")
self.mlp = Mlp(in_features=hidden_size, hidden_features=int(hidden_size * mlp_ratio), act_layer=approx_gelu, drop=0)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.drop_path = nn.Identity() #DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.scale_shift_table = nn.Parameter(torch.randn(6, hidden_size) / hidden_size ** 0.5)
self.sampling = sampling
self.sr_ratio = sr_ratio
-312
View File
@@ -1,312 +0,0 @@
import re
import torch
import torch.nn as nn
from copy import deepcopy
from torch import Tensor
from torch.nn import Module, Linear, init
from typing import Any, Mapping
from .PixArt import PixArt, get_2d_sincos_pos_embed
from .PixArtMS import PixArtMSBlock, PixArtMS
from .utils import auto_grad_checkpoint
# The implementation of ControlNet-Half architrecture
# https://github.com/lllyasviel/ControlNet/discussions/188
class ControlT2IDitBlockHalf(Module):
def __init__(self, base_block: PixArtMSBlock, block_index: 0) -> None:
super().__init__()
self.copied_block = deepcopy(base_block)
self.block_index = block_index
for p in self.copied_block.parameters():
p.requires_grad_(True)
self.copied_block.load_state_dict(base_block.state_dict())
self.copied_block.train()
self.hidden_size = hidden_size = base_block.hidden_size
if self.block_index == 0:
self.before_proj = Linear(hidden_size, hidden_size)
init.zeros_(self.before_proj.weight)
init.zeros_(self.before_proj.bias)
self.after_proj = Linear(hidden_size, hidden_size)
init.zeros_(self.after_proj.weight)
init.zeros_(self.after_proj.bias)
def forward(self, x, y, t, mask=None, c=None):
if self.block_index == 0:
# the first block
c = self.before_proj(c)
c = self.copied_block(x + c, y, t, mask)
c_skip = self.after_proj(c)
else:
# load from previous c and produce the c for skip connection
c = self.copied_block(c, y, t, mask)
c_skip = self.after_proj(c)
return c, c_skip
# The implementation of ControlPixArtHalf net
class ControlPixArtHalf(Module):
# only support single res model
def __init__(self, base_model: PixArt, copy_blocks_num: int = 13) -> None:
super().__init__()
self.dtype = torch.get_default_dtype()
self.base_model = base_model.eval()
self.controlnet = []
self.copy_blocks_num = copy_blocks_num
self.total_blocks_num = len(base_model.blocks)
for p in self.base_model.parameters():
p.requires_grad_(False)
# Copy first copy_blocks_num block
for i in range(copy_blocks_num):
self.controlnet.append(ControlT2IDitBlockHalf(base_model.blocks[i], i))
self.controlnet = nn.ModuleList(self.controlnet)
def __getattr__(self, name: str) -> Tensor or Module:
if name in ['forward', 'forward_with_dpmsolver', 'forward_with_cfg', 'forward_c', 'load_state_dict']:
return self.__dict__[name]
elif name in ['base_model', 'controlnet']:
return super().__getattr__(name)
else:
return getattr(self.base_model, name)
def forward_c(self, c):
self.h, self.w = c.shape[-2]//self.patch_size, c.shape[-1]//self.patch_size
pos_embed = torch.from_numpy(get_2d_sincos_pos_embed(self.pos_embed.shape[-1], (self.h, self.w), lewei_scale=self.lewei_scale, base_size=self.base_size)).unsqueeze(0).to(c.device).to(self.dtype)
return self.x_embedder(c) + pos_embed if c is not None else c
# def forward(self, x, t, c, **kwargs):
# return self.base_model(x, t, c=self.forward_c(c), **kwargs)
def forward_raw(self, x, timestep, y, mask=None, data_info=None, c=None, **kwargs):
# modify the original PixArtMS forward function
if c is not None:
c = c.to(self.dtype)
c = self.forward_c(c)
"""
Forward pass of PixArt.
x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images)
t: (N,) tensor of diffusion timesteps
y: (N, 1, 120, C) tensor of class labels
"""
x = x.to(self.dtype)
timestep = timestep.to(self.dtype)
y = y.to(self.dtype)
pos_embed = self.pos_embed.to(self.dtype)
self.h, self.w = x.shape[-2]//self.patch_size, x.shape[-1]//self.patch_size
x = self.x_embedder(x) + pos_embed # (N, T, D), where T = H * W / patch_size ** 2
t = self.t_embedder(timestep.to(x.dtype)) # (N, D)
t0 = self.t_block(t)
y = self.y_embedder(y, self.training) # (N, 1, L, D)
if mask is not None:
if mask.shape[0] != y.shape[0]:
mask = mask.repeat(y.shape[0] // mask.shape[0], 1)
mask = mask.squeeze(1).squeeze(1)
y = y.squeeze(1).masked_select(mask.unsqueeze(-1) != 0).view(1, -1, x.shape[-1])
y_lens = mask.sum(dim=1).tolist()
else:
y_lens = [y.shape[2]] * y.shape[0]
y = y.squeeze(1).view(1, -1, x.shape[-1])
# define the first layer
x = auto_grad_checkpoint(self.base_model.blocks[0], x, y, t0, y_lens, **kwargs) # (N, T, D) #support grad checkpoint
if c is not None:
# update c
for index in range(1, self.copy_blocks_num + 1):
c, c_skip = auto_grad_checkpoint(self.controlnet[index - 1], x, y, t0, y_lens, c, **kwargs)
x = auto_grad_checkpoint(self.base_model.blocks[index], x + c_skip, y, t0, y_lens, **kwargs)
# update x
for index in range(self.copy_blocks_num + 1, self.total_blocks_num):
x = auto_grad_checkpoint(self.base_model.blocks[index], x, y, t0, y_lens, **kwargs)
else:
for index in range(1, self.total_blocks_num):
x = auto_grad_checkpoint(self.base_model.blocks[index], x, y, t0, y_lens, **kwargs)
x = self.final_layer(x, t) # (N, T, patch_size ** 2 * out_channels)
x = self.unpatchify(x) # (N, out_channels, H, W)
return x
def forward(self, x, timesteps, context, cn_hint=None, **kwargs):
"""
Forward pass that adapts comfy input to original forward function
x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images)
timesteps: (N,) tensor of diffusion timesteps
context: (N, 1, 120, C) conditioning
cn_hint: controlnet hint
"""
## Still accepts the input w/o that dim but returns garbage
if len(context.shape) == 3:
context = context.unsqueeze(1)
## run original forward pass
out = self.forward_raw(
x = x.to(self.dtype),
timestep = timesteps.to(self.dtype),
y = context.to(self.dtype),
c = cn_hint,
)
## only return EPS
out = out.to(torch.float)
eps, rest = out[:, :self.in_channels], out[:, self.in_channels:]
return eps
def forward_with_dpmsolver(self, x, t, y, data_info, c, **kwargs):
model_out = self.forward_raw(x, t, y, data_info=data_info, c=c, **kwargs)
return model_out.chunk(2, dim=1)[0]
# def forward_with_dpmsolver(self, x, t, y, data_info, c, **kwargs):
# return self.base_model.forward_with_dpmsolver(x, t, y, data_info=data_info, c=self.forward_c(c), **kwargs)
def forward_with_cfg(self, x, t, y, cfg_scale, data_info, c, **kwargs):
return self.base_model.forward_with_cfg(x, t, y, cfg_scale, data_info, c=self.forward_c(c), **kwargs)
def load_state_dict(self, state_dict: Mapping[str, Any], strict: bool = True):
if all((k.startswith('base_model') or k.startswith('controlnet')) for k in state_dict.keys()):
return super().load_state_dict(state_dict, strict)
else:
new_key = {}
for k in state_dict.keys():
new_key[k] = re.sub(r"(blocks\.\d+)(.*)", r"\1.base_block\2", k)
for k, v in new_key.items():
if k != v:
print(f"replace {k} to {v}")
state_dict[v] = state_dict.pop(k)
return self.base_model.load_state_dict(state_dict, strict)
def unpatchify(self, x):
"""
x: (N, T, patch_size**2 * C)
imgs: (N, H, W, C)
"""
c = self.out_channels
p = self.x_embedder.patch_size[0]
assert self.h * self.w == x.shape[1]
x = x.reshape(shape=(x.shape[0], self.h, self.w, p, p, c))
x = torch.einsum('nhwpqc->nchpwq', x)
imgs = x.reshape(shape=(x.shape[0], c, self.h * p, self.w * p))
return imgs
# @property
# def dtype(self):
## 返回模型参数的数据类型
# return next(self.parameters()).dtype
# The implementation for PixArtMS_Half + 1024 resolution
class ControlPixArtMSHalf(ControlPixArtHalf):
# support multi-scale res model (multi-scale model can also be applied to single reso training & inference)
def __init__(self, base_model: PixArtMS, copy_blocks_num: int = 13) -> None:
super().__init__(base_model=base_model, copy_blocks_num=copy_blocks_num)
def forward_raw(self, x, timestep, y, mask=None, data_info=None, c=None, **kwargs):
# modify the original PixArtMS forward function
"""
Forward pass of PixArt.
x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images)
t: (N,) tensor of diffusion timesteps
y: (N, 1, 120, C) tensor of class labels
"""
if c is not None:
c = c.to(self.dtype)
c = self.forward_c(c)
bs = x.shape[0]
x = x.to(self.dtype)
timestep = timestep.to(self.dtype)
y = y.to(self.dtype)
c_size, ar = data_info['img_hw'].to(self.dtype), data_info['aspect_ratio'].to(self.dtype)
self.h, self.w = x.shape[-2]//self.patch_size, x.shape[-1]//self.patch_size
pos_embed = torch.from_numpy(get_2d_sincos_pos_embed(self.pos_embed.shape[-1], (self.h, self.w), lewei_scale=self.lewei_scale, base_size=self.base_size)).unsqueeze(0).to(x.device).to(self.dtype)
x = self.x_embedder(x) + pos_embed # (N, T, D), where T = H * W / patch_size ** 2
t = self.t_embedder(timestep) # (N, D)
csize = self.csize_embedder(c_size, bs) # (N, D)
ar = self.ar_embedder(ar, bs) # (N, D)
t = t + torch.cat([csize, ar], dim=1)
t0 = self.t_block(t)
y = self.y_embedder(y, self.training) # (N, D)
if mask is not None:
if mask.shape[0] != y.shape[0]:
mask = mask.repeat(y.shape[0] // mask.shape[0], 1)
mask = mask.squeeze(1).squeeze(1)
y = y.squeeze(1).masked_select(mask.unsqueeze(-1) != 0).view(1, -1, x.shape[-1])
y_lens = mask.sum(dim=1).tolist()
else:
y_lens = [y.shape[2]] * y.shape[0]
y = y.squeeze(1).view(1, -1, x.shape[-1])
# define the first layer
x = auto_grad_checkpoint(self.base_model.blocks[0], x, y, t0, y_lens, **kwargs) # (N, T, D) #support grad checkpoint
if c is not None:
# update c
for index in range(1, self.copy_blocks_num + 1):
c, c_skip = auto_grad_checkpoint(self.controlnet[index - 1], x, y, t0, y_lens, c, **kwargs)
x = auto_grad_checkpoint(self.base_model.blocks[index], x + c_skip, y, t0, y_lens, **kwargs)
# update x
for index in range(self.copy_blocks_num + 1, self.total_blocks_num):
x = auto_grad_checkpoint(self.base_model.blocks[index], x, y, t0, y_lens, **kwargs)
else:
for index in range(1, self.total_blocks_num):
x = auto_grad_checkpoint(self.base_model.blocks[index], x, y, t0, y_lens, **kwargs)
x = self.final_layer(x, t) # (N, T, patch_size ** 2 * out_channels)
x = self.unpatchify(x) # (N, out_channels, H, W)
return x
def forward(self, x, timesteps, context, img_hw=None, aspect_ratio=None, cn_hint=None, **kwargs):
"""
Forward pass that adapts comfy input to original forward function
x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images)
timesteps: (N,) tensor of diffusion timesteps
context: (N, 1, 120, C) conditioning
img_hw: height|width conditioning
aspect_ratio: aspect ratio conditioning
cn_hint: controlnet hint
"""
## size/ar from cond with fallback based on the latent image shape.
bs = x.shape[0]
data_info = {}
if img_hw is None:
data_info["img_hw"] = torch.tensor(
[[x.shape[2]*8, x.shape[3]*8]],
dtype=self.dtype,
device=x.device
).repeat(bs, 1)
else:
data_info["img_hw"] = img_hw.to(x.dtype)
if aspect_ratio is None or True:
data_info["aspect_ratio"] = torch.tensor(
[[x.shape[2]/x.shape[3]]],
dtype=self.dtype,
device=x.device
).repeat(bs, 1)
else:
data_info["aspect_ratio"] = aspect_ratio.to(x.dtype)
## Still accepts the input w/o that dim but returns garbage
if len(context.shape) == 3:
context = context.unsqueeze(1)
## run original forward pass
out = self.forward_raw(
x = x.to(self.dtype),
timestep = timesteps.to(self.dtype),
y = context.to(self.dtype),
c = cn_hint,
data_info=data_info,
)
## only return EPS
out = out.to(torch.float)
eps, rest = out[:, :self.in_channels], out[:, self.in_channels:]
return eps
@@ -11,12 +11,10 @@
import torch
import torch.nn as nn
from tqdm import tqdm
from timm.models.layers import DropPath
from timm.models.vision_transformer import Mlp
from .utils import auto_grad_checkpoint, to_2tuple
from .PixArt_blocks import t2i_modulate, CaptionEmbedder, AttentionKVCompress, MultiHeadCrossAttention, T2IFinalLayer, TimestepEmbedder, SizeEmbedder
from .PixArt import PixArt, get_2d_sincos_pos_embed
from .blocks import t2i_modulate, CaptionEmbedder, AttentionKVCompress, MultiHeadCrossAttention, T2IFinalLayer, TimestepEmbedder, SizeEmbedder, Mlp
from .pixart import PixArt, get_2d_sincos_pos_embed
class PatchEmbed(nn.Module):
@@ -31,12 +29,15 @@ class PatchEmbed(nn.Module):
norm_layer=None,
flatten=True,
bias=True,
dtype=None,
device=None,
operations=None
):
super().__init__()
patch_size = to_2tuple(patch_size)
self.patch_size = patch_size
self.flatten = flatten
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias)
self.proj = operations.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias, dtype=dtype, device=device)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
@@ -52,29 +53,34 @@ class PixArtMSBlock(nn.Module):
A PixArt block with adaptive layer norm zero (adaLN-Zero) conditioning.
"""
def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, drop_path=0., input_size=None,
sampling=None, sr_ratio=1, qk_norm=False, **block_kwargs):
sampling=None, sr_ratio=1, qk_norm=False, dtype=None, device=None, operations=None, **block_kwargs):
super().__init__()
self.hidden_size = hidden_size
self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
self.norm1 = operations.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
self.attn = AttentionKVCompress(
hidden_size, num_heads=num_heads, qkv_bias=True, sampling=sampling, sr_ratio=sr_ratio,
qk_norm=qk_norm, **block_kwargs
qk_norm=qk_norm, dtype=dtype, device=device, operations=operations, **block_kwargs
)
self.cross_attn = MultiHeadCrossAttention(hidden_size, num_heads, **block_kwargs)
self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
self.cross_attn = MultiHeadCrossAttention(
hidden_size, num_heads, dtype=dtype, device=device, operations=operations, **block_kwargs
)
self.norm2 = operations.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
# to be compatible with lower version pytorch
approx_gelu = lambda: nn.GELU(approximate="tanh")
self.mlp = Mlp(in_features=hidden_size, hidden_features=int(hidden_size * mlp_ratio), act_layer=approx_gelu, drop=0)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.mlp = Mlp(
in_features=hidden_size, hidden_features=int(hidden_size * mlp_ratio), act_layer=approx_gelu,
dtype=dtype, device=device, operations=operations
)
self.scale_shift_table = nn.Parameter(torch.randn(6, hidden_size) / hidden_size ** 0.5)
def forward(self, x, y, t, mask=None, HW=None, **kwargs):
B, N, C = x.shape
dtype = x.dtype
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (self.scale_shift_table[None] + t.reshape(B, 6, -1)).chunk(6, dim=1)
x = x + self.drop_path(gate_msa * self.attn(t2i_modulate(self.norm1(x), shift_msa, scale_msa), HW=HW))
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (self.scale_shift_table[None].to(x.dtype) + t.reshape(B, 6, -1)).chunk(6, dim=1)
x = x + (gate_msa * self.attn(t2i_modulate(self.norm1(x), shift_msa, scale_msa), HW=HW))
x = x + self.cross_attn(x, y, mask)
x = x + self.drop_path(gate_mlp * self.mlp(t2i_modulate(self.norm2(x), shift_mlp, scale_mlp)))
x = x + (gate_mlp * self.mlp(t2i_modulate(self.norm2(x), shift_mlp, scale_mlp)))
return x
@@ -105,40 +111,52 @@ class PixArtMS(PixArt):
micro_condition=True,
qk_norm=False,
kv_compress_config=None,
dtype=None,
device=None,
operations=None,
**kwargs,
):
super().__init__(
input_size=input_size,
patch_size=patch_size,
in_channels=in_channels,
hidden_size=hidden_size,
depth=depth,
num_heads=num_heads,
mlp_ratio=mlp_ratio,
class_dropout_prob=class_dropout_prob,
learn_sigma=learn_sigma,
pred_sigma=pred_sigma,
drop_path=drop_path,
pe_interpolation=pe_interpolation,
config=config,
model_max_length=model_max_length,
qk_norm=qk_norm,
kv_compress_config=kv_compress_config,
**kwargs,
)
self.dtype = torch.get_default_dtype()
nn.Module.__init__(self)
self.dtype = dtype
self.pred_sigma = pred_sigma
self.in_channels = in_channels
self.out_channels = in_channels * 2 if pred_sigma else in_channels
self.patch_size = patch_size
self.num_heads = num_heads
self.pe_interpolation = pe_interpolation
self.pe_precision = pe_precision
self.depth = depth
self.h = self.w = 0
approx_gelu = lambda: nn.GELU(approximate="tanh")
self.t_block = nn.Sequential(
nn.SiLU(),
nn.Linear(hidden_size, 6 * hidden_size, bias=True)
operations.Linear(hidden_size, 6 * hidden_size, bias=True, dtype=dtype, device=device)
)
self.x_embedder = PatchEmbed(patch_size, in_channels, hidden_size, bias=True)
self.y_embedder = CaptionEmbedder(in_channels=caption_channels, hidden_size=hidden_size, uncond_prob=class_dropout_prob, act_layer=approx_gelu, token_num=model_max_length)
self.x_embedder = PatchEmbed(
patch_size, in_channels, hidden_size, bias=True,
dtype=dtype, device=device, operations=operations
)
self.t_embedder = TimestepEmbedder(
hidden_size, dtype=dtype, device=device, operations=operations,
)
self.y_embedder = CaptionEmbedder(
in_channels=caption_channels, hidden_size=hidden_size, uncond_prob=class_dropout_prob,
act_layer=approx_gelu, token_num=model_max_length,
dtype=dtype, device=device, operations=operations,
)
self.micro_conditioning = micro_condition
if self.micro_conditioning:
self.csize_embedder = SizeEmbedder(hidden_size//3) # c_size embed
self.ar_embedder = SizeEmbedder(hidden_size//3) # aspect ratio embed
self.csize_embedder = SizeEmbedder(hidden_size//3, dtype=dtype, device=device, operations=operations)
self.ar_embedder = SizeEmbedder(hidden_size//3, dtype=dtype, device=device, operations=operations)
# Will use fixed sin-cos embedding:
num_patches = (input_size // patch_size) * (input_size // patch_size)
self.base_size = input_size // self.patch_size
self.register_buffer("pos_embed", torch.zeros(1, num_patches, hidden_size))
drop_path = [x.item() for x in torch.linspace(0, drop_path, depth)] # stochastic depth decay rule
if kv_compress_config is None:
kv_compress_config = {
@@ -153,12 +171,17 @@ class PixArtMS(PixArt):
sampling=kv_compress_config['sampling'],
sr_ratio=int(kv_compress_config['scale_factor']) if i in kv_compress_config['kv_compress_layer'] else 1,
qk_norm=qk_norm,
dtype=dtype,
device=device,
operations=operations,
)
for i in range(depth)
])
self.final_layer = T2IFinalLayer(hidden_size, patch_size, self.out_channels)
self.final_layer = T2IFinalLayer(
hidden_size, patch_size, self.out_channels, dtype=dtype, device=device, operations=operations
)
def forward_raw(self, x, t, y, mask=None, data_info=None, **kwargs):
def forward_orig(self, x, timestep, y, mask=None, data_info=None, **kwargs):
"""
Original forward pass of PixArt.
x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images)
@@ -166,9 +189,6 @@ class PixArtMS(PixArt):
y: (N, 1, 120, C) tensor of class labels
"""
bs = x.shape[0]
x = x.to(self.dtype)
timestep = t.to(self.dtype)
y = y.to(self.dtype)
pe_interpolation = self.pe_interpolation
if pe_interpolation is None or self.pe_precision is not None:
@@ -181,10 +201,10 @@ class PixArtMS(PixArt):
self.pos_embed.shape[-1], (self.h, self.w), pe_interpolation=pe_interpolation,
base_size=self.base_size
)
).unsqueeze(0).to(device=x.device, dtype=self.dtype)
).to(device=x.device, dtype=x.dtype).unsqueeze(0)
x = self.x_embedder(x) + pos_embed # (N, T, D), where T = H * W / patch_size ** 2
t = self.t_embedder(timestep) # (N, D)
t = self.t_embedder(timestep, x.dtype) # (N, D)
if self.micro_conditioning:
c_size, ar = data_info['img_hw'].to(self.dtype), data_info['aspect_ratio'].to(self.dtype)
@@ -212,46 +232,29 @@ class PixArtMS(PixArt):
return x
def forward(self, x, timesteps, context, img_hw=None, aspect_ratio=None, **kwargs):
"""
Forward pass that adapts comfy input to original forward function
x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images)
timesteps: (N,) tensor of diffusion timesteps
context: (N, 1, 120, C) conditioning
img_hw: height|width conditioning
aspect_ratio: aspect ratio conditioning
"""
def forward(self, x, timesteps, context, width=None, height=None, img_hw=None, aspect_ratio=None, **kwargs):
bs, c, h, w = x.shape
dtype = self.dtype
device = x.device
## size/ar from cond with fallback based on the latent image shape.
bs = x.shape[0]
data_info = {}
if img_hw is None:
data_info["img_hw"] = torch.tensor(
[[x.shape[2]*8, x.shape[3]*8]],
dtype=self.dtype,
device=x.device
).repeat(bs, 1)
data_info["img_hw"] = torch.tensor([h*8, w*8], dtype=dtype, device=device).repeat(bs, 1)
else:
data_info["img_hw"] = img_hw.to(dtype=x.dtype, device=x.device)
if aspect_ratio is None or True:
data_info["aspect_ratio"] = torch.tensor(
[[x.shape[2]/x.shape[3]]],
dtype=self.dtype,
device=x.device
).repeat(bs, 1)
if aspect_ratio is None:
data_info["aspect_ratio"] = torch.tensor([h/w], dtype=dtype, device=device).repeat(bs, 1)
else:
data_info["aspect_ratio"] = aspect_ratio.to(dtype=x.dtype, device=x.device)
data_info["aspect_ratio"] = aspect_ratio.to(dtype=dtype, device=device)
## Still accepts the input w/o that dim but returns garbage
if len(context.shape) == 3:
context = context.unsqueeze(1)
## run original forward pass
out = self.forward_raw(
x = x.to(self.dtype),
t = timesteps.to(self.dtype),
y = context.to(self.dtype),
data_info=data_info,
)
out = self.forward_orig(x, timesteps, context, data_info=data_info)
## only return EPS
out = out.to(torch.float)
+1 -192
View File
@@ -1,111 +1,3 @@
import os
import json
import torch
import folder_paths
from comfy import utils
from .conf import pixart_conf, pixart_res
from .lora import load_pixart_lora
from .loader import load_pixart
class PixArtCheckpointLoader:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"ckpt_name": (folder_paths.get_filename_list("checkpoints"),),
"model": (list(pixart_conf.keys()),),
}
}
RETURN_TYPES = ("MODEL",)
RETURN_NAMES = ("model",)
FUNCTION = "load_checkpoint"
CATEGORY = "ExtraModels/PixArt"
TITLE = "PixArt Checkpoint Loader"
def load_checkpoint(self, ckpt_name, model):
ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
model_conf = pixart_conf[model]
model = load_pixart(
model_path = ckpt_path,
model_conf = model_conf,
)
return (model,)
class PixArtCheckpointLoaderSimple(PixArtCheckpointLoader):
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"ckpt_name": (folder_paths.get_filename_list("checkpoints"),),
}
}
TITLE = "PixArt Checkpoint Loader (auto)"
def load_checkpoint(self, ckpt_name):
ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
model = load_pixart(model_path=ckpt_path)
return (model,)
class PixArtResolutionSelect():
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model": (list(pixart_res.keys()),),
# keys are the same for both
"ratio": (list(pixart_res["PixArtMS_XL_2"].keys()),{"default":"1.00"}),
}
}
RETURN_TYPES = ("INT","INT")
RETURN_NAMES = ("width","height")
FUNCTION = "get_res"
CATEGORY = "ExtraModels/PixArt"
TITLE = "PixArt Resolution Select"
def get_res(self, model, ratio):
width, height = pixart_res[model][ratio]
return (width,height)
class PixArtLoraLoader:
def __init__(self):
self.loaded_lora = None
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model": ("MODEL",),
"lora_name": (folder_paths.get_filename_list("loras"), ),
"strength": ("FLOAT", {"default": 1.0, "min": -20.0, "max": 20.0, "step": 0.01}),
}
}
RETURN_TYPES = ("MODEL",)
FUNCTION = "load_lora"
CATEGORY = "ExtraModels/PixArt"
TITLE = "PixArt Load LoRA"
def load_lora(self, model, lora_name, strength,):
if strength == 0:
return (model)
lora_path = folder_paths.get_full_path("loras", lora_name)
lora = None
if self.loaded_lora is not None:
if self.loaded_lora[0] == lora_path:
lora = self.loaded_lora[1]
else:
temp = self.loaded_lora
self.loaded_lora = None
del temp
if lora is None:
lora = utils.load_torch_file(lora_path, safe_load=True)
self.loaded_lora = (lora_path, lora)
model_lora = load_pixart_lora(model, lora, lora_path, strength,)
return (model_lora,)
class PixArtResolutionCond:
@classmethod
def INPUT_TYPES(s):
@@ -131,83 +23,6 @@ class PixArtResolutionCond:
})
return (cond,)
class PixArtControlNetCond:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"cond": ("CONDITIONING",),
"latent": ("LATENT",),
# "image": ("IMAGE",),
# "vae": ("VAE",),
# "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01})
}
}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("cond",)
FUNCTION = "add_cond"
CATEGORY = "ExtraModels/PixArt"
TITLE = "PixArt ControlNet Conditioning"
def add_cond(self, cond, latent):
for c in range(len(cond)):
cond[c][1]["cn_hint"] = latent["samples"] * 0.18215
return (cond,)
class PixArtT5TextEncode:
"""
Reference code, mostly to verify compatibility.
Once everything works, this should instead inherit from the
T5 text encode node and simply add the extra conds (res/ar).
"""
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"text": ("STRING", {"multiline": True}),
"T5": ("T5",),
}
}
RETURN_TYPES = ("CONDITIONING",)
FUNCTION = "encode"
CATEGORY = "ExtraModels/PixArt"
TITLE = "PixArt T5 Text Encode [Reference]"
def mask_feature(self, emb, mask):
if emb.shape[0] == 1:
keep_index = mask.sum().item()
return emb[:, :, :keep_index, :], keep_index
else:
masked_feature = emb * mask[:, None, :, None]
return masked_feature, emb.shape[2]
def encode(self, text, T5):
text = text.lower().strip()
tokenizer_out = T5.tokenizer.tokenizer(
text,
max_length = 120,
padding = 'max_length',
truncation = True,
return_attention_mask = True,
add_special_tokens = True,
return_tensors = 'pt'
)
tokens = tokenizer_out["input_ids"]
mask = tokenizer_out["attention_mask"]
embs = T5.cond_stage_model.transformer(
input_ids = tokens.to(T5.load_device),
attention_mask = mask.to(T5.load_device),
)['last_hidden_state'].float()[:, None]
masked_embs, keep_index = self.mask_feature(
embs.detach().to("cpu"),
mask.detach().to("cpu")
)
masked_embs = masked_embs.squeeze(0) # match CLIP/internal
print("Encoded T5:", masked_embs.shape)
return ([[masked_embs, {}]], )
class PixArtT5FromSD3CLIP:
"""
Split the T5 text encoder away from SD3
@@ -232,7 +47,7 @@ class PixArtT5FromSD3CLIP:
from comfy.text_encoders.sd3_clip import SD3Tokenizer, SD3ClipModel
except ImportError:
# fallback for older ComfyUI versions
from comfy.sd3_clip import SD3Tokenizer, SD3ClipModel
from comfy.sd3_clip import SD3Tokenizer, SD3ClipModel # type: ignore
import copy
clip = sd3_clip.clone()
@@ -267,12 +82,6 @@ class PixArtT5FromSD3CLIP:
return (clip, )
NODE_CLASS_MAPPINGS = {
"PixArtCheckpointLoader" : PixArtCheckpointLoader,
"PixArtCheckpointLoaderSimple" : PixArtCheckpointLoaderSimple,
"PixArtResolutionSelect" : PixArtResolutionSelect,
"PixArtLoraLoader" : PixArtLoraLoader,
"PixArtT5TextEncode" : PixArtT5TextEncode,
"PixArtResolutionCond" : PixArtResolutionCond,
"PixArtControlNetCond" : PixArtControlNetCond,
"PixArtT5FromSD3CLIP": PixArtT5FromSD3CLIP,
}
+2 -11
View File
@@ -23,6 +23,7 @@ Clone the repository to your custom nodes folder, assuming haven't installed in
To install the requirements on windows, run these commands in the same window:
```
.\python_embeded\python.exe -s -m pip install -r .\ComfyUI\custom_nodes\ComfyUI_ExtraModels\requirements.txt
.\python_embeded\python.exe -s -m pip install bitsandbytes --prefer-binary --extra-index-url=https://jllllll.github.io/bitsandbytes-windows-webui
```
To update, open the command line window like before and run the following commands:
@@ -39,16 +40,6 @@ Alternatively, use the manager, assuming it has an update function.
[Original Repo](https://github.com/NVlabs/Sana)
> [!CAUTION]
> As many people have had issues with Sana, it's for now recommended to try the fork by the Sana devs, which auto downloads all models:
>
> [Readme](https://github.com/NVlabs/Sana/blob/main/asset/docs/ComfyUI/comfyui.md) | [Fork repo](https://github.com/Efficient-Large-Model/ComfyUI_ExtraModels)
A full rewrite to have better integration is in progress in [this PR](https://github.com/city96/ComfyUI_ExtraModels/pull/92) but isn't ready yet.
https://github.com/NVlabs/Sana/blob/main/asset/docs/ComfyUI/comfyui.md
https://github.com/Efficient-Large-Model/ComfyUI_ExtraModels
### Model info / implementation
- Uses Gemma2 2B as the text encoder
- Multiple resolutions and models available
@@ -59,7 +50,7 @@ https://github.com/Efficient-Large-Model/ComfyUI_ExtraModels
2. Place them in your checkpoints folder
3. Load them with the correct PixArt checkpoint loader
4. Use the "Gemma Loader" node - it should automatically download the requested model from Huggingface - Recommended to use the 4bit quantized model on CPU when low on memory.
5. Download the VAE from [here](https://huggingface.co/Efficient-Large-Model/Sana_1600M_1024px_diffusers/blob/main/vae/diffusion_pytorch_model.safetensors) or [here](https://huggingface.co/mit-han-lab/dc-ae-f32c32-sana-1.0/blob/main/model.safetensors) and place it in your VAE folder after renaming it.
5. Download the VAE from [here](https://huggingface.co/Efficient-Large-Model/Sana_1600M_1024px_diffusers/blob/main/vae/diffusion_pytorch_model.safetensors) and place it in your VAE folder after renaming it.
6. Use either the "Empty Sana Latent Image" or "Empty DCAE Latent Image" node for the latent input when doing txt2img.
[Sample workflow](https://github.com/user-attachments/files/18027854/SanaV1.json)
-98
View File
@@ -1,98 +0,0 @@
"""
List of all Sana model types / settings
"""
sampling_settings = {
"shift": 3.0,
}
sana_conf = {
"SanaMS_600M_P1_D28": {
"target": "SanaMS",
"unet_config": {
"in_channels": 32,
"depth": 28,
"hidden_size": 1152,
"patch_size": 1,
"num_heads": 16,
"linear_head_dim": 32,
"model_max_length": 300,
"y_norm": True,
"attn_type": "linear",
"ffn_type": "glumbconv",
"mlp_ratio": 2.5,
"mlp_acts": ["silu", "silu", None],
"use_pe": False,
"pred_sigma": False,
"learn_sigma": False,
"fp32_attention": True,
},
"sampling_settings" : sampling_settings,
},
"SanaMS_1600M_P1_D20": {
"target": "SanaMS",
"unet_config": {
"in_channels": 32,
"depth": 20,
"hidden_size": 2240,
"patch_size": 1,
"num_heads": 20,
"linear_head_dim": 32,
"model_max_length": 300,
"y_norm": True,
"attn_type": "linear",
"ffn_type": "glumbconv",
"mlp_ratio": 2.5,
"mlp_acts": ["silu", "silu", None],
"use_pe": False,
"pred_sigma": False,
"learn_sigma": False,
"fp32_attention": True,
},
"sampling_settings" : sampling_settings,
},
}
sana_res = {
"1024px": { # models/SanaMS 1024x1024
'0.25': [512, 2048], '0.26': [512, 1984], '0.27': [512, 1920], '0.28': [512, 1856],
'0.32': [576, 1792], '0.33': [576, 1728], '0.35': [576, 1664], '0.40': [640, 1600],
'0.42': [640, 1536], '0.48': [704, 1472], '0.50': [704, 1408], '0.52': [704, 1344],
'0.57': [768, 1344], '0.60': [768, 1280], '0.68': [832, 1216], '0.72': [832, 1152],
'0.78': [896, 1152], '0.82': [896, 1088], '0.88': [960, 1088], '0.94': [960, 1024],
'1.00': [1024,1024], '1.07': [1024, 960], '1.13': [1088, 960], '1.21': [1088, 896],
'1.29': [1152, 896], '1.38': [1152, 832], '1.46': [1216, 832], '1.67': [1280, 768],
'1.75': [1344, 768], '2.00': [1408, 704], '2.09': [1472, 704], '2.40': [1536, 640],
'2.50': [1600, 640], '2.89': [1664, 576], '3.00': [1728, 576], '3.11': [1792, 576],
'3.62': [1856, 512], '3.75': [1920, 512], '3.88': [1984, 512], '4.00': [2048, 512],
},
"512px": { # models/SanaMS 512x512
'0.25': [256,1024], '0.26': [256, 992], '0.27': [256, 960], '0.28': [256, 928],
'0.32': [288, 896], '0.33': [288, 864], '0.35': [288, 832], '0.40': [320, 800],
'0.42': [320, 768], '0.48': [352, 736], '0.50': [352, 704], '0.52': [352, 672],
'0.57': [384, 672], '0.60': [384, 640], '0.68': [416, 608], '0.72': [416, 576],
'0.78': [448, 576], '0.82': [448, 544], '0.88': [480, 544], '0.94': [480, 512],
'1.00': [512, 512], '1.07': [512, 480], '1.13': [544, 480], '1.21': [544, 448],
'1.29': [576, 448], '1.38': [576, 416], '1.46': [608, 416], '1.67': [640, 384],
'1.75': [672, 384], '2.00': [704, 352], '2.09': [736, 352], '2.40': [768, 320],
'2.50': [800, 320], '2.89': [832, 288], '3.00': [864, 288], '3.11': [896, 288],
'3.62': [928, 256], '3.75': [960, 256], '3.88': [992, 256], '4.00': [1024,256]
},
"2K": {
'0.25': [1024, 4096], '0.26': [1024, 3968], '0.27': [1024, 3840], '0.28': [1024, 3712],
'0.32': [1152, 3584], '0.33': [1152, 3456], '0.35': [1152, 3328], '0.40': [1280, 3200],
'0.42': [1280, 3072], '0.48': [1408, 2944], '0.50': [1408, 2816], '0.52': [1408, 2688],
'0.57': [1536, 2688], '0.60': [1536, 2560], '0.68': [1664, 2432], '0.72': [1664, 2304],
'0.78': [1792, 2304], '0.82': [1792, 2176], '0.88': [1920, 2176], '0.94': [1920, 2048],
'1.00': [2048, 2048], '1.07': [2048, 1920], '1.13': [2176, 1920], '1.21': [2176, 1792],
'1.29': [2304, 1792], '1.38': [2304, 1664], '1.46': [2432, 1664], '1.67': [2560, 1536],
'1.75': [2688, 1536], '2.00': [2816, 1408], '2.09': [2944, 1408], '2.40': [3072, 1280],
'2.50': [3200, 1280], '2.89': [3328, 1152], '3.00': [3456, 1152], '3.11': [3584, 1152],
'3.62': [3712, 1024], '3.75': [3840, 1024], '3.88': [3968, 1024], '4.00': [4096, 1024]
}
}
# These should be the same
sana_res.update({
"SanaMS_600M_P1_D28": sana_res["1024px"],
"SanaMS_1600M_P1_D20": sana_res["1024px"],
})
+123 -77
View File
@@ -1,100 +1,146 @@
import comfy.supported_models_base
import comfy.latent_formats
import comfy.model_patcher
import comfy.model_base
import comfy.utils
import comfy.conds
import torch
import math
from comfy import model_management
from comfy.latent_formats import LatentFormat
import logging
import comfy.utils
import comfy.model_base
import comfy.model_detection
import comfy.supported_models_base
import comfy.supported_models
import comfy.latent_formats
from .models.sana import Sana
from .models.sana_multi_scale import SanaMS
from .diffusers_convert import convert_state_dict
from ..utils.loader import load_state_dict_from_config
class SanaLatent(LatentFormat):
class SanaLatent(comfy.latent_formats.LatentFormat):
latent_channels = 32
def __init__(self):
self.scale_factor = 0.41407
self.latent_rgb_factors = latent_rgb_factors.copy()
self.latent_rgb_factors_bias = latent_rgb_factors_bias.copy()
class EXM_Sana(comfy.supported_models_base.BASE):
class SanaConfig(comfy.supported_models_base.BASE):
unet_class = SanaMS
unet_config = {}
unet_extra_config = {}
latent_format = SanaLatent
def __init__(self, model_conf):
self.model_target = model_conf.get("target")
self.unet_config = model_conf.get("unet_config", {})
self.sampling_settings = model_conf.get("sampling_settings", {})
self.latent_format = self.latent_format()
# UNET is handled by extension
self.unet_config["disable_unet_model_creation"] = True
latent_format = SanaLatent
sampling_settings = {
"shift": 3.0,
}
def model_type(self, state_dict, prefix=""):
return comfy.model_base.ModelType.FLOW
def get_model(self, state_dict, prefix="", device=None):
return SanaModel(model_config=self, unet_model=self.unet_class, device=device)
class EXM_Sana_Model(comfy.model_base.BaseModel):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class SanaModel(comfy.model_base.BaseModel):
def __init__(self, *args, model_type=comfy.model_base.ModelType.FLOW, unet_model=SanaMS, **kwargs):
super().__init__(*args, model_type=model_type, unet_model=unet_model, **kwargs)
def extra_conds(self, **kwargs):
out = super().extra_conds(**kwargs)
def load_sana_state_dict(sd, model_options={}):
# prefix / format
sd = sd.get("model", sd) # ref ckpt
diffusion_model_prefix = comfy.model_detection.unet_prefix_from_state_dict(sd)
temp_sd = comfy.utils.state_dict_prefix_replace(sd, {diffusion_model_prefix: ""}, filter_keys=True)
if len(temp_sd) > 0:
sd = temp_sd
cn_hint = kwargs.get("cn_hint", None)
if cn_hint is not None:
out["cn_hint"] = comfy.conds.CONDRegular(cn_hint)
# diffusers convert
if "adaln_single.linear.weight" in sd:
sd = convert_state_dict(sd)
return out
# model config
model_config = model_config_from_unet(sd)
return load_state_dict_from_config(model_config, sd, model_options)
def model_config_from_unet(sd):
"""
Guess config based on (converted) state dict.
"""
# shared settings that match between all models
# TODO: some can (should) be enumerated
config = {
"in_channels": 32,
"linear_head_dim": 32,
"model_max_length": 300,
"y_norm": True,
"attn_type": "linear",
"ffn_type": "glumbconv",
"mlp_ratio": 2.5,
"mlp_acts": ["silu", "silu", None],
"use_pe": False,
"pred_sigma": False,
"learn_sigma": False,
"fp32_attention": True,
"patch_size": 1,
}
config["depth"] = sum([key.endswith(".point_conv.conv.weight") for key in sd.keys()]) or 28
def load_sana(model_path, model_conf):
state_dict = comfy.utils.load_torch_file(model_path)
state_dict = state_dict.get("model", state_dict)
# prefix
for prefix in ["model.diffusion_model.",]:
if any(True for x in state_dict if x.startswith(prefix)):
state_dict = {k[len(prefix):]:v for k,v in state_dict.items()}
# diffusers
if "adaln_single.linear.weight" in state_dict:
state_dict = convert_state_dict(state_dict) # Diffusers
parameters = comfy.utils.calculate_parameters(state_dict)
unet_dtype = comfy.model_management.unet_dtype()
load_device = comfy.model_management.get_torch_device()
offload_device = comfy.model_management.unet_offload_device()
# ignore fp8/etc and use directly for now
manual_cast_dtype = model_management.unet_manual_cast(unet_dtype, load_device)
if manual_cast_dtype:
print(f"Sana: falling back to {manual_cast_dtype}")
unet_dtype = manual_cast_dtype
model_conf = EXM_Sana(model_conf) # convert to object
model = EXM_Sana_Model( # same as comfy.model_base.BaseModel
model_conf,
model_type=comfy.model_base.ModelType.FLOW,
device=model_management.get_torch_device()
)
if model_conf.model_target == "SanaMS":
from .models.sana_multi_scale import SanaMS
model.diffusion_model = SanaMS(**model_conf.unet_config)
if "pos_embed" in sd:
config["input_size"] = int(math.sqrt(sd["pos_embed"].shape[1])) * config["patch_size"]
else:
raise NotImplementedError(f"Unknown model target '{model_conf.model_target}'")
# TODO: this isn't optimal though most models don't use it
config["use_pe"] = False
m, u = model.diffusion_model.load_state_dict(state_dict, strict=False)
if len(m) > 0: print("Missing UNET keys", m)
if len(u) > 0: print("Leftover UNET keys", u)
model.diffusion_model.dtype = unet_dtype
model.diffusion_model.eval()
model.diffusion_model.to(unet_dtype)
if "x_embedder.proj.bias" in sd:
config["hidden_size"] = sd["x_embedder.proj.bias"].shape[0]
model_patcher = comfy.model_patcher.ModelPatcher(
model,
load_device = load_device,
offload_device = offload_device,
)
return model_patcher
if config["hidden_size"] == 1152:
config["num_heads"] = 16
elif config["hidden_size"] == 2240:
config["num_heads"] = 20
else:
raise RuntimeError(f"Unknown model config.")
model_config = SanaConfig(config)
logging.debug(f"Sana config:\n{config}")
return model_config
# for fast latent preview
latent_rgb_factors = [
[-2.0022e-03, -6.0736e-03, -1.7096e-03],
[ 1.4221e-03, 3.6703e-03, 4.1083e-03],
[ 1.0081e-02, 2.6456e-04, -1.4333e-02],
[-2.4253e-03, 3.0967e-03, -1.0301e-03],
[ 2.2158e-03, 7.7274e-03, -1.3151e-02],
[ 1.1235e-02, 5.7630e-03, 3.6146e-03],
[-7.2899e-02, 1.1062e-02, 3.6103e-02],
[ 3.2346e-02, 2.8678e-02, 2.5014e-02],
[ 1.6469e-03, -1.1364e-03, 2.8366e-03],
[-3.5597e-02, -2.3447e-02, -3.1172e-03],
[-1.9985e-04, -2.0647e-03, -1.2702e-02],
[ 2.1318e-04, 1.2196e-03, -8.3461e-04],
[ 1.3766e-02, 2.7559e-03, 7.3567e-03],
[ 1.3027e-02, 2.6365e-03, 3.0405e-03],
[ 1.5335e-02, 9.4682e-03, 6.7312e-03],
[ 5.1827e-03, -9.4865e-03, 8.5080e-03],
[ 1.4365e-02, -3.2867e-03, 9.5108e-03],
[-4.1216e-03, -1.9177e-03, -3.3726e-03],
[-2.4757e-03, 5.1739e-04, 2.0280e-03],
[-3.5950e-03, 1.0720e-03, 5.3043e-03],
[-5.1758e-03, 8.1040e-03, -3.7564e-02],
[-3.8555e-03, -1.5529e-03, -3.5799e-03],
[-6.6175e-03, -6.8484e-03, -9.9609e-03],
[-2.1656e-03, 5.5770e-05, 1.4936e-03],
[-9.2857e-02, -1.1379e-01, -1.0919e-01],
[ 7.7044e-04, 5.5594e-03, 3.4755e-02],
[ 1.2714e-02, 2.9729e-02, 3.1989e-03],
[-1.1805e-03, 9.0548e-03, -4.1063e-04],
[ 8.3309e-04, 4.9694e-03, 2.3087e-03],
[ 7.8456e-03, 3.9750e-03, 3.5655e-03],
[-1.7552e-03, 4.9306e-03, 1.4210e-02],
[-1.4790e-03, 2.8837e-03, -4.5687e-03]
]
latent_rgb_factors_bias = [0.4358, 0.3814, 0.3388]
# 512/1024/2K match, TODO: 4K is new, add on release
from ..PixArt.loader import resolutions as pixart_res
resolutions = {
"Sana 512": pixart_res["PixArt 512"],
"Sana 1024": pixart_res["PixArt 1024"],
"Sana 2K": pixart_res["PixArt 2K"],
}
View File
+2 -2
View File
@@ -37,7 +37,7 @@ REGISTERED_ACT_DICT: dict[str, tuple[type, dict[str, any]]] = {
}
def build_act(name: str or None, **kwargs) -> nn.Module or None:
def build_act(name, **kwargs):
if name in REGISTERED_ACT_DICT:
act_cls, default_args = copy.deepcopy(REGISTERED_ACT_DICT[name])
for key in default_args:
@@ -50,7 +50,7 @@ def build_act(name: str or None, **kwargs) -> nn.Module or None:
raise ValueError(f"do not support: {name}")
def get_act_name(act: nn.Module or None) -> str or None:
def get_act_name(act):
if act is None:
return None
module2name = {}
+61 -41
View File
@@ -17,13 +17,31 @@
# This file is modified from https://github.com/PixArt-alpha/PixArt-sigma
import torch
import torch.nn as nn
from timm.models.vision_transformer import Mlp
#from timm.models.vision_transformer import Mlp
from .act import build_act, get_act_name
from .norms import build_norm, get_norm_name
from .utils import get_same_padding, val2tuple
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, bias=True, drop=None, dtype=None, device=None, operations=None) -> None:
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = operations.Linear(in_features, hidden_features, bias=bias, dtype=dtype, device=device)
self.act = act_layer()
self.fc2 = operations.Linear(hidden_features, out_features, bias=bias, dtype=dtype, device=device)
self.drop1 = nn.Identity()
self.drop2 = nn.Identity()
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.act(self.fc1(x))
return self.fc2(x)
class ConvLayer(nn.Module):
def __init__(
self,
@@ -33,11 +51,14 @@ class ConvLayer(nn.Module):
stride=1,
dilation=1,
groups=1,
padding: int or None = None,
padding=None,
use_bias=False,
dropout=0.0,
norm="bn2d",
act="relu",
dtype=None,
device=None,
operations=None,
):
super().__init__()
if padding is None:
@@ -54,7 +75,7 @@ class ConvLayer(nn.Module):
self.use_bias = use_bias
self.dropout = nn.Dropout2d(dropout, inplace=False) if dropout > 0 else None
self.conv = nn.Conv2d(
self.conv = operations.Conv2d(
in_dim,
out_dim,
kernel_size=(kernel_size, kernel_size),
@@ -63,6 +84,8 @@ class ConvLayer(nn.Module):
dilation=(dilation, dilation),
groups=groups,
bias=use_bias,
dtype=dtype,
device=device,
)
self.norm = build_norm(norm, num_features=out_dim)
self.act = build_act(act)
@@ -86,11 +109,14 @@ class GLUMBConv(nn.Module):
out_feature=None,
kernel_size=3,
stride=1,
padding: int or None = None,
padding=None,
use_bias=False,
norm=(None, None, None),
act=("silu", "silu", None),
dilation=1,
dtype=None,
device=None,
operations=None,
):
out_feature = out_feature or in_features
super().__init__()
@@ -106,6 +132,9 @@ class GLUMBConv(nn.Module):
use_bias=use_bias[0],
norm=norm[0],
act=act[0],
dtype=dtype,
device=device,
operations=operations,
)
self.depth_conv = ConvLayer(
hidden_features * 2,
@@ -118,6 +147,9 @@ class GLUMBConv(nn.Module):
norm=norm[1],
act=None,
dilation=dilation,
dtype=dtype,
device=device,
operations=operations,
)
self.point_conv = ConvLayer(
hidden_features,
@@ -126,6 +158,9 @@ class GLUMBConv(nn.Module):
use_bias=use_bias[2],
norm=norm[2],
act=act[2],
dtype=dtype,
device=device,
operations=operations,
)
# from IPython import embed; embed(header='debug dilate conv')
@@ -189,10 +224,13 @@ class MBConvPreGLU(nn.Module):
stride=1,
mid_dim=None,
expand=6,
padding: int or None = None,
padding=None,
use_bias=False,
norm=(None, None, "ln2d"),
act=("silu", "silu", None),
dtype=None,
device=None,
operations=None,
):
super().__init__()
use_bias = val2tuple(use_bias, 3)
@@ -208,6 +246,9 @@ class MBConvPreGLU(nn.Module):
use_bias=use_bias[0],
norm=norm[0],
act=None,
dtype=dtype,
device=device,
operations=operations,
)
self.glu_act = build_act(act[0], inplace=False)
self.depth_conv = ConvLayer(
@@ -220,6 +261,9 @@ class MBConvPreGLU(nn.Module):
use_bias=use_bias[1],
norm=norm[1],
act=act[1],
dtype=dtype,
device=device,
operations=operations,
)
self.point_conv = ConvLayer(
mid_dim,
@@ -228,6 +272,9 @@ class MBConvPreGLU(nn.Module):
use_bias=use_bias[2],
norm=norm[2],
act=act[2],
dtype=dtype,
device=device,
operations=operations,
)
def forward(self, x: torch.Tensor, HW=None) -> torch.Tensor:
@@ -283,6 +330,9 @@ class DWMlp(Mlp):
stride=1,
dilation=1,
padding=None,
dtype=None,
device=None,
operations=None,
):
super().__init__(
in_features=in_features,
@@ -291,6 +341,9 @@ class DWMlp(Mlp):
act_layer=act_layer,
bias=bias,
drop=drop,
dtype=dtype,
device=device,
operations=operations,
)
hidden_features = hidden_features or in_features
self.hidden_features = hidden_features
@@ -298,7 +351,7 @@ class DWMlp(Mlp):
padding = get_same_padding(kernel_size)
padding *= dilation
self.conv = nn.Conv2d(
self.conv = operations.Conv2d(
hidden_features,
hidden_features,
kernel_size=(kernel_size, kernel_size),
@@ -307,6 +360,8 @@ class DWMlp(Mlp):
dilation=(dilation, dilation),
groups=hidden_features,
bias=bias,
dtype=dtype,
device=device,
)
def forward(self, x, HW=None):
@@ -324,38 +379,3 @@ class DWMlp(Mlp):
x = self.fc2(x)
x = self.drop2(x)
return x
class Mlp(Mlp):
"""MLP as used in Vision Transformer, MLP-Mixer and related networks"""
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, bias=True, drop=0.0):
super().__init__(
in_features=in_features,
hidden_features=hidden_features,
out_features=out_features,
act_layer=act_layer,
bias=bias,
drop=drop,
)
def forward(self, x, HW=None):
x = self.fc1(x)
x = self.act(x)
x = self.drop1(x)
x = self.fc2(x)
x = self.drop2(x)
return x
if __name__ == "__main__":
model = GLUMBConv(
1152,
1152 * 4,
1152,
use_bias=(True, True, False),
norm=(None, None, None),
act=("silu", "silu", None),
).cuda()
input = torch.randn(4, 256, 1152).cuda()
output = model(input)
+3 -3
View File
@@ -48,7 +48,7 @@ REGISTERED_NORMALIZATION_DICT: dict[str, tuple[type, dict[str, any]]] = {
}
def build_norm(name="bn2d", num_features=None, affine=True, **kwargs) -> nn.Module or None:
def build_norm(name="bn2d", num_features=None, affine=True, **kwargs):
if name in ["ln", "ln2d"]:
kwargs["normalized_shape"] = num_features
kwargs["elementwise_affine"] = affine
@@ -67,7 +67,7 @@ def build_norm(name="bn2d", num_features=None, affine=True, **kwargs) -> nn.Modu
raise ValueError("do not support: %s" % name)
def get_norm_name(norm: nn.Module or None) -> str or None:
def get_norm_name(norm):
if norm is None:
return None
module2name = {}
@@ -171,7 +171,7 @@ def remove_bn(model: nn.Module) -> None:
m.forward = lambda x: x
def set_norm_eps(model: nn.Module, eps: float or None = None, momentum: float or None = None) -> None:
def set_norm_eps(model, eps=None, momentum=None):
for m in model.modules():
if isinstance(m, (nn.GroupNorm, nn.LayerNorm, _BatchNorm)):
if eps is not None:
+63 -55
View File
@@ -20,7 +20,6 @@ import os
import numpy as np
import torch
import torch.nn as nn
from timm.models.layers import DropPath
from .basic_modules import DWMlp, GLUMBConv, MBConvPreGLU, Mlp
from .sana_blocks import (
@@ -35,7 +34,7 @@ from .sana_blocks import (
t2i_modulate,
)
from .norms import RMSNorm
from .utils import auto_grad_checkpoint, to_2tuple
from .utils import to_2tuple
class SanaBlock(nn.Module):
@@ -55,10 +54,13 @@ class SanaBlock(nn.Module):
ffn_type="mlp",
mlp_acts=("silu", "silu", None),
linear_head_dim=32,
dtype=None,
device=None,
operations=None,
**block_kwargs,
):
super().__init__()
self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
self.norm1 = operations.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
if attn_type == "flash":
# flash self attention
self.attn = FlashAttention(
@@ -66,20 +68,28 @@ class SanaBlock(nn.Module):
num_heads=num_heads,
qkv_bias=True,
qk_norm=qk_norm,
dtype=dtype,
device=device,
operations=operations,
**block_kwargs,
)
elif attn_type == "linear":
# linear self attention
# TODO: Here the num_heads set to 36 for tmp used
self_num_heads = hidden_size // linear_head_dim
self.attn = LiteLA(hidden_size, hidden_size, heads=self_num_heads, eps=1e-8, qk_norm=qk_norm)
self.attn = LiteLA(
hidden_size, hidden_size, heads=self_num_heads, eps=1e-8, qk_norm=qk_norm,
dtype=dtype, device=device, operations=operations,
)
elif attn_type == "vanilla":
# vanilla self attention
self.attn = Attention(hidden_size, num_heads=num_heads, qkv_bias=True)
self.attn = Attention(
hidden_size, num_heads=num_heads, qkv_bias=True, dtype=dtype, device=device, operations=operations,
)
else:
raise ValueError(f"{attn_type} type is not defined.")
self.cross_attn = MultiHeadCrossAttention(hidden_size, num_heads, **block_kwargs)
self.cross_attn = MultiHeadCrossAttention(hidden_size, num_heads, dtype=dtype, device=device, operations=operations, **block_kwargs)
self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
# to be compatible with lower version pytorch
if ffn_type == "dwmlp":
@@ -94,6 +104,9 @@ class SanaBlock(nn.Module):
use_bias=(True, True, False),
norm=(None, None, None),
act=mlp_acts,
dtype=dtype,
device=device,
operations=operations,
)
elif ffn_type == "glumbconv_dilate":
self.mlp = GLUMBConv(
@@ -103,6 +116,9 @@ class SanaBlock(nn.Module):
norm=(None, None, None),
act=mlp_acts,
dilation=2,
dtype=dtype,
device=device,
operations=operations,
)
elif ffn_type == "mbconvpreglu":
self.mlp = MBConvPreGLU(
@@ -112,15 +128,19 @@ class SanaBlock(nn.Module):
use_bias=(True, True, False),
norm=None,
act=("silu", "silu", None),
dtype=dtype,
device=device,
operations=operations,
)
elif ffn_type == "mlp":
approx_gelu = lambda: nn.GELU(approximate="tanh")
self.mlp = Mlp(
in_features=hidden_size, hidden_features=int(hidden_size * mlp_ratio), act_layer=approx_gelu, drop=0
in_features=hidden_size, hidden_features=int(hidden_size * mlp_ratio), act_layer=approx_gelu, drop=0,
# dtype=dtype, device=device, operations=operations,
)
else:
raise ValueError(f"{ffn_type} type is not defined.")
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.drop_path = nn.Identity() #DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.scale_shift_table = nn.Parameter(torch.randn(6, hidden_size) / hidden_size**0.5)
def forward(self, x, y, t, mask=None, **kwargs):
@@ -146,7 +166,7 @@ class Sana(nn.Module):
def __init__(
self,
input_size=32,
input_size=None,
patch_size=1,
in_channels=32,
hidden_size=1152,
@@ -170,9 +190,13 @@ class Sana(nn.Module):
patch_embed_kernel=None,
mlp_acts=("silu", "silu", None),
linear_head_dim=32,
dtype=None,
device=None,
operations=None,
**kwargs,
):
super().__init__()
self.dtype = dtype
self.pred_sigma = pred_sigma
self.in_channels = in_channels
self.out_channels = in_channels * 2 if pred_sigma else in_channels
@@ -187,22 +211,36 @@ class Sana(nn.Module):
kernel_size = patch_embed_kernel or patch_size
self.x_embedder = PatchEmbed(
input_size, patch_size, in_channels, hidden_size, kernel_size=kernel_size, bias=True
input_size, patch_size, in_channels, hidden_size, kernel_size=kernel_size, bias=True,
dtype=dtype, device=device, operations=operations
)
self.t_embedder = TimestepEmbedder(hidden_size)
num_patches = self.x_embedder.num_patches
self.t_embedder = TimestepEmbedder(hidden_size, dtype=dtype, device=device, operations=operations)
if input_size is not None:
self.base_size = input_size // self.patch_size
# Will use fixed sin-cos embedding:
else:
self.base_size = None
num_patches = self.x_embedder.num_patches
if self.use_pe and num_patches is not None:
#Will use fixed sin-cos embedding:
self.register_buffer("pos_embed", torch.zeros(1, num_patches, hidden_size))
else:
self.pos_embed = None
approx_gelu = lambda: nn.GELU(approximate="tanh")
self.t_block = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 6 * hidden_size, bias=True))
self.t_block = nn.Sequential(
nn.SiLU(), operations.Linear(hidden_size, 6 * hidden_size, bias=True, dtype=dtype, device=device)
)
self.y_embedder = CaptionEmbedder(
in_channels=caption_channels,
hidden_size=hidden_size,
uncond_prob=class_dropout_prob,
act_layer=approx_gelu,
token_num=model_max_length,
dtype=dtype,
device=device,
operations=operations
)
if self.y_norm:
self.attention_y_norm = RMSNorm(hidden_size, scale_factor=y_norm_scale_factor, eps=norm_eps)
@@ -220,29 +258,32 @@ class Sana(nn.Module):
ffn_type=ffn_type,
mlp_acts=mlp_acts,
linear_head_dim=linear_head_dim,
dtype=dtype,
device=device,
operations=operations
)
for i in range(depth)
]
)
self.final_layer = T2IFinalLayer(hidden_size, patch_size, self.out_channels)
self.final_layer = T2IFinalLayer(
hidden_size, patch_size, self.out_channels, dtype=dtype, device=device, operations=operations
)
def forward(self, x, timestep, y, mask=None, data_info=None, **kwargs):
def forward(self, x, timestep, context, mask=None, data_info=None, **kwargs):
"""
Forward pass of Sana.
x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images)
t: (N,) tensor of diffusion timesteps
y: (N, 1, 120, C) tensor of class labels
"""
x = x.to(self.dtype)
timestep = timestep.to(self.dtype)
y = y.to(self.dtype)
pos_embed = self.pos_embed.to(self.dtype)
y = context # remap comfy cond name
self.h, self.w = x.shape[-2] // self.patch_size, x.shape[-1] // self.patch_size
if self.use_pe:
pos_embed = self.pos_embed.to(x.dtype)
x = self.x_embedder(x) + pos_embed # (N, T, D), where T = H * W / patch_size ** 2
else:
x = self.x_embedder(x)
t = self.t_embedder(timestep.to(x.dtype)) # (N, D)
t = self.t_embedder(timestep, x.dtype) # (N, D)
t0 = self.t_block(t)
y = self.y_embedder(y, self.training) # (N, 1, L, D)
if self.y_norm:
@@ -257,7 +298,7 @@ class Sana(nn.Module):
y_lens = [y.shape[2]] * y.shape[0]
y = y.squeeze(1).view(1, -1, x.shape[-1])
for block in self.blocks:
x = auto_grad_checkpoint(block, x, y, t0, y_lens) # (N, T, D) #support grad checkpoint
x = block(x, y, t0, y_lens) # (N, T, D)
x = self.final_layer(x, t) # (N, T, patch_size ** 2 * out_channels)
x = self.unpatchify(x) # (N, out_channels, H, W)
return x
@@ -292,39 +333,6 @@ class Sana(nn.Module):
imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p))
return imgs
def initialize_weights(self):
# Initialize transformer layers:
def _basic_init(module):
if isinstance(module, nn.Linear):
torch.nn.init.xavier_uniform_(module.weight)
if module.bias is not None:
nn.init.constant_(module.bias, 0)
self.apply(_basic_init)
if self.use_pe:
# Initialize (and freeze) pos_embed by sin-cos embedding:
pos_embed = get_2d_sincos_pos_embed(
self.pos_embed.shape[-1],
int(self.x_embedder.num_patches**0.5),
pe_interpolation=self.pe_interpolation,
base_size=self.base_size,
)
self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
# Initialize patch_embed like nn.Linear (instead of nn.Conv2d):
w = self.x_embedder.proj.weight.data
nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
# Initialize timestep embedding MLP:
nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
nn.init.normal_(self.t_block[1].weight, std=0.02)
# Initialize caption embedding MLP:
nn.init.normal_(self.y_embedder.y_proj.fc1.weight, std=0.02)
nn.init.normal_(self.y_embedder.y_proj.fc2.weight, std=0.02)
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0, pe_interpolation=1.0, base_size=16):
"""
+125 -49
View File
@@ -22,12 +22,13 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from timm.models.vision_transformer import Attention as Attention_
from timm.models.vision_transformer import Mlp
from transformers import AutoModelForCausalLM
from .norms import RMSNorm
from .utils import get_same_padding, to_2tuple
from .basic_modules import Mlp
import comfy.ldm.common_dit
sdpa_32b = None
Q_4GB_LIMIT = 32000000
@@ -38,11 +39,14 @@ Q_4GB_LIMIT = 32000000
from comfy import model_management
if model_management.xformers_enabled():
import xformers
import xformers.ops
if int((xformers.__version__).split(".")[2]) >= 28:
block_diagonal_mask_from_seqlens = xformers.ops.fmha.attn_bias.BlockDiagonalMask.from_seqlens
else:
block_diagonal_mask_from_seqlens = xformers.ops.fmha.BlockDiagonalMask.from_seqlens
else:
if model_management.xpu_available:
import intel_extension_for_pytorch as ipex
import intel_extension_for_pytorch as ipex # type: ignore
import os
if not torch.xpu.has_fp64_dtype() and not os.environ.get('IPEX_FORCE_ATTENTION_SLICE', None):
from ...utils.IPEX.attention import scaled_dot_product_attention_32_bit
@@ -61,7 +65,7 @@ def t2i_modulate(x, shift, scale):
class MultiHeadCrossAttention(nn.Module):
def __init__(self, d_model, num_heads, attn_drop=0.0, proj_drop=0.0, qk_norm=False, **block_kwargs):
def __init__(self, d_model, num_heads, attn_drop=0.0, proj_drop=0.0, qk_norm=False, dtype=None, device=None, operations=None, **block_kwargs):
super().__init__()
assert d_model % num_heads == 0, "d_model must be divisible by num_heads"
@@ -69,10 +73,10 @@ class MultiHeadCrossAttention(nn.Module):
self.num_heads = num_heads
self.head_dim = d_model // num_heads
self.q_linear = nn.Linear(d_model, d_model)
self.kv_linear = nn.Linear(d_model, d_model * 2)
self.q_linear = operations.Linear(d_model, d_model, dtype=dtype, device=device)
self.kv_linear = operations.Linear(d_model, d_model * 2, dtype=dtype, device=device)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(d_model, d_model)
self.proj = operations.Linear(d_model, d_model, dtype=dtype, device=device)
self.proj_drop = nn.Dropout(proj_drop)
if qk_norm:
# not used for now
@@ -93,7 +97,7 @@ class MultiHeadCrossAttention(nn.Module):
if model_management.xformers_enabled():
attn_bias = None
if mask is not None:
attn_bias = xformers.ops.fmha.BlockDiagonalMask.from_seqlens([N] * B, mask)
attn_bias = block_diagonal_mask_from_seqlens([N] * B, mask)
x = xformers.ops.memory_efficient_attention(
q, k, v,
p=self.attn_drop.p,
@@ -135,7 +139,7 @@ class MultiHeadCrossAttention(nn.Module):
return x
class LiteLA(Attention_):
class LiteLA(torch.nn.Module): # from attention
r"""Lightweight linear attention"""
PAD_VAL = 1
@@ -151,9 +155,20 @@ class LiteLA(Attention_):
use_bias=False,
qk_norm=False,
norm_eps=1e-5,
dtype=None,
device=None,
operations=None,
):
super().__init__()
heads = heads or int(out_dim // dim * heads_ratio)
super().__init__(in_dim, num_heads=heads, qkv_bias=use_bias)
# assert dim % heads == 0, 'dim should be divisible by num_heads'
self.num_heads = heads
self.head_dim = in_dim // heads
self.scale = self.head_dim ** -0.5
self.qkv = operations.Linear(in_dim, in_dim * 3, bias=use_bias, dtype=dtype, device=device)
self.proj = operations.Linear(in_dim, in_dim, dtype=dtype, device=device)
self.in_dim = in_dim
self.out_dim = out_dim
@@ -346,7 +361,7 @@ class SelfAttnProcessorLiteLA:
return out
class FlashAttention(Attention_):
class FlashAttention(torch.nn.Module): # from attention
"""Multi-head Flash Attention block with qk norm."""
def __init__(
@@ -395,7 +410,7 @@ class FlashAttention(Attention_):
attn_bias = torch.zeros([B * self.num_heads, q.shape[1], k.shape[1]], dtype=q.dtype, device=q.device)
attn_bias.masked_fill_(mask.squeeze(1).repeat(self.num_heads, 1, 1) == 0, float("-inf"))
if _xformers_available:
if model_management.xformers_enabled():
x = xformers.ops.memory_efficient_attention(q, k, v, p=self.attn_drop.p, attn_bias=attn_bias)
else:
q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
@@ -418,7 +433,31 @@ class FlashAttention(Attention_):
#################################################################################
# AMP attention with fp32 softmax to fix loss NaN problem during training #
#################################################################################
class Attention(Attention_):
class Attention(torch.nn.Module):
def __init__(
self,
dim,
num_heads=8,
qkv_bias=True,
sampling='conv',
sr_ratio=1,
qk_norm=False,
dtype=None,
device=None,
operations=None,
**block_kwargs,
):
super().__init__()
assert dim % num_heads == 0, 'dim should be divisible by num_heads'
self.num_heads = num_heads
self.head_dim = dim // num_heads
self.scale = self.head_dim ** -0.5
self.qkv = operations.Linear(dim, dim * 3, bias=qkv_bias, dtype=dtype, device=device)
self.q_norm = nn.Identity()
self.k_norm = nn.Identity()
self.proj = operations.Linear(dim, dim, dtype=dtype, device=device)
def forward(self, x, HW=None):
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
@@ -432,11 +471,11 @@ class Attention(Attention_):
attn = (q @ k.transpose(-2, -1)) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
#attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
#x = self.proj_drop(x)
return x
@@ -445,11 +484,14 @@ class FinalLayer(nn.Module):
The final layer of Sana.
"""
def __init__(self, hidden_size, patch_size, out_channels):
def __init__(self, hidden_size, patch_size, out_channels, dtype=None, device=None, operations=None):
super().__init__()
self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
self.norm_final = operations.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
self.linear = operations.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True, dtype=dtype, device=device)
self.adaLN_modulation = nn.Sequential(
nn.SiLU(),
operations.Linear(hidden_size, 2 * hidden_size, bias=True, dtype=dtype, device=device)
)
def forward(self, x, c):
shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
@@ -463,17 +505,18 @@ class T2IFinalLayer(nn.Module):
The final layer of Sana.
"""
def __init__(self, hidden_size, patch_size, out_channels):
def __init__(self, hidden_size, patch_size, out_channels, dtype=None, device=None, operations=None):
super().__init__()
self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
self.scale_shift_table = nn.Parameter(torch.randn(2, hidden_size) / hidden_size**0.5)
self.norm_final = operations.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
self.linear = operations.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True, dtype=dtype, device=device)
self.scale_shift_table = nn.Parameter(torch.randn(2, hidden_size) / hidden_size ** 0.5)
self.out_channels = out_channels
def forward(self, x, t):
dtype = x.dtype
shift, scale = (self.scale_shift_table[None] + t[:, None]).chunk(2, dim=1)
x = t2i_modulate(self.norm_final(x), shift, scale)
x = self.linear(x)
x = self.linear(x.to(dtype))
return x
@@ -482,12 +525,14 @@ class MaskFinalLayer(nn.Module):
The final layer of Sana.
"""
def __init__(self, final_hidden_size, c_emb_size, patch_size, out_channels):
def __init__(self, final_hidden_size, c_emb_size, patch_size, out_channels, dtype=None, device=None, operations=None):
super().__init__()
self.norm_final = nn.LayerNorm(final_hidden_size, elementwise_affine=False, eps=1e-6)
self.linear = nn.Linear(final_hidden_size, patch_size * patch_size * out_channels, bias=True)
self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(c_emb_size, 2 * final_hidden_size, bias=True))
self.norm_final = operations.LayerNorm(final_hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
self.linear = operations.Linear(final_hidden_size, patch_size * patch_size * out_channels, bias=True, dtype=dtype, device=device)
self.adaLN_modulation = nn.Sequential(
nn.SiLU(),
operations.Linear(c_emb_size, 2 * final_hidden_size, bias=True, dtype=dtype, device=device)
)
def forward(self, x, t):
shift, scale = self.adaLN_modulation(t).chunk(2, dim=1)
x = modulate(self.norm_final(x), shift, scale)
@@ -500,12 +545,14 @@ class DecoderLayer(nn.Module):
The final layer of Sana.
"""
def __init__(self, hidden_size, decoder_hidden_size):
def __init__(self, hidden_size, decoder_hidden_size, dtype=None, device=None, operations=None):
super().__init__()
self.norm_decoder = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
self.linear = nn.Linear(hidden_size, decoder_hidden_size, bias=True)
self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
self.norm_decoder = operations.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
self.linear = operations.Linear(hidden_size, decoder_hidden_size, bias=True, dtype=dtype, device=device)
self.adaLN_modulation = nn.Sequential(
nn.SiLU(),
operations.Linear(hidden_size, 2 * hidden_size, bias=True, dtype=dtype, device=device)
)
def forward(self, x, t):
shift, scale = self.adaLN_modulation(t).chunk(2, dim=1)
x = modulate(self.norm_decoder(x), shift, scale)
@@ -521,12 +568,12 @@ class TimestepEmbedder(nn.Module):
Embeds scalar timesteps into vector representations.
"""
def __init__(self, hidden_size, frequency_embedding_size=256):
def __init__(self, hidden_size, frequency_embedding_size=256, dtype=None, device=None, operations=None):
super().__init__()
self.mlp = nn.Sequential(
nn.Linear(frequency_embedding_size, hidden_size, bias=True),
operations.Linear(frequency_embedding_size, hidden_size, bias=True, dtype=dtype, device=device),
nn.SiLU(),
nn.Linear(hidden_size, hidden_size, bias=True),
operations.Linear(hidden_size, hidden_size, bias=True, dtype=dtype, device=device),
)
self.frequency_embedding_size = frequency_embedding_size
@@ -551,9 +598,9 @@ class TimestepEmbedder(nn.Module):
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
return embedding
def forward(self, t):
t_freq = self.timestep_embedding(t, self.frequency_embedding_size).to(self.dtype)
t_emb = self.mlp(t_freq)
def forward(self, t, dtype):
t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
t_emb = self.mlp(t_freq.to(dtype))
return t_emb
@property
@@ -644,10 +691,14 @@ class CaptionEmbedder(nn.Module):
uncond_prob,
act_layer=nn.GELU(approximate="tanh"),
token_num=120,
dtype=None,
device=None,
operations=None,
):
super().__init__()
self.y_proj = Mlp(
in_features=in_channels, hidden_features=hidden_size, out_features=hidden_size, act_layer=act_layer, drop=0
in_features=in_channels, hidden_features=hidden_size, out_features=hidden_size, act_layer=act_layer, drop=0,
dtype=dtype, device=device, operations=operations
)
self.register_buffer("y_embedding", nn.Parameter(torch.randn(token_num, in_channels) / in_channels**0.5))
self.uncond_prob = uncond_prob
@@ -734,27 +785,43 @@ class PatchEmbed(nn.Module):
norm_layer=None,
flatten=True,
bias=True,
dynamic_img_pad=True,
padding_mode='circular',
dtype=None,
device=None,
operations=None,
):
super().__init__()
kernel_size = kernel_size or patch_size
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
self.img_size = img_size
self.patch_size = patch_size
if img_size is not None and False:
self.img_size = img_size
self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
self.num_patches = self.grid_size[0] * self.grid_size[1]
else:
self.img_size = None
self.grid_size = None
self.num_patches = None
self.flatten = flatten
self.dynamic_img_pad = dynamic_img_pad
self.padding_mode = padding_mode
if not padding and kernel_size % 2 > 0:
padding = get_same_padding(kernel_size)
self.proj = nn.Conv2d(
in_chans, embed_dim, kernel_size=kernel_size, stride=patch_size, padding=padding, bias=bias
self.proj = operations.Conv2d(
in_chans, embed_dim, kernel_size=kernel_size, stride=patch_size, padding=padding, bias=bias, dtype=dtype, device=device
)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
assert (H == self.img_size[0], f"Input image height ({H}) doesn't match model ({self.img_size[0]}).")
assert (W == self.img_size[1], f"Input image width ({W}) doesn't match model ({self.img_size[1]}).")
# assert (H == self.img_size[0], f"Input image height ({H}) doesn't match model ({self.img_size[0]}).")
# assert (W == self.img_size[1], f"Input image width ({W}) doesn't match model ({self.img_size[1]}).")
if self.dynamic_img_pad:
x = comfy.ldm.common_dit.pad_to_patch_size(x, self.patch_size, padding_mode=self.padding_mode)
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
@@ -775,20 +842,29 @@ class PatchEmbedMS(nn.Module):
norm_layer=None,
flatten=True,
bias=True,
dynamic_img_pad=True,
padding_mode='circular',
dtype=None,
device=None,
operations=None,
):
super().__init__()
kernel_size = kernel_size or patch_size
patch_size = to_2tuple(patch_size)
self.patch_size = patch_size
self.flatten = flatten
self.dynamic_img_pad = dynamic_img_pad
self.padding_mode = padding_mode
if not padding and kernel_size % 2 > 0:
padding = get_same_padding(kernel_size)
self.proj = nn.Conv2d(
in_chans, embed_dim, kernel_size=kernel_size, stride=patch_size, padding=padding, bias=bias
self.proj = operations.Conv2d(
in_chans, embed_dim, kernel_size=kernel_size, stride=patch_size, padding=padding, bias=bias, dtype=dtype, device=device
)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
if self.dynamic_img_pad:
x = comfy.ldm.common_dit.pad_to_patch_size(x, self.patch_size, padding_mode=self.padding_mode)
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
+83 -81
View File
@@ -17,13 +17,13 @@
# This file is modified from https://github.com/PixArt-alpha/PixArt-sigma
import torch
import torch.nn as nn
from timm.models.layers import DropPath
from .basic_modules import DWMlp, GLUMBConv, MBConvPreGLU, Mlp
from .sana import Sana, get_2d_sincos_pos_embed
from .sana_blocks import (
Attention,
CaptionEmbedder,
TimestepEmbedder,
FlashAttention,
LiteLA,
MultiHeadCrossAttention,
@@ -31,8 +31,7 @@ from .sana_blocks import (
T2IFinalLayer,
t2i_modulate,
)
from .utils import auto_grad_checkpoint
from .norms import RMSNorm
class SanaMSBlock(nn.Module):
"""
@@ -52,11 +51,14 @@ class SanaMSBlock(nn.Module):
mlp_acts=("silu", "silu", None),
linear_head_dim=32,
cross_norm=False,
dtype=None,
device=None,
operations=None,
**block_kwargs,
):
super().__init__()
self.hidden_size = hidden_size
self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
self.norm1 = operations.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
if attn_type == "flash":
# flash self attention
self.attn = FlashAttention(
@@ -64,25 +66,34 @@ class SanaMSBlock(nn.Module):
num_heads=num_heads,
qkv_bias=True,
qk_norm=qk_norm,
dtype=dtype,
device=device,
operations=operations,
**block_kwargs,
)
elif attn_type == "linear":
# linear self attention
# TODO: Here the num_heads set to 36 for tmp used
self_num_heads = hidden_size // linear_head_dim
self.attn = LiteLA(hidden_size, hidden_size, heads=self_num_heads, eps=1e-8, qk_norm=qk_norm)
self.attn = LiteLA(
hidden_size, hidden_size, heads=self_num_heads, eps=1e-8, qk_norm=qk_norm,
dtype=dtype, device=device, operations=operations,
)
elif attn_type == "vanilla":
# vanilla self attention
self.attn = Attention(hidden_size, num_heads=num_heads, qkv_bias=True)
self.attn = Attention(
hidden_size, num_heads=num_heads, qkv_bias=True, dtype=dtype, device=device, operations=operations,
)
else:
raise ValueError(f"{attn_type} type is not defined.")
self.cross_attn = MultiHeadCrossAttention(hidden_size, num_heads, qk_norm=cross_norm, **block_kwargs)
self.cross_attn = MultiHeadCrossAttention(hidden_size, num_heads, qk_norm=cross_norm, dtype=dtype, device=device, operations=operations, **block_kwargs)
self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
if ffn_type == "dwmlp":
approx_gelu = lambda: nn.GELU(approximate="tanh")
self.mlp = DWMlp(
in_features=hidden_size, hidden_features=int(hidden_size * mlp_ratio), act_layer=approx_gelu, drop=0
in_features=hidden_size, hidden_features=int(hidden_size * mlp_ratio), act_layer=approx_gelu, drop=0,
dtype=dtype, device=device, operations=operations,
)
elif ffn_type == "glumbconv":
self.mlp = GLUMBConv(
@@ -91,6 +102,9 @@ class SanaMSBlock(nn.Module):
use_bias=(True, True, False),
norm=(None, None, None),
act=mlp_acts,
dtype=dtype,
device=device,
operations=operations,
)
elif ffn_type == "glumbconv_dilate":
self.mlp = GLUMBConv(
@@ -100,11 +114,15 @@ class SanaMSBlock(nn.Module):
norm=(None, None, None),
act=mlp_acts,
dilation=2,
dtype=dtype,
device=device,
operations=operations,
)
elif ffn_type == "mlp":
approx_gelu = lambda: nn.GELU(approximate="tanh")
self.mlp = Mlp(
in_features=hidden_size, hidden_features=int(hidden_size * mlp_ratio), act_layer=approx_gelu, drop=0
in_features=hidden_size, hidden_features=int(hidden_size * mlp_ratio), act_layer=approx_gelu, drop=0,
dtype=dtype, device=device, operations=operations,
)
elif ffn_type == "mbconvpreglu":
self.mlp = MBConvPreGLU(
@@ -114,17 +132,20 @@ class SanaMSBlock(nn.Module):
use_bias=(True, True, False),
norm=None,
act=mlp_acts,
dtype=dtype,
device=device,
operations=operations,
)
else:
raise ValueError(f"{ffn_type} type is not defined.")
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.drop_path = nn.Identity() # DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.scale_shift_table = nn.Parameter(torch.randn(6, hidden_size) / hidden_size**0.5)
def forward(self, x, y, t, mask=None, HW=None, **kwargs):
B, N, C = x.shape
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
self.scale_shift_table[None] + t.reshape(B, 6, -1)
self.scale_shift_table[None].to(x.dtype) + t.reshape(B, 6, -1)
).chunk(6, dim=1)
x = x + self.drop_path(gate_msa * self.attn(t2i_modulate(self.norm1(x), shift_msa, scale_msa), HW=HW))
x = x + self.cross_attn(x, y, mask)
@@ -169,51 +190,57 @@ class SanaMS(Sana):
mlp_acts=("silu", "silu", None),
linear_head_dim=32,
cross_norm=False,
dtype=None,
device=None,
operations=None,
**kwargs,
):
super().__init__(
input_size=input_size,
patch_size=patch_size,
in_channels=in_channels,
hidden_size=hidden_size,
depth=depth,
num_heads=num_heads,
mlp_ratio=mlp_ratio,
class_dropout_prob=class_dropout_prob,
learn_sigma=learn_sigma,
pred_sigma=pred_sigma,
drop_path=drop_path,
caption_channels=caption_channels,
pe_interpolation=pe_interpolation,
config=config,
model_max_length=model_max_length,
qk_norm=qk_norm,
y_norm=y_norm,
norm_eps=norm_eps,
attn_type=attn_type,
ffn_type=ffn_type,
use_pe=use_pe,
y_norm_scale_factor=y_norm_scale_factor,
patch_embed_kernel=patch_embed_kernel,
mlp_acts=mlp_acts,
linear_head_dim=linear_head_dim,
**kwargs,
)
self.dtype = torch.get_default_dtype()
nn.Module.__init__(self)
self.dtype = dtype
self.pred_sigma = pred_sigma
self.in_channels = in_channels
self.out_channels = in_channels * 2 if pred_sigma else in_channels
self.patch_size = patch_size
self.num_heads = num_heads
self.pe_interpolation = pe_interpolation
self.depth = depth
self.use_pe = use_pe
self.y_norm = y_norm
self.model_max_length = model_max_length
self.fp32_attention = kwargs.get("use_fp32_attention", False)
self.h = self.w = 0
approx_gelu = lambda: nn.GELU(approximate="tanh")
self.t_block = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 6 * hidden_size, bias=True))
self.t_block = nn.Sequential(
nn.SiLU(), operations.Linear(hidden_size, 6 * hidden_size, bias=True, dtype=dtype, device=device)
)
self.t_embedder = TimestepEmbedder(hidden_size, dtype=dtype, device=device, operations=operations)
self.pos_embed_ms = None
if input_size is not None:
self.base_size = input_size // self.patch_size
else:
self.base_size = None
kernel_size = patch_embed_kernel or patch_size
self.x_embedder = PatchEmbedMS(patch_size, in_channels, hidden_size, kernel_size=kernel_size, bias=True)
self.x_embedder = PatchEmbedMS(
patch_size, in_channels, hidden_size, kernel_size=kernel_size, bias=True,
dtype=dtype, device=device, operations=operations,
)
self.y_embedder = CaptionEmbedder(
in_channels=caption_channels,
hidden_size=hidden_size,
uncond_prob=class_dropout_prob,
act_layer=approx_gelu,
token_num=model_max_length,
dtype=dtype,
device=device,
operations=operations,
)
if self.y_norm:
self.attention_y_norm = RMSNorm(hidden_size, scale_factor=y_norm_scale_factor, eps=norm_eps)
drop_path = [x.item() for x in torch.linspace(0, drop_path, depth)] # stochastic depth decay rule
self.blocks = nn.ModuleList(
[
@@ -229,13 +256,16 @@ class SanaMS(Sana):
mlp_acts=mlp_acts,
linear_head_dim=linear_head_dim,
cross_norm=cross_norm,
dtype=dtype,
device=device,
operations=operations,
)
for i in range(depth)
]
)
self.final_layer = T2IFinalLayer(hidden_size, patch_size, self.out_channels)
self.initialize()
self.final_layer = T2IFinalLayer(
hidden_size, patch_size, self.out_channels, dtype=dtype, device=device, operations=operations
)
def forward(self, x, timesteps, context, **kwargs):
"""
@@ -251,7 +281,7 @@ class SanaMS(Sana):
context = context.unsqueeze(1)
## run original forward pass
out = self.forward_raw(
out = self.forward_orig(
x = x.to(self.dtype),
timestep = timesteps.to(self.dtype),
y = context.to(self.dtype),
@@ -262,7 +292,7 @@ class SanaMS(Sana):
return out
def forward_raw(self, x, timestep, y, mask=None, data_info=None, **kwargs):
def forward(self, x, timestep, context, mask=None, data_info=None, **kwargs):
"""
Forward pass of Sana.
x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images)
@@ -270,9 +300,9 @@ class SanaMS(Sana):
y: (N, 1, 120, C) tensor of class labels
"""
bs = x.shape[0]
x = x.to(self.dtype)
timestep = timestep.to(self.dtype)
y = y.to(self.dtype)
y = context
if len(y.shape) == 3:
y = y.unsqueeze(1)
self.h, self.w = x.shape[-2] // self.patch_size, x.shape[-1] // self.patch_size
if self.use_pe:
x = self.x_embedder(x)
@@ -285,16 +315,13 @@ class SanaMS(Sana):
pe_interpolation=self.pe_interpolation,
base_size=self.base_size,
)
)
.unsqueeze(0)
.to(x.device)
.to(self.dtype)
).unsqueeze(0).to(x.device).to(x.dtype)
)
x += self.pos_embed_ms # (N, T, D), where T = H * W / patch_size ** 2
else:
x = self.x_embedder(x)
t = self.t_embedder(timestep) # (N, D)
t = self.t_embedder(timestep, x.dtype) # (N, D)
y_lens = ((y != 0).sum(dim=3) > 0).sum(dim=2).squeeze().tolist()
y_lens = [y_lens[1]] * bs
@@ -311,9 +338,7 @@ class SanaMS(Sana):
y = y.squeeze(1).masked_select(mask.unsqueeze(-1).bool()).view(1, -1, y.shape[-1])
for block in self.blocks:
x = auto_grad_checkpoint(
block, x, y, t0, y_lens, (self.h, self.w), **kwargs
) # (N, T, D) #support grad checkpoint
x = block(x, y, t0, y_lens, (self.h, self.w), **kwargs) # (N, T, D) #
x = self.final_layer(x, t) # (N, T, patch_size ** 2 * out_channels)
x = self.unpatchify(x) # (N, out_channels, H, W)
@@ -348,26 +373,3 @@ class SanaMS(Sana):
x = torch.einsum("nhwpqc->nchpwq", x)
imgs = x.reshape(shape=(x.shape[0], c, self.h * p, self.w * p))
return imgs
def initialize(self):
# Initialize transformer layers:
def _basic_init(module):
if isinstance(module, nn.Linear):
torch.nn.init.xavier_uniform_(module.weight)
if module.bias is not None:
nn.init.constant_(module.bias, 0)
self.apply(_basic_init)
# Initialize patch_embed like nn.Linear (instead of nn.Conv2d):
w = self.x_embedder.proj.weight.data
nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
# Initialize timestep embedding MLP:
nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
nn.init.normal_(self.t_block[1].weight, std=0.02)
# Initialize caption embedding MLP:
nn.init.normal_(self.y_embedder.y_proj.fc1.weight, std=0.02)
nn.init.normal_(self.y_embedder.y_proj.fc2.weight, std=0.02)
-85
View File
@@ -2,41 +2,6 @@ import torch
import folder_paths
from nodes import EmptyLatentImage
from .conf import sana_conf, sana_res
from .loader import load_sana
dtypes = [
"auto",
"FP32",
"FP16",
"BF16"
]
class SanaCheckpointLoader:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"ckpt_name": (folder_paths.get_filename_list("checkpoints"),),
"model": (list(sana_conf.keys()),),
}
}
RETURN_TYPES = ("MODEL",)
RETURN_NAMES = ("model",)
FUNCTION = "load_checkpoint"
CATEGORY = "ExtraModels/Sana"
TITLE = "Sana Checkpoint Loader"
def load_checkpoint(self, ckpt_name, model):
ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
model_conf = sana_conf[model]
model = load_sana(
model_path = ckpt_path,
model_conf = model_conf,
)
return (model,)
class EmptySanaLatentImage(EmptyLatentImage):
CATEGORY = "ExtraModels/Sana"
TITLE = "Empty Sana Latent Image"
@@ -45,53 +10,6 @@ class EmptySanaLatentImage(EmptyLatentImage):
latent = torch.zeros([batch_size, 32, height // 32, width // 32], device=self.device)
return ({"samples":latent}, )
class SanaResolutionSelect():
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model": (list(sana_res.keys()),),
"ratio": (list(sana_res["1024px"].keys()),{"default":"1.00"}),
}
}
RETURN_TYPES = ("INT","INT")
RETURN_NAMES = ("width","height")
FUNCTION = "get_res"
CATEGORY = "ExtraModels/Sana"
TITLE = "Sana Resolution Select"
def get_res(self, model, ratio):
width, height = sana_res[model][ratio]
return (width,height)
class SanaResolutionCond:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"cond": ("CONDITIONING", ),
"width": ("INT", {"default": 1024.0, "min": 0, "max": 8192}),
"height": ("INT", {"default": 1024.0, "min": 0, "max": 8192}),
}
}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("cond",)
FUNCTION = "add_cond"
CATEGORY = "ExtraModels/Sana"
TITLE = "Sana Resolution Conditioning"
def add_cond(self, cond, width, height):
for c in range(len(cond)):
cond[c][1].update({
"img_hw": [[height, width]],
"aspect_ratio": [[height/width]],
})
return (cond,)
class SanaTextEncode:
@classmethod
def INPUT_TYPES(s):
@@ -144,9 +62,6 @@ preset_te_prompt = [
]
NODE_CLASS_MAPPINGS = {
"SanaCheckpointLoader" : SanaCheckpointLoader,
"SanaResolutionSelect" : SanaResolutionSelect,
"SanaTextEncode" : SanaTextEncode,
"SanaResolutionCond" : SanaResolutionCond,
"EmptySanaLatentImage": EmptySanaLatentImage,
}
-674
View File
@@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
-118
View File
@@ -1,118 +0,0 @@
import os
import torch
import comfy.utils
import comfy.model_patcher
from comfy import model_management
import folder_paths
from .t5v11 import T5v11Model, T5v11Tokenizer
class EXM_T5v11:
def __init__(self, textmodel_ver="xxl", embedding_directory=None, textmodel_path=None, no_init=False, device="cpu", dtype=None):
if no_init:
return
if device == "auto":
size = 0
self.load_device = model_management.text_encoder_device()
self.offload_device = model_management.text_encoder_offload_device()
self.init_device = "cpu"
elif dtype == "bnb8bit":
# BNB doesn't support size enum
size = 12.4 * (1024**3)
# Or moving between devices
self.load_device = model_management.get_torch_device()
self.offload_device = self.load_device
self.init_device = self.load_device
elif dtype == "bnb4bit":
# This seems to use the same VRAM as 8bit on Pascal?
size = 6.2 * (1024**3)
self.load_device = model_management.get_torch_device()
self.offload_device = self.load_device
self.init_device = self.load_device
elif device == "cpu":
size = 0
self.load_device = "cpu"
self.offload_device = "cpu"
self.init_device="cpu"
elif device.startswith("cuda"):
print("Direct CUDA device override!\nVRAM will not be freed by default.")
size = 0
self.load_device = device
self.offload_device = device
self.init_device = device
else:
size = 0
self.load_device = model_management.get_torch_device()
self.offload_device = "cpu"
self.init_device="cpu"
self.cond_stage_model = T5v11Model(
textmodel_ver = textmodel_ver,
textmodel_path = textmodel_path,
device = device,
dtype = dtype,
)
self.tokenizer = T5v11Tokenizer(embedding_directory=embedding_directory)
self.patcher = comfy.model_patcher.ModelPatcher(
self.cond_stage_model,
load_device = self.load_device,
offload_device = self.offload_device,
size = size,
)
def clone(self):
n = T5(no_init=True)
n.patcher = self.patcher.clone()
n.cond_stage_model = self.cond_stage_model
n.tokenizer = self.tokenizer
return n
def tokenize(self, text, return_word_ids=False):
return self.tokenizer.tokenize_with_weights(text, return_word_ids)
def encode_from_tokens(self, tokens):
self.load_model()
return self.cond_stage_model.encode_token_weights(tokens)
def encode(self, text):
tokens = self.tokenize(text)
return self.encode_from_tokens(tokens)
def load_sd(self, sd):
return self.cond_stage_model.load_sd(sd)
def get_sd(self):
return self.cond_stage_model.state_dict()
def load_model(self):
if self.load_device != "cpu":
model_management.load_model_gpu(self.patcher)
return self.patcher
def add_patches(self, patches, strength_patch=1.0, strength_model=1.0):
return self.patcher.add_patches(patches, strength_patch, strength_model)
def get_key_patches(self):
return self.patcher.get_key_patches()
def load_t5(model_type, model_ver, model_path, path_type="file", device="cpu", dtype=None):
assert model_type in ["t5v11"] # Only supported model for now
model_args = {
"textmodel_ver" : model_ver,
"device" : device,
"dtype" : dtype,
}
if path_type == "folder":
# pass directly to transformers and initialize there
# this is to avoid having to handle multi-file state dict loading for now.
model_args["textmodel_path"] = os.path.dirname(model_path)
return EXM_T5v11(**model_args)
else:
# for some reason this returns garbage with torch.int8 weights, or just OOMs
model = EXM_T5v11(**model_args)
sd = comfy.utils.load_torch_file(model_path)
model.load_sd(sd)
return model
-95
View File
@@ -1,95 +0,0 @@
import os
import json
import torch
import folder_paths
from .loader import load_t5
from ..utils.dtype import string_to_dtype
# initialize custom folder path
os.makedirs(
os.path.join(folder_paths.models_dir,"t5"),
exist_ok = True,
)
folder_paths.folder_names_and_paths["t5"] = (
[
os.path.join(folder_paths.models_dir,"t5"),
*folder_paths.folder_names_and_paths.get("t5", [[],set()])[0]
],
folder_paths.supported_pt_extensions
)
dtypes = [
"default",
"auto (comfy)",
"FP32",
"FP16",
# Note: remove these at some point
"bnb8bit",
"bnb4bit",
]
try: torch.float8_e5m2
except AttributeError: print("Torch version too old for FP8")
else: dtypes += ["FP8 E4M3", "FP8 E5M2"]
class T5v11Loader:
@classmethod
def INPUT_TYPES(s):
devices = ["auto", "cpu", "gpu"]
# hack for using second GPU as offload
for k in range(1, torch.cuda.device_count()):
devices.append(f"cuda:{k}")
return {
"required": {
"t5v11_name": (folder_paths.get_filename_list("t5"),),
"t5v11_ver": (["xxl"],),
"path_type": (["folder", "file"],),
"device": (devices, {"default":"cpu"}),
"dtype": (dtypes,),
}
}
RETURN_TYPES = ("T5",)
FUNCTION = "load_model"
CATEGORY = "ExtraModels/T5"
TITLE = "T5v1.1 Loader"
def load_model(self, t5v11_name, t5v11_ver, path_type, device, dtype):
if "bnb" in dtype:
assert device == "gpu" or device.startswith("cuda"), "BitsAndBytes only works on CUDA! Set device to 'gpu'."
dtype = string_to_dtype(dtype, "text_encoder")
if device == "cpu":
assert dtype in [None, torch.float32], f"Can't use dtype '{dtype}' with CPU! Set dtype to 'default'."
return (load_t5(
model_type = "t5v11",
model_ver = t5v11_ver,
model_path = folder_paths.get_full_path("t5", t5v11_name),
path_type = path_type,
device = device,
dtype = dtype,
),)
class T5TextEncode:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"text": ("STRING", {"multiline": True}),
"T5": ("T5",),
}
}
RETURN_TYPES = ("CONDITIONING",)
FUNCTION = "encode"
CATEGORY = "ExtraModels/T5"
TITLE = "T5 Text Encode"
def encode(self, text, T5=None):
tokens = T5.tokenize(text)
cond = T5.encode_from_tokens(tokens)
return ([[cond, {}]], )
NODE_CLASS_MAPPINGS = {
"T5v11Loader" : T5v11Loader,
"T5TextEncode" : T5TextEncode,
}
-31
View File
@@ -1,31 +0,0 @@
{
"_name_or_path": "google/t5-v1_1-xxl",
"architectures": [
"T5EncoderModel"
],
"d_ff": 10240,
"d_kv": 64,
"d_model": 4096,
"decoder_start_token_id": 0,
"dense_act_fn": "gelu_new",
"dropout_rate": 0.1,
"eos_token_id": 1,
"feed_forward_proj": "gated-gelu",
"initializer_factor": 1.0,
"is_encoder_decoder": true,
"is_gated_act": true,
"layer_norm_epsilon": 1e-06,
"model_type": "t5",
"num_decoder_layers": 24,
"num_heads": 64,
"num_layers": 24,
"output_past": true,
"pad_token_id": 0,
"relative_attention_max_distance": 128,
"relative_attention_num_buckets": 32,
"tie_word_embeddings": false,
"torch_dtype": "float32",
"transformers_version": "4.21.1",
"use_cache": true,
"vocab_size": 32128
}
-227
View File
@@ -1,227 +0,0 @@
"""
Adapted from comfyui CLIP code.
https://github.com/comfyanonymous/ComfyUI/blob/master/comfy/sd1_clip.py
"""
import os
from transformers import T5Tokenizer, T5EncoderModel, T5Config, modeling_utils
import torch
import traceback
import zipfile
from comfy import model_management
from comfy.sd1_clip import parse_parentheses, token_weights, escape_important, unescape_important, safe_load_embed_zip, expand_directory_list, load_embed
class T5v11Model(torch.nn.Module):
def __init__(self, textmodel_ver="xxl", textmodel_json_config=None, textmodel_path=None, device="cpu", max_length=120, freeze=True, dtype=None):
super().__init__()
self.num_layers = 24
self.max_length = max_length
self.bnb = False
if textmodel_path is not None:
model_args = {}
model_args["low_cpu_mem_usage"] = True # Don't take 2x system ram on cpu
if dtype == "bnb8bit":
self.bnb = True
model_args["load_in_8bit"] = True
elif dtype == "bnb4bit":
self.bnb = True
model_args["load_in_4bit"] = True
else:
if dtype: model_args["torch_dtype"] = dtype
self.bnb = False
# second GPU offload hack part 2
if device.startswith("cuda"):
model_args["device_map"] = device
print(f"Loading T5 from '{textmodel_path}'")
self.transformer = T5EncoderModel.from_pretrained(textmodel_path, **model_args)
else:
if textmodel_json_config is None:
textmodel_json_config = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
f"t5v11-{textmodel_ver}_config.json"
)
config = T5Config.from_json_file(textmodel_json_config)
self.num_layers = config.num_hidden_layers
with modeling_utils.no_init_weights():
self.transformer = T5EncoderModel(config)
if freeze:
self.freeze()
self.empty_tokens = [[0] * self.max_length] # <pad> token
def freeze(self):
self.transformer = self.transformer.eval()
for param in self.parameters():
param.requires_grad = False
def forward(self, tokens):
device = self.transformer.get_input_embeddings().weight.device
tokens = torch.LongTensor(tokens).to(device)
attention_mask = torch.zeros_like(tokens)
max_token = 1 # </s> token
for x in range(attention_mask.shape[0]):
for y in range(attention_mask.shape[1]):
attention_mask[x, y] = 1
if tokens[x, y] == max_token:
break
outputs = self.transformer(input_ids=tokens, attention_mask=attention_mask)
z = outputs['last_hidden_state']
z.detach().cpu().float()
return z
def encode(self, tokens):
return self(tokens)
def load_sd(self, sd):
return self.transformer.load_state_dict(sd, strict=False)
def to(self, *args, **kwargs):
"""BNB complains if you try to change the device or dtype"""
if self.bnb:
print("Thanks to BitsAndBytes, T5 becomes an immovable rock.", args, kwargs)
else:
self.transformer.to(*args, **kwargs)
def encode_token_weights(self, token_weight_pairs, return_padded=False):
to_encode = list(self.empty_tokens)
for x in token_weight_pairs:
tokens = list(map(lambda a: a[0], x))
to_encode.append(tokens)
out = self.encode(to_encode)
z_empty = out[0:1]
output = []
for k in range(1, out.shape[0]):
z = out[k:k+1]
for i in range(len(z)):
for j in range(len(z[i])):
weight = token_weight_pairs[k - 1][j][1]
z[i][j] = (z[i][j] - z_empty[0][j]) * weight + z_empty[0][j]
output.append(z)
if (len(output) == 0):
return z_empty.cpu()
out = torch.cat(output, dim=-2)
if not return_padded:
# Count number of tokens that aren't <pad>, then use that number as an index.
keep_index = sum([sum([1 for y in x if y[0] != 0]) for x in token_weight_pairs])
out = out[:, :keep_index, :]
return out
class T5v11Tokenizer:
"""
This is largely just based on the ComfyUI CLIP code.
"""
def __init__(self, tokenizer_path=None, max_length=120, embedding_directory=None, embedding_size=4096, embedding_key='t5'):
if tokenizer_path is None:
tokenizer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "t5_tokenizer")
self.tokenizer = T5Tokenizer.from_pretrained(tokenizer_path)
self.max_length = max_length
self.max_tokens_per_section = self.max_length - 1 # </s> but no <BOS>
self.pad_token = self.tokenizer("<pad>", add_special_tokens=False)["input_ids"][0]
self.end_token = self.tokenizer("</s>", add_special_tokens=False)["input_ids"][0]
vocab = self.tokenizer.get_vocab()
self.inv_vocab = {v: k for k, v in vocab.items()}
self.embedding_directory = embedding_directory
self.max_word_length = 8 # haven't verified this
self.embedding_identifier = "embedding:"
self.embedding_size = embedding_size
self.embedding_key = embedding_key
def _try_get_embedding(self, embedding_name:str):
'''
Takes a potential embedding name and tries to retrieve it.
Returns a Tuple consisting of the embedding and any leftover string, embedding can be None.
'''
embed = load_embed(embedding_name, self.embedding_directory, self.embedding_size, self.embedding_key)
if embed is None:
stripped = embedding_name.strip(',')
if len(stripped) < len(embedding_name):
embed = load_embed(stripped, self.embedding_directory, self.embedding_size, self.embedding_key)
return (embed, embedding_name[len(stripped):])
return (embed, "")
def tokenize_with_weights(self, text:str, return_word_ids=False):
'''
Takes a prompt and converts it to a list of (token, weight, word id) elements.
Tokens can both be integer tokens and pre computed T5 tensors.
Word id values are unique per word and embedding, where the id 0 is reserved for non word tokens.
Returned list has the dimensions NxM where M is the input size of T5
'''
pad_token = self.pad_token
text = escape_important(text)
parsed_weights = token_weights(text, 1.0)
#tokenize words
tokens = []
for weighted_segment, weight in parsed_weights:
to_tokenize = unescape_important(weighted_segment).replace("\n", " ").split(' ')
to_tokenize = [x for x in to_tokenize if x != ""]
for word in to_tokenize:
#if we find an embedding, deal with the embedding
if word.startswith(self.embedding_identifier) and self.embedding_directory is not None:
embedding_name = word[len(self.embedding_identifier):].strip('\n')
embed, leftover = self._try_get_embedding(embedding_name)
if embed is None:
print(f"warning, embedding:{embedding_name} does not exist, ignoring")
else:
if len(embed.shape) == 1:
tokens.append([(embed, weight)])
else:
tokens.append([(embed[x], weight) for x in range(embed.shape[0])])
#if we accidentally have leftover text, continue parsing using leftover, else move on to next word
if leftover != "":
word = leftover
else:
continue
#parse word
tokens.append([(t, weight) for t in self.tokenizer(word, add_special_tokens=False)["input_ids"]])
#reshape token array to T5 input size
batched_tokens = []
batch = []
batched_tokens.append(batch)
for i, t_group in enumerate(tokens):
#determine if we're going to try and keep the tokens in a single batch
is_large = len(t_group) >= self.max_word_length
while len(t_group) > 0:
if len(t_group) + len(batch) > self.max_length - 1:
remaining_length = self.max_length - len(batch) - 1
#break word in two and add end token
if is_large:
batch.extend([(t,w,i+1) for t,w in t_group[:remaining_length]])
batch.append((self.end_token, 1.0, 0))
t_group = t_group[remaining_length:]
#add end token and pad
else:
batch.append((self.end_token, 1.0, 0))
batch.extend([(self.pad_token, 1.0, 0)] * (remaining_length))
#start new batch
batch = []
batched_tokens.append(batch)
else:
batch.extend([(t,w,i+1) for t,w in t_group])
t_group = []
# fill last batch
batch.extend([(self.end_token, 1.0, 0)] + [(self.pad_token, 1.0, 0)] * (self.max_length - len(batch) - 1))
# instead of filling, just add EOS (DEBUG)
# batch.extend([(self.end_token, 1.0, 0)])
if not return_word_ids:
batched_tokens = [[(t, w) for t, w,_ in x] for x in batched_tokens]
return batched_tokens
def untokenize(self, token_weight_pair):
return list(map(lambda a: (a, self.inv_vocab[a[0]]), token_weight_pair))
-3
View File
@@ -34,9 +34,6 @@ class EXVAE(comfy.sd.VAE):
model = MoVQ(model_conf)
elif model_conf["type"] == "DCAE":
from .models.dcae import DCAE
if 'decoder.project_out.op_list.0.bias' in sd:
from .models import dcae_key_mapping
sd = dcae_key_mapping.convert_sd(sd)
model = DCAE(**model_conf)
else:
raise NotImplementedError(f"Unknown VAE type '{model_conf['type']}'")
-350
View File
@@ -1,350 +0,0 @@
def convert_sd(sd, cpu=False):
sd_converted = {}
mapping = get_mapping()
for k, v in sd.items():
sd_converted[mapping[k]] = v.cpu() if cpu else v
return sd_converted
def get_mapping():
return {
"encoder.project_in.conv.bias": "encoder.project_in.bias",
"encoder.project_in.conv.weight": "encoder.project_in.weight",
"encoder.stages.0.op_list.0.main.conv1.conv.bias": "encoder.stages.0.0.conv1.conv.bias",
"encoder.stages.0.op_list.0.main.conv1.conv.weight": "encoder.stages.0.0.conv1.conv.weight",
"encoder.stages.0.op_list.0.main.conv2.conv.weight": "encoder.stages.0.0.conv2.conv.weight",
"encoder.stages.0.op_list.0.main.conv2.norm.bias": "encoder.stages.0.0.conv2.norm.bias",
"encoder.stages.0.op_list.0.main.conv2.norm.weight": "encoder.stages.0.0.conv2.norm.weight",
"encoder.stages.0.op_list.1.main.conv1.conv.bias": "encoder.stages.0.1.conv1.conv.bias",
"encoder.stages.0.op_list.1.main.conv1.conv.weight": "encoder.stages.0.1.conv1.conv.weight",
"encoder.stages.0.op_list.1.main.conv2.conv.weight": "encoder.stages.0.1.conv2.conv.weight",
"encoder.stages.0.op_list.1.main.conv2.norm.bias": "encoder.stages.0.1.conv2.norm.bias",
"encoder.stages.0.op_list.1.main.conv2.norm.weight": "encoder.stages.0.1.conv2.norm.weight",
"encoder.stages.0.op_list.2.main.conv.bias": "encoder.stages.0.2.main.bias",
"encoder.stages.0.op_list.2.main.conv.weight": "encoder.stages.0.2.main.weight",
"encoder.stages.1.op_list.0.main.conv1.conv.bias": "encoder.stages.1.0.conv1.conv.bias",
"encoder.stages.1.op_list.0.main.conv1.conv.weight": "encoder.stages.1.0.conv1.conv.weight",
"encoder.stages.1.op_list.0.main.conv2.conv.weight": "encoder.stages.1.0.conv2.conv.weight",
"encoder.stages.1.op_list.0.main.conv2.norm.bias": "encoder.stages.1.0.conv2.norm.bias",
"encoder.stages.1.op_list.0.main.conv2.norm.weight": "encoder.stages.1.0.conv2.norm.weight",
"encoder.stages.1.op_list.1.main.conv1.conv.bias": "encoder.stages.1.1.conv1.conv.bias",
"encoder.stages.1.op_list.1.main.conv1.conv.weight": "encoder.stages.1.1.conv1.conv.weight",
"encoder.stages.1.op_list.1.main.conv2.conv.weight": "encoder.stages.1.1.conv2.conv.weight",
"encoder.stages.1.op_list.1.main.conv2.norm.bias": "encoder.stages.1.1.conv2.norm.bias",
"encoder.stages.1.op_list.1.main.conv2.norm.weight": "encoder.stages.1.1.conv2.norm.weight",
"encoder.stages.1.op_list.2.main.conv.bias": "encoder.stages.1.2.main.bias",
"encoder.stages.1.op_list.2.main.conv.weight": "encoder.stages.1.2.main.weight",
"encoder.stages.2.op_list.0.main.conv1.conv.bias": "encoder.stages.2.0.conv1.conv.bias",
"encoder.stages.2.op_list.0.main.conv1.conv.weight": "encoder.stages.2.0.conv1.conv.weight",
"encoder.stages.2.op_list.0.main.conv2.conv.weight": "encoder.stages.2.0.conv2.conv.weight",
"encoder.stages.2.op_list.0.main.conv2.norm.bias": "encoder.stages.2.0.conv2.norm.bias",
"encoder.stages.2.op_list.0.main.conv2.norm.weight": "encoder.stages.2.0.conv2.norm.weight",
"encoder.stages.2.op_list.1.main.conv1.conv.bias": "encoder.stages.2.1.conv1.conv.bias",
"encoder.stages.2.op_list.1.main.conv1.conv.weight": "encoder.stages.2.1.conv1.conv.weight",
"encoder.stages.2.op_list.1.main.conv2.conv.weight": "encoder.stages.2.1.conv2.conv.weight",
"encoder.stages.2.op_list.1.main.conv2.norm.bias": "encoder.stages.2.1.conv2.norm.bias",
"encoder.stages.2.op_list.1.main.conv2.norm.weight": "encoder.stages.2.1.conv2.norm.weight",
"encoder.stages.2.op_list.2.main.conv.bias": "encoder.stages.2.2.main.bias",
"encoder.stages.2.op_list.2.main.conv.weight": "encoder.stages.2.2.main.weight",
"encoder.stages.3.op_list.0.context_module.main.aggreg.0.0.weight": "encoder.stages.3.0.context_module.aggreg.0.0.weight",
"encoder.stages.3.op_list.0.context_module.main.aggreg.0.1.weight": "encoder.stages.3.0.context_module.aggreg.0.1.weight",
"encoder.stages.3.op_list.0.context_module.main.proj.conv.weight": "encoder.stages.3.0.context_module.proj.0.weight",
"encoder.stages.3.op_list.0.context_module.main.proj.norm.bias": "encoder.stages.3.0.context_module.proj.1.bias",
"encoder.stages.3.op_list.0.context_module.main.proj.norm.weight": "encoder.stages.3.0.context_module.proj.1.weight",
"encoder.stages.3.op_list.0.context_module.main.qkv.conv.weight": "encoder.stages.3.0.context_module.qkv.0.weight",
"encoder.stages.3.op_list.0.local_module.main.depth_conv.conv.bias": "encoder.stages.3.0.local_module.depth_conv.conv.bias",
"encoder.stages.3.op_list.0.local_module.main.depth_conv.conv.weight": "encoder.stages.3.0.local_module.depth_conv.conv.weight",
"encoder.stages.3.op_list.0.local_module.main.inverted_conv.conv.bias": "encoder.stages.3.0.local_module.inverted_conv.conv.bias",
"encoder.stages.3.op_list.0.local_module.main.inverted_conv.conv.weight": "encoder.stages.3.0.local_module.inverted_conv.conv.weight",
"encoder.stages.3.op_list.0.local_module.main.point_conv.conv.weight": "encoder.stages.3.0.local_module.point_conv.conv.weight",
"encoder.stages.3.op_list.0.local_module.main.point_conv.norm.bias": "encoder.stages.3.0.local_module.point_conv.norm.bias",
"encoder.stages.3.op_list.0.local_module.main.point_conv.norm.weight": "encoder.stages.3.0.local_module.point_conv.norm.weight",
"encoder.stages.3.op_list.1.context_module.main.aggreg.0.0.weight": "encoder.stages.3.1.context_module.aggreg.0.0.weight",
"encoder.stages.3.op_list.1.context_module.main.aggreg.0.1.weight": "encoder.stages.3.1.context_module.aggreg.0.1.weight",
"encoder.stages.3.op_list.1.context_module.main.proj.conv.weight": "encoder.stages.3.1.context_module.proj.0.weight",
"encoder.stages.3.op_list.1.context_module.main.proj.norm.bias": "encoder.stages.3.1.context_module.proj.1.bias",
"encoder.stages.3.op_list.1.context_module.main.proj.norm.weight": "encoder.stages.3.1.context_module.proj.1.weight",
"encoder.stages.3.op_list.1.context_module.main.qkv.conv.weight": "encoder.stages.3.1.context_module.qkv.0.weight",
"encoder.stages.3.op_list.1.local_module.main.depth_conv.conv.bias": "encoder.stages.3.1.local_module.depth_conv.conv.bias",
"encoder.stages.3.op_list.1.local_module.main.depth_conv.conv.weight": "encoder.stages.3.1.local_module.depth_conv.conv.weight",
"encoder.stages.3.op_list.1.local_module.main.inverted_conv.conv.bias": "encoder.stages.3.1.local_module.inverted_conv.conv.bias",
"encoder.stages.3.op_list.1.local_module.main.inverted_conv.conv.weight": "encoder.stages.3.1.local_module.inverted_conv.conv.weight",
"encoder.stages.3.op_list.1.local_module.main.point_conv.conv.weight": "encoder.stages.3.1.local_module.point_conv.conv.weight",
"encoder.stages.3.op_list.1.local_module.main.point_conv.norm.bias": "encoder.stages.3.1.local_module.point_conv.norm.bias",
"encoder.stages.3.op_list.1.local_module.main.point_conv.norm.weight": "encoder.stages.3.1.local_module.point_conv.norm.weight",
"encoder.stages.3.op_list.2.context_module.main.aggreg.0.0.weight": "encoder.stages.3.2.context_module.aggreg.0.0.weight",
"encoder.stages.3.op_list.2.context_module.main.aggreg.0.1.weight": "encoder.stages.3.2.context_module.aggreg.0.1.weight",
"encoder.stages.3.op_list.2.context_module.main.proj.conv.weight": "encoder.stages.3.2.context_module.proj.0.weight",
"encoder.stages.3.op_list.2.context_module.main.proj.norm.bias": "encoder.stages.3.2.context_module.proj.1.bias",
"encoder.stages.3.op_list.2.context_module.main.proj.norm.weight": "encoder.stages.3.2.context_module.proj.1.weight",
"encoder.stages.3.op_list.2.context_module.main.qkv.conv.weight": "encoder.stages.3.2.context_module.qkv.0.weight",
"encoder.stages.3.op_list.2.local_module.main.depth_conv.conv.bias": "encoder.stages.3.2.local_module.depth_conv.conv.bias",
"encoder.stages.3.op_list.2.local_module.main.depth_conv.conv.weight": "encoder.stages.3.2.local_module.depth_conv.conv.weight",
"encoder.stages.3.op_list.2.local_module.main.inverted_conv.conv.bias": "encoder.stages.3.2.local_module.inverted_conv.conv.bias",
"encoder.stages.3.op_list.2.local_module.main.inverted_conv.conv.weight": "encoder.stages.3.2.local_module.inverted_conv.conv.weight",
"encoder.stages.3.op_list.2.local_module.main.point_conv.conv.weight": "encoder.stages.3.2.local_module.point_conv.conv.weight",
"encoder.stages.3.op_list.2.local_module.main.point_conv.norm.bias": "encoder.stages.3.2.local_module.point_conv.norm.bias",
"encoder.stages.3.op_list.2.local_module.main.point_conv.norm.weight": "encoder.stages.3.2.local_module.point_conv.norm.weight",
"encoder.stages.3.op_list.3.main.conv.bias": "encoder.stages.3.3.main.bias",
"encoder.stages.3.op_list.3.main.conv.weight": "encoder.stages.3.3.main.weight",
"encoder.stages.4.op_list.0.context_module.main.aggreg.0.0.weight": "encoder.stages.4.0.context_module.aggreg.0.0.weight",
"encoder.stages.4.op_list.0.context_module.main.aggreg.0.1.weight": "encoder.stages.4.0.context_module.aggreg.0.1.weight",
"encoder.stages.4.op_list.0.context_module.main.proj.conv.weight": "encoder.stages.4.0.context_module.proj.0.weight",
"encoder.stages.4.op_list.0.context_module.main.proj.norm.bias": "encoder.stages.4.0.context_module.proj.1.bias",
"encoder.stages.4.op_list.0.context_module.main.proj.norm.weight": "encoder.stages.4.0.context_module.proj.1.weight",
"encoder.stages.4.op_list.0.context_module.main.qkv.conv.weight": "encoder.stages.4.0.context_module.qkv.0.weight",
"encoder.stages.4.op_list.0.local_module.main.depth_conv.conv.bias": "encoder.stages.4.0.local_module.depth_conv.conv.bias",
"encoder.stages.4.op_list.0.local_module.main.depth_conv.conv.weight": "encoder.stages.4.0.local_module.depth_conv.conv.weight",
"encoder.stages.4.op_list.0.local_module.main.inverted_conv.conv.bias": "encoder.stages.4.0.local_module.inverted_conv.conv.bias",
"encoder.stages.4.op_list.0.local_module.main.inverted_conv.conv.weight": "encoder.stages.4.0.local_module.inverted_conv.conv.weight",
"encoder.stages.4.op_list.0.local_module.main.point_conv.conv.weight": "encoder.stages.4.0.local_module.point_conv.conv.weight",
"encoder.stages.4.op_list.0.local_module.main.point_conv.norm.bias": "encoder.stages.4.0.local_module.point_conv.norm.bias",
"encoder.stages.4.op_list.0.local_module.main.point_conv.norm.weight": "encoder.stages.4.0.local_module.point_conv.norm.weight",
"encoder.stages.4.op_list.1.context_module.main.aggreg.0.0.weight": "encoder.stages.4.1.context_module.aggreg.0.0.weight",
"encoder.stages.4.op_list.1.context_module.main.aggreg.0.1.weight": "encoder.stages.4.1.context_module.aggreg.0.1.weight",
"encoder.stages.4.op_list.1.context_module.main.proj.conv.weight": "encoder.stages.4.1.context_module.proj.0.weight",
"encoder.stages.4.op_list.1.context_module.main.proj.norm.bias": "encoder.stages.4.1.context_module.proj.1.bias",
"encoder.stages.4.op_list.1.context_module.main.proj.norm.weight": "encoder.stages.4.1.context_module.proj.1.weight",
"encoder.stages.4.op_list.1.context_module.main.qkv.conv.weight": "encoder.stages.4.1.context_module.qkv.0.weight",
"encoder.stages.4.op_list.1.local_module.main.depth_conv.conv.bias": "encoder.stages.4.1.local_module.depth_conv.conv.bias",
"encoder.stages.4.op_list.1.local_module.main.depth_conv.conv.weight": "encoder.stages.4.1.local_module.depth_conv.conv.weight",
"encoder.stages.4.op_list.1.local_module.main.inverted_conv.conv.bias": "encoder.stages.4.1.local_module.inverted_conv.conv.bias",
"encoder.stages.4.op_list.1.local_module.main.inverted_conv.conv.weight": "encoder.stages.4.1.local_module.inverted_conv.conv.weight",
"encoder.stages.4.op_list.1.local_module.main.point_conv.conv.weight": "encoder.stages.4.1.local_module.point_conv.conv.weight",
"encoder.stages.4.op_list.1.local_module.main.point_conv.norm.bias": "encoder.stages.4.1.local_module.point_conv.norm.bias",
"encoder.stages.4.op_list.1.local_module.main.point_conv.norm.weight": "encoder.stages.4.1.local_module.point_conv.norm.weight",
"encoder.stages.4.op_list.2.context_module.main.aggreg.0.0.weight": "encoder.stages.4.2.context_module.aggreg.0.0.weight",
"encoder.stages.4.op_list.2.context_module.main.aggreg.0.1.weight": "encoder.stages.4.2.context_module.aggreg.0.1.weight",
"encoder.stages.4.op_list.2.context_module.main.proj.conv.weight": "encoder.stages.4.2.context_module.proj.0.weight",
"encoder.stages.4.op_list.2.context_module.main.proj.norm.bias": "encoder.stages.4.2.context_module.proj.1.bias",
"encoder.stages.4.op_list.2.context_module.main.proj.norm.weight": "encoder.stages.4.2.context_module.proj.1.weight",
"encoder.stages.4.op_list.2.context_module.main.qkv.conv.weight": "encoder.stages.4.2.context_module.qkv.0.weight",
"encoder.stages.4.op_list.2.local_module.main.depth_conv.conv.bias": "encoder.stages.4.2.local_module.depth_conv.conv.bias",
"encoder.stages.4.op_list.2.local_module.main.depth_conv.conv.weight": "encoder.stages.4.2.local_module.depth_conv.conv.weight",
"encoder.stages.4.op_list.2.local_module.main.inverted_conv.conv.bias": "encoder.stages.4.2.local_module.inverted_conv.conv.bias",
"encoder.stages.4.op_list.2.local_module.main.inverted_conv.conv.weight": "encoder.stages.4.2.local_module.inverted_conv.conv.weight",
"encoder.stages.4.op_list.2.local_module.main.point_conv.conv.weight": "encoder.stages.4.2.local_module.point_conv.conv.weight",
"encoder.stages.4.op_list.2.local_module.main.point_conv.norm.bias": "encoder.stages.4.2.local_module.point_conv.norm.bias",
"encoder.stages.4.op_list.2.local_module.main.point_conv.norm.weight": "encoder.stages.4.2.local_module.point_conv.norm.weight",
"encoder.stages.4.op_list.3.main.conv.bias": "encoder.stages.4.3.main.bias",
"encoder.stages.4.op_list.3.main.conv.weight": "encoder.stages.4.3.main.weight",
"encoder.stages.5.op_list.0.context_module.main.aggreg.0.0.weight": "encoder.stages.5.0.context_module.aggreg.0.0.weight",
"encoder.stages.5.op_list.0.context_module.main.aggreg.0.1.weight": "encoder.stages.5.0.context_module.aggreg.0.1.weight",
"encoder.stages.5.op_list.0.context_module.main.proj.conv.weight": "encoder.stages.5.0.context_module.proj.0.weight",
"encoder.stages.5.op_list.0.context_module.main.proj.norm.bias": "encoder.stages.5.0.context_module.proj.1.bias",
"encoder.stages.5.op_list.0.context_module.main.proj.norm.weight": "encoder.stages.5.0.context_module.proj.1.weight",
"encoder.stages.5.op_list.0.context_module.main.qkv.conv.weight": "encoder.stages.5.0.context_module.qkv.0.weight",
"encoder.stages.5.op_list.0.local_module.main.depth_conv.conv.bias": "encoder.stages.5.0.local_module.depth_conv.conv.bias",
"encoder.stages.5.op_list.0.local_module.main.depth_conv.conv.weight": "encoder.stages.5.0.local_module.depth_conv.conv.weight",
"encoder.stages.5.op_list.0.local_module.main.inverted_conv.conv.bias": "encoder.stages.5.0.local_module.inverted_conv.conv.bias",
"encoder.stages.5.op_list.0.local_module.main.inverted_conv.conv.weight": "encoder.stages.5.0.local_module.inverted_conv.conv.weight",
"encoder.stages.5.op_list.0.local_module.main.point_conv.conv.weight": "encoder.stages.5.0.local_module.point_conv.conv.weight",
"encoder.stages.5.op_list.0.local_module.main.point_conv.norm.bias": "encoder.stages.5.0.local_module.point_conv.norm.bias",
"encoder.stages.5.op_list.0.local_module.main.point_conv.norm.weight": "encoder.stages.5.0.local_module.point_conv.norm.weight",
"encoder.stages.5.op_list.1.context_module.main.aggreg.0.0.weight": "encoder.stages.5.1.context_module.aggreg.0.0.weight",
"encoder.stages.5.op_list.1.context_module.main.aggreg.0.1.weight": "encoder.stages.5.1.context_module.aggreg.0.1.weight",
"encoder.stages.5.op_list.1.context_module.main.proj.conv.weight": "encoder.stages.5.1.context_module.proj.0.weight",
"encoder.stages.5.op_list.1.context_module.main.proj.norm.bias": "encoder.stages.5.1.context_module.proj.1.bias",
"encoder.stages.5.op_list.1.context_module.main.proj.norm.weight": "encoder.stages.5.1.context_module.proj.1.weight",
"encoder.stages.5.op_list.1.context_module.main.qkv.conv.weight": "encoder.stages.5.1.context_module.qkv.0.weight",
"encoder.stages.5.op_list.1.local_module.main.depth_conv.conv.bias": "encoder.stages.5.1.local_module.depth_conv.conv.bias",
"encoder.stages.5.op_list.1.local_module.main.depth_conv.conv.weight": "encoder.stages.5.1.local_module.depth_conv.conv.weight",
"encoder.stages.5.op_list.1.local_module.main.inverted_conv.conv.bias": "encoder.stages.5.1.local_module.inverted_conv.conv.bias",
"encoder.stages.5.op_list.1.local_module.main.inverted_conv.conv.weight": "encoder.stages.5.1.local_module.inverted_conv.conv.weight",
"encoder.stages.5.op_list.1.local_module.main.point_conv.conv.weight": "encoder.stages.5.1.local_module.point_conv.conv.weight",
"encoder.stages.5.op_list.1.local_module.main.point_conv.norm.bias": "encoder.stages.5.1.local_module.point_conv.norm.bias",
"encoder.stages.5.op_list.1.local_module.main.point_conv.norm.weight": "encoder.stages.5.1.local_module.point_conv.norm.weight",
"encoder.stages.5.op_list.2.context_module.main.aggreg.0.0.weight": "encoder.stages.5.2.context_module.aggreg.0.0.weight",
"encoder.stages.5.op_list.2.context_module.main.aggreg.0.1.weight": "encoder.stages.5.2.context_module.aggreg.0.1.weight",
"encoder.stages.5.op_list.2.context_module.main.proj.conv.weight": "encoder.stages.5.2.context_module.proj.0.weight",
"encoder.stages.5.op_list.2.context_module.main.proj.norm.bias": "encoder.stages.5.2.context_module.proj.1.bias",
"encoder.stages.5.op_list.2.context_module.main.proj.norm.weight": "encoder.stages.5.2.context_module.proj.1.weight",
"encoder.stages.5.op_list.2.context_module.main.qkv.conv.weight": "encoder.stages.5.2.context_module.qkv.0.weight",
"encoder.stages.5.op_list.2.local_module.main.depth_conv.conv.bias": "encoder.stages.5.2.local_module.depth_conv.conv.bias",
"encoder.stages.5.op_list.2.local_module.main.depth_conv.conv.weight": "encoder.stages.5.2.local_module.depth_conv.conv.weight",
"encoder.stages.5.op_list.2.local_module.main.inverted_conv.conv.bias": "encoder.stages.5.2.local_module.inverted_conv.conv.bias",
"encoder.stages.5.op_list.2.local_module.main.inverted_conv.conv.weight": "encoder.stages.5.2.local_module.inverted_conv.conv.weight",
"encoder.stages.5.op_list.2.local_module.main.point_conv.conv.weight": "encoder.stages.5.2.local_module.point_conv.conv.weight",
"encoder.stages.5.op_list.2.local_module.main.point_conv.norm.bias": "encoder.stages.5.2.local_module.point_conv.norm.bias",
"encoder.stages.5.op_list.2.local_module.main.point_conv.norm.weight": "encoder.stages.5.2.local_module.point_conv.norm.weight",
"encoder.project_out.main.op_list.0.conv.bias": "encoder.project_out.main.0.conv.bias",
"encoder.project_out.main.op_list.0.conv.weight": "encoder.project_out.main.0.conv.weight",
"decoder.project_in.main.conv.bias": "decoder.project_in.main.conv.bias",
"decoder.project_in.main.conv.weight": "decoder.project_in.main.conv.weight",
"decoder.stages.0.op_list.0.main.conv.conv.bias": "decoder.stages.0.0.main.conv.bias",
"decoder.stages.0.op_list.0.main.conv.conv.weight": "decoder.stages.0.0.main.conv.weight",
"decoder.stages.0.op_list.1.main.conv1.conv.bias": "decoder.stages.0.1.conv1.conv.bias",
"decoder.stages.0.op_list.1.main.conv1.conv.weight": "decoder.stages.0.1.conv1.conv.weight",
"decoder.stages.0.op_list.1.main.conv2.conv.weight": "decoder.stages.0.1.conv2.conv.weight",
"decoder.stages.0.op_list.1.main.conv2.norm.bias": "decoder.stages.0.1.conv2.norm.bias",
"decoder.stages.0.op_list.1.main.conv2.norm.weight": "decoder.stages.0.1.conv2.norm.weight",
"decoder.stages.0.op_list.2.main.conv1.conv.bias": "decoder.stages.0.2.conv1.conv.bias",
"decoder.stages.0.op_list.2.main.conv1.conv.weight": "decoder.stages.0.2.conv1.conv.weight",
"decoder.stages.0.op_list.2.main.conv2.conv.weight": "decoder.stages.0.2.conv2.conv.weight",
"decoder.stages.0.op_list.2.main.conv2.norm.bias": "decoder.stages.0.2.conv2.norm.bias",
"decoder.stages.0.op_list.2.main.conv2.norm.weight": "decoder.stages.0.2.conv2.norm.weight",
"decoder.stages.0.op_list.3.main.conv1.conv.bias": "decoder.stages.0.3.conv1.conv.bias",
"decoder.stages.0.op_list.3.main.conv1.conv.weight": "decoder.stages.0.3.conv1.conv.weight",
"decoder.stages.0.op_list.3.main.conv2.conv.weight": "decoder.stages.0.3.conv2.conv.weight",
"decoder.stages.0.op_list.3.main.conv2.norm.bias": "decoder.stages.0.3.conv2.norm.bias",
"decoder.stages.0.op_list.3.main.conv2.norm.weight": "decoder.stages.0.3.conv2.norm.weight",
"decoder.stages.1.op_list.0.main.conv.conv.bias": "decoder.stages.1.0.main.conv.bias",
"decoder.stages.1.op_list.0.main.conv.conv.weight": "decoder.stages.1.0.main.conv.weight",
"decoder.stages.1.op_list.1.main.conv1.conv.bias": "decoder.stages.1.1.conv1.conv.bias",
"decoder.stages.1.op_list.1.main.conv1.conv.weight": "decoder.stages.1.1.conv1.conv.weight",
"decoder.stages.1.op_list.1.main.conv2.conv.weight": "decoder.stages.1.1.conv2.conv.weight",
"decoder.stages.1.op_list.1.main.conv2.norm.bias": "decoder.stages.1.1.conv2.norm.bias",
"decoder.stages.1.op_list.1.main.conv2.norm.weight": "decoder.stages.1.1.conv2.norm.weight",
"decoder.stages.1.op_list.2.main.conv1.conv.bias": "decoder.stages.1.2.conv1.conv.bias",
"decoder.stages.1.op_list.2.main.conv1.conv.weight": "decoder.stages.1.2.conv1.conv.weight",
"decoder.stages.1.op_list.2.main.conv2.conv.weight": "decoder.stages.1.2.conv2.conv.weight",
"decoder.stages.1.op_list.2.main.conv2.norm.bias": "decoder.stages.1.2.conv2.norm.bias",
"decoder.stages.1.op_list.2.main.conv2.norm.weight": "decoder.stages.1.2.conv2.norm.weight",
"decoder.stages.1.op_list.3.main.conv1.conv.bias": "decoder.stages.1.3.conv1.conv.bias",
"decoder.stages.1.op_list.3.main.conv1.conv.weight": "decoder.stages.1.3.conv1.conv.weight",
"decoder.stages.1.op_list.3.main.conv2.conv.weight": "decoder.stages.1.3.conv2.conv.weight",
"decoder.stages.1.op_list.3.main.conv2.norm.bias": "decoder.stages.1.3.conv2.norm.bias",
"decoder.stages.1.op_list.3.main.conv2.norm.weight": "decoder.stages.1.3.conv2.norm.weight",
"decoder.stages.2.op_list.0.main.conv.conv.bias": "decoder.stages.2.0.main.conv.bias",
"decoder.stages.2.op_list.0.main.conv.conv.weight": "decoder.stages.2.0.main.conv.weight",
"decoder.stages.2.op_list.1.main.conv1.conv.bias": "decoder.stages.2.1.conv1.conv.bias",
"decoder.stages.2.op_list.1.main.conv1.conv.weight": "decoder.stages.2.1.conv1.conv.weight",
"decoder.stages.2.op_list.1.main.conv2.conv.weight": "decoder.stages.2.1.conv2.conv.weight",
"decoder.stages.2.op_list.1.main.conv2.norm.bias": "decoder.stages.2.1.conv2.norm.bias",
"decoder.stages.2.op_list.1.main.conv2.norm.weight": "decoder.stages.2.1.conv2.norm.weight",
"decoder.stages.2.op_list.2.main.conv1.conv.bias": "decoder.stages.2.2.conv1.conv.bias",
"decoder.stages.2.op_list.2.main.conv1.conv.weight": "decoder.stages.2.2.conv1.conv.weight",
"decoder.stages.2.op_list.2.main.conv2.conv.weight": "decoder.stages.2.2.conv2.conv.weight",
"decoder.stages.2.op_list.2.main.conv2.norm.bias": "decoder.stages.2.2.conv2.norm.bias",
"decoder.stages.2.op_list.2.main.conv2.norm.weight": "decoder.stages.2.2.conv2.norm.weight",
"decoder.stages.2.op_list.3.main.conv1.conv.bias": "decoder.stages.2.3.conv1.conv.bias",
"decoder.stages.2.op_list.3.main.conv1.conv.weight": "decoder.stages.2.3.conv1.conv.weight",
"decoder.stages.2.op_list.3.main.conv2.conv.weight": "decoder.stages.2.3.conv2.conv.weight",
"decoder.stages.2.op_list.3.main.conv2.norm.bias": "decoder.stages.2.3.conv2.norm.bias",
"decoder.stages.2.op_list.3.main.conv2.norm.weight": "decoder.stages.2.3.conv2.norm.weight",
"decoder.stages.3.op_list.0.main.conv.conv.bias": "decoder.stages.3.0.main.conv.bias",
"decoder.stages.3.op_list.0.main.conv.conv.weight": "decoder.stages.3.0.main.conv.weight",
"decoder.stages.3.op_list.1.context_module.main.aggreg.0.0.weight": "decoder.stages.3.1.context_module.aggreg.0.0.weight",
"decoder.stages.3.op_list.1.context_module.main.aggreg.0.1.weight": "decoder.stages.3.1.context_module.aggreg.0.1.weight",
"decoder.stages.3.op_list.1.context_module.main.proj.conv.weight": "decoder.stages.3.1.context_module.proj.0.weight",
"decoder.stages.3.op_list.1.context_module.main.proj.norm.bias": "decoder.stages.3.1.context_module.proj.1.bias",
"decoder.stages.3.op_list.1.context_module.main.proj.norm.weight": "decoder.stages.3.1.context_module.proj.1.weight",
"decoder.stages.3.op_list.1.context_module.main.qkv.conv.weight": "decoder.stages.3.1.context_module.qkv.0.weight",
"decoder.stages.3.op_list.1.local_module.main.depth_conv.conv.bias": "decoder.stages.3.1.local_module.depth_conv.conv.bias",
"decoder.stages.3.op_list.1.local_module.main.depth_conv.conv.weight": "decoder.stages.3.1.local_module.depth_conv.conv.weight",
"decoder.stages.3.op_list.1.local_module.main.inverted_conv.conv.bias": "decoder.stages.3.1.local_module.inverted_conv.conv.bias",
"decoder.stages.3.op_list.1.local_module.main.inverted_conv.conv.weight": "decoder.stages.3.1.local_module.inverted_conv.conv.weight",
"decoder.stages.3.op_list.1.local_module.main.point_conv.conv.weight": "decoder.stages.3.1.local_module.point_conv.conv.weight",
"decoder.stages.3.op_list.1.local_module.main.point_conv.norm.bias": "decoder.stages.3.1.local_module.point_conv.norm.bias",
"decoder.stages.3.op_list.1.local_module.main.point_conv.norm.weight": "decoder.stages.3.1.local_module.point_conv.norm.weight",
"decoder.stages.3.op_list.2.context_module.main.aggreg.0.0.weight": "decoder.stages.3.2.context_module.aggreg.0.0.weight",
"decoder.stages.3.op_list.2.context_module.main.aggreg.0.1.weight": "decoder.stages.3.2.context_module.aggreg.0.1.weight",
"decoder.stages.3.op_list.2.context_module.main.proj.conv.weight": "decoder.stages.3.2.context_module.proj.0.weight",
"decoder.stages.3.op_list.2.context_module.main.proj.norm.bias": "decoder.stages.3.2.context_module.proj.1.bias",
"decoder.stages.3.op_list.2.context_module.main.proj.norm.weight": "decoder.stages.3.2.context_module.proj.1.weight",
"decoder.stages.3.op_list.2.context_module.main.qkv.conv.weight": "decoder.stages.3.2.context_module.qkv.0.weight",
"decoder.stages.3.op_list.2.local_module.main.depth_conv.conv.bias": "decoder.stages.3.2.local_module.depth_conv.conv.bias",
"decoder.stages.3.op_list.2.local_module.main.depth_conv.conv.weight": "decoder.stages.3.2.local_module.depth_conv.conv.weight",
"decoder.stages.3.op_list.2.local_module.main.inverted_conv.conv.bias": "decoder.stages.3.2.local_module.inverted_conv.conv.bias",
"decoder.stages.3.op_list.2.local_module.main.inverted_conv.conv.weight": "decoder.stages.3.2.local_module.inverted_conv.conv.weight",
"decoder.stages.3.op_list.2.local_module.main.point_conv.conv.weight": "decoder.stages.3.2.local_module.point_conv.conv.weight",
"decoder.stages.3.op_list.2.local_module.main.point_conv.norm.bias": "decoder.stages.3.2.local_module.point_conv.norm.bias",
"decoder.stages.3.op_list.2.local_module.main.point_conv.norm.weight": "decoder.stages.3.2.local_module.point_conv.norm.weight",
"decoder.stages.3.op_list.3.context_module.main.aggreg.0.0.weight": "decoder.stages.3.3.context_module.aggreg.0.0.weight",
"decoder.stages.3.op_list.3.context_module.main.aggreg.0.1.weight": "decoder.stages.3.3.context_module.aggreg.0.1.weight",
"decoder.stages.3.op_list.3.context_module.main.proj.conv.weight": "decoder.stages.3.3.context_module.proj.0.weight",
"decoder.stages.3.op_list.3.context_module.main.proj.norm.bias": "decoder.stages.3.3.context_module.proj.1.bias",
"decoder.stages.3.op_list.3.context_module.main.proj.norm.weight": "decoder.stages.3.3.context_module.proj.1.weight",
"decoder.stages.3.op_list.3.context_module.main.qkv.conv.weight": "decoder.stages.3.3.context_module.qkv.0.weight",
"decoder.stages.3.op_list.3.local_module.main.depth_conv.conv.bias": "decoder.stages.3.3.local_module.depth_conv.conv.bias",
"decoder.stages.3.op_list.3.local_module.main.depth_conv.conv.weight": "decoder.stages.3.3.local_module.depth_conv.conv.weight",
"decoder.stages.3.op_list.3.local_module.main.inverted_conv.conv.bias": "decoder.stages.3.3.local_module.inverted_conv.conv.bias",
"decoder.stages.3.op_list.3.local_module.main.inverted_conv.conv.weight": "decoder.stages.3.3.local_module.inverted_conv.conv.weight",
"decoder.stages.3.op_list.3.local_module.main.point_conv.conv.weight": "decoder.stages.3.3.local_module.point_conv.conv.weight",
"decoder.stages.3.op_list.3.local_module.main.point_conv.norm.bias": "decoder.stages.3.3.local_module.point_conv.norm.bias",
"decoder.stages.3.op_list.3.local_module.main.point_conv.norm.weight": "decoder.stages.3.3.local_module.point_conv.norm.weight",
"decoder.stages.4.op_list.0.main.conv.conv.bias": "decoder.stages.4.0.main.conv.bias",
"decoder.stages.4.op_list.0.main.conv.conv.weight": "decoder.stages.4.0.main.conv.weight",
"decoder.stages.4.op_list.1.context_module.main.aggreg.0.0.weight": "decoder.stages.4.1.context_module.aggreg.0.0.weight",
"decoder.stages.4.op_list.1.context_module.main.aggreg.0.1.weight": "decoder.stages.4.1.context_module.aggreg.0.1.weight",
"decoder.stages.4.op_list.1.context_module.main.proj.conv.weight": "decoder.stages.4.1.context_module.proj.0.weight",
"decoder.stages.4.op_list.1.context_module.main.proj.norm.bias": "decoder.stages.4.1.context_module.proj.1.bias",
"decoder.stages.4.op_list.1.context_module.main.proj.norm.weight": "decoder.stages.4.1.context_module.proj.1.weight",
"decoder.stages.4.op_list.1.context_module.main.qkv.conv.weight": "decoder.stages.4.1.context_module.qkv.0.weight",
"decoder.stages.4.op_list.1.local_module.main.depth_conv.conv.bias": "decoder.stages.4.1.local_module.depth_conv.conv.bias",
"decoder.stages.4.op_list.1.local_module.main.depth_conv.conv.weight": "decoder.stages.4.1.local_module.depth_conv.conv.weight",
"decoder.stages.4.op_list.1.local_module.main.inverted_conv.conv.bias": "decoder.stages.4.1.local_module.inverted_conv.conv.bias",
"decoder.stages.4.op_list.1.local_module.main.inverted_conv.conv.weight": "decoder.stages.4.1.local_module.inverted_conv.conv.weight",
"decoder.stages.4.op_list.1.local_module.main.point_conv.conv.weight": "decoder.stages.4.1.local_module.point_conv.conv.weight",
"decoder.stages.4.op_list.1.local_module.main.point_conv.norm.bias": "decoder.stages.4.1.local_module.point_conv.norm.bias",
"decoder.stages.4.op_list.1.local_module.main.point_conv.norm.weight": "decoder.stages.4.1.local_module.point_conv.norm.weight",
"decoder.stages.4.op_list.2.context_module.main.aggreg.0.0.weight": "decoder.stages.4.2.context_module.aggreg.0.0.weight",
"decoder.stages.4.op_list.2.context_module.main.aggreg.0.1.weight": "decoder.stages.4.2.context_module.aggreg.0.1.weight",
"decoder.stages.4.op_list.2.context_module.main.proj.conv.weight": "decoder.stages.4.2.context_module.proj.0.weight",
"decoder.stages.4.op_list.2.context_module.main.proj.norm.bias": "decoder.stages.4.2.context_module.proj.1.bias",
"decoder.stages.4.op_list.2.context_module.main.proj.norm.weight": "decoder.stages.4.2.context_module.proj.1.weight",
"decoder.stages.4.op_list.2.context_module.main.qkv.conv.weight": "decoder.stages.4.2.context_module.qkv.0.weight",
"decoder.stages.4.op_list.2.local_module.main.depth_conv.conv.bias": "decoder.stages.4.2.local_module.depth_conv.conv.bias",
"decoder.stages.4.op_list.2.local_module.main.depth_conv.conv.weight": "decoder.stages.4.2.local_module.depth_conv.conv.weight",
"decoder.stages.4.op_list.2.local_module.main.inverted_conv.conv.bias": "decoder.stages.4.2.local_module.inverted_conv.conv.bias",
"decoder.stages.4.op_list.2.local_module.main.inverted_conv.conv.weight": "decoder.stages.4.2.local_module.inverted_conv.conv.weight",
"decoder.stages.4.op_list.2.local_module.main.point_conv.conv.weight": "decoder.stages.4.2.local_module.point_conv.conv.weight",
"decoder.stages.4.op_list.2.local_module.main.point_conv.norm.bias": "decoder.stages.4.2.local_module.point_conv.norm.bias",
"decoder.stages.4.op_list.2.local_module.main.point_conv.norm.weight": "decoder.stages.4.2.local_module.point_conv.norm.weight",
"decoder.stages.4.op_list.3.context_module.main.aggreg.0.0.weight": "decoder.stages.4.3.context_module.aggreg.0.0.weight",
"decoder.stages.4.op_list.3.context_module.main.aggreg.0.1.weight": "decoder.stages.4.3.context_module.aggreg.0.1.weight",
"decoder.stages.4.op_list.3.context_module.main.proj.conv.weight": "decoder.stages.4.3.context_module.proj.0.weight",
"decoder.stages.4.op_list.3.context_module.main.proj.norm.bias": "decoder.stages.4.3.context_module.proj.1.bias",
"decoder.stages.4.op_list.3.context_module.main.proj.norm.weight": "decoder.stages.4.3.context_module.proj.1.weight",
"decoder.stages.4.op_list.3.context_module.main.qkv.conv.weight": "decoder.stages.4.3.context_module.qkv.0.weight",
"decoder.stages.4.op_list.3.local_module.main.depth_conv.conv.bias": "decoder.stages.4.3.local_module.depth_conv.conv.bias",
"decoder.stages.4.op_list.3.local_module.main.depth_conv.conv.weight": "decoder.stages.4.3.local_module.depth_conv.conv.weight",
"decoder.stages.4.op_list.3.local_module.main.inverted_conv.conv.bias": "decoder.stages.4.3.local_module.inverted_conv.conv.bias",
"decoder.stages.4.op_list.3.local_module.main.inverted_conv.conv.weight": "decoder.stages.4.3.local_module.inverted_conv.conv.weight",
"decoder.stages.4.op_list.3.local_module.main.point_conv.conv.weight": "decoder.stages.4.3.local_module.point_conv.conv.weight",
"decoder.stages.4.op_list.3.local_module.main.point_conv.norm.bias": "decoder.stages.4.3.local_module.point_conv.norm.bias",
"decoder.stages.4.op_list.3.local_module.main.point_conv.norm.weight": "decoder.stages.4.3.local_module.point_conv.norm.weight",
"decoder.stages.5.op_list.0.context_module.main.aggreg.0.0.weight": "decoder.stages.5.0.context_module.aggreg.0.0.weight",
"decoder.stages.5.op_list.0.context_module.main.aggreg.0.1.weight": "decoder.stages.5.0.context_module.aggreg.0.1.weight",
"decoder.stages.5.op_list.0.context_module.main.proj.conv.weight": "decoder.stages.5.0.context_module.proj.0.weight",
"decoder.stages.5.op_list.0.context_module.main.proj.norm.bias": "decoder.stages.5.0.context_module.proj.1.bias",
"decoder.stages.5.op_list.0.context_module.main.proj.norm.weight": "decoder.stages.5.0.context_module.proj.1.weight",
"decoder.stages.5.op_list.0.context_module.main.qkv.conv.weight": "decoder.stages.5.0.context_module.qkv.0.weight",
"decoder.stages.5.op_list.0.local_module.main.depth_conv.conv.bias": "decoder.stages.5.0.local_module.depth_conv.conv.bias",
"decoder.stages.5.op_list.0.local_module.main.depth_conv.conv.weight": "decoder.stages.5.0.local_module.depth_conv.conv.weight",
"decoder.stages.5.op_list.0.local_module.main.inverted_conv.conv.bias": "decoder.stages.5.0.local_module.inverted_conv.conv.bias",
"decoder.stages.5.op_list.0.local_module.main.inverted_conv.conv.weight": "decoder.stages.5.0.local_module.inverted_conv.conv.weight",
"decoder.stages.5.op_list.0.local_module.main.point_conv.conv.weight": "decoder.stages.5.0.local_module.point_conv.conv.weight",
"decoder.stages.5.op_list.0.local_module.main.point_conv.norm.bias": "decoder.stages.5.0.local_module.point_conv.norm.bias",
"decoder.stages.5.op_list.0.local_module.main.point_conv.norm.weight": "decoder.stages.5.0.local_module.point_conv.norm.weight",
"decoder.stages.5.op_list.1.context_module.main.aggreg.0.0.weight": "decoder.stages.5.1.context_module.aggreg.0.0.weight",
"decoder.stages.5.op_list.1.context_module.main.aggreg.0.1.weight": "decoder.stages.5.1.context_module.aggreg.0.1.weight",
"decoder.stages.5.op_list.1.context_module.main.proj.conv.weight": "decoder.stages.5.1.context_module.proj.0.weight",
"decoder.stages.5.op_list.1.context_module.main.proj.norm.bias": "decoder.stages.5.1.context_module.proj.1.bias",
"decoder.stages.5.op_list.1.context_module.main.proj.norm.weight": "decoder.stages.5.1.context_module.proj.1.weight",
"decoder.stages.5.op_list.1.context_module.main.qkv.conv.weight": "decoder.stages.5.1.context_module.qkv.0.weight",
"decoder.stages.5.op_list.1.local_module.main.depth_conv.conv.bias": "decoder.stages.5.1.local_module.depth_conv.conv.bias",
"decoder.stages.5.op_list.1.local_module.main.depth_conv.conv.weight": "decoder.stages.5.1.local_module.depth_conv.conv.weight",
"decoder.stages.5.op_list.1.local_module.main.inverted_conv.conv.bias": "decoder.stages.5.1.local_module.inverted_conv.conv.bias",
"decoder.stages.5.op_list.1.local_module.main.inverted_conv.conv.weight": "decoder.stages.5.1.local_module.inverted_conv.conv.weight",
"decoder.stages.5.op_list.1.local_module.main.point_conv.conv.weight": "decoder.stages.5.1.local_module.point_conv.conv.weight",
"decoder.stages.5.op_list.1.local_module.main.point_conv.norm.bias": "decoder.stages.5.1.local_module.point_conv.norm.bias",
"decoder.stages.5.op_list.1.local_module.main.point_conv.norm.weight": "decoder.stages.5.1.local_module.point_conv.norm.weight",
"decoder.stages.5.op_list.2.context_module.main.aggreg.0.0.weight": "decoder.stages.5.2.context_module.aggreg.0.0.weight",
"decoder.stages.5.op_list.2.context_module.main.aggreg.0.1.weight": "decoder.stages.5.2.context_module.aggreg.0.1.weight",
"decoder.stages.5.op_list.2.context_module.main.proj.conv.weight": "decoder.stages.5.2.context_module.proj.0.weight",
"decoder.stages.5.op_list.2.context_module.main.proj.norm.bias": "decoder.stages.5.2.context_module.proj.1.bias",
"decoder.stages.5.op_list.2.context_module.main.proj.norm.weight": "decoder.stages.5.2.context_module.proj.1.weight",
"decoder.stages.5.op_list.2.context_module.main.qkv.conv.weight": "decoder.stages.5.2.context_module.qkv.0.weight",
"decoder.stages.5.op_list.2.local_module.main.depth_conv.conv.bias": "decoder.stages.5.2.local_module.depth_conv.conv.bias",
"decoder.stages.5.op_list.2.local_module.main.depth_conv.conv.weight": "decoder.stages.5.2.local_module.depth_conv.conv.weight",
"decoder.stages.5.op_list.2.local_module.main.inverted_conv.conv.bias": "decoder.stages.5.2.local_module.inverted_conv.conv.bias",
"decoder.stages.5.op_list.2.local_module.main.inverted_conv.conv.weight": "decoder.stages.5.2.local_module.inverted_conv.conv.weight",
"decoder.stages.5.op_list.2.local_module.main.point_conv.conv.weight": "decoder.stages.5.2.local_module.point_conv.conv.weight",
"decoder.stages.5.op_list.2.local_module.main.point_conv.norm.bias": "decoder.stages.5.2.local_module.point_conv.norm.bias",
"decoder.stages.5.op_list.2.local_module.main.point_conv.norm.weight": "decoder.stages.5.2.local_module.point_conv.norm.weight",
"decoder.project_out.op_list.0.bias": "decoder.project_out.0.bias",
"decoder.project_out.op_list.0.weight": "decoder.project_out.0.weight",
"decoder.project_out.op_list.2.conv.bias": "decoder.project_out.2.conv.bias",
"decoder.project_out.op_list.2.conv.weight": "decoder.project_out.2.conv.weight",
}
+3 -12
View File
@@ -6,9 +6,9 @@ except ImportError:
else:
NODE_CLASS_MAPPINGS = {}
# Deci Diffusion
# from .DeciDiffusion.nodes import NODE_CLASS_MAPPINGS as DeciDiffusion_Nodes
# NODE_CLASS_MAPPINGS.update(DeciDiffusion_Nodes)
# Generic/universal nodes
from .nodes import NODE_CLASS_MAPPINGS as Base_Nodes
NODE_CLASS_MAPPINGS.update(Base_Nodes)
# DiT
from .DiT.nodes import NODE_CLASS_MAPPINGS as DiT_Nodes
@@ -18,14 +18,6 @@ else:
from .PixArt.nodes import NODE_CLASS_MAPPINGS as PixArt_Nodes
NODE_CLASS_MAPPINGS.update(PixArt_Nodes)
# T5
from .T5.nodes import NODE_CLASS_MAPPINGS as T5_Nodes
NODE_CLASS_MAPPINGS.update(T5_Nodes)
# HYDiT
from .HunYuanDiT.nodes import NODE_CLASS_MAPPINGS as HunYuanDiT_Nodes
NODE_CLASS_MAPPINGS.update(HunYuanDiT_Nodes)
# VAE
from .VAE.nodes import NODE_CLASS_MAPPINGS as VAE_Nodes
NODE_CLASS_MAPPINGS.update(VAE_Nodes)
@@ -48,4 +40,3 @@ else:
NODE_DISPLAY_NAME_MAPPINGS = {k:v.TITLE for k,v in NODE_CLASS_MAPPINGS.items()}
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS']
+70
View File
@@ -0,0 +1,70 @@
import folder_paths
import comfy.utils
from .PixArt.loader import load_pixart_state_dict
from .Sana.loader import load_sana_state_dict
from .text_encoders.tenc import load_text_encoder, tenc_names
loaders = {
"PixArt": load_pixart_state_dict,
"Sana": load_sana_state_dict,
}
class EXMUnetLoader:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"unet_name": (folder_paths.get_filename_list("unet"),),
"model_type": (list(loaders.keys()),)
}
}
RETURN_TYPES = ("MODEL",)
FUNCTION = "load_unet"
CATEGORY = "ExtraModels"
TITLE = "Load Diffusion Model (ExtraModels)"
def load_unet(self, unet_name, model_type):
model_options = {}
unet_path = folder_paths.get_full_path("diffusion_models", unet_name)
loader_fn = loaders[model_type]
sd = comfy.utils.load_torch_file(unet_path)
return (loader_fn(sd),)
class EXMCLIPLoader:
@classmethod
def INPUT_TYPES(s):
files = []
files += folder_paths.get_filename_list("clip")
# if "clip_gguf" in folder_paths.folder_names_and_paths:
# files += folder_paths.get_filename_list("clip_gguf")
return {
"required": {
"clip_name": (files, ),
"type": (["PixArt", "MiaoBi", "Sana"],),
}
}
RETURN_TYPES = ("CLIP",)
FUNCTION = "load_clip"
CATEGORY = "ExtraModels"
TITLE = "CLIPLoader (ExtraModels)"
def load_clip(self, clip_name, type):
clip_path = folder_paths.get_full_path("clip", clip_name)
clip_type = tenc_names.get(type, None)
clip = load_text_encoder(
ckpt_paths =[clip_path],
embedding_directory = folder_paths.get_folder_paths("embeddings"),
clip_type = clip_type
)
return (clip,)
#class EXMResolutionSelect:
NODE_CLASS_MAPPINGS = {
"EXMUnetLoader": EXMUnetLoader,
"EXMCLIPLoader": EXMCLIPLoader,
}
-2
View File
@@ -1,7 +1,5 @@
timm>=0.6.13
sentencepiece>=0.1.97
transformers>=4.34.1
accelerate>=0.23.0
einops>=0.6.0
protobuf>=3.20.3
bitsandbytes>=0.41.0
+43
View File
@@ -0,0 +1,43 @@
import os
import torch
from comfy import sd1_clip
import comfy.text_encoders.t5
import comfy.text_encoders.sd3_clip
import comfy.model_management
from transformers import T5TokenizerFast
class T5XXLModel(comfy.text_encoders.sd3_clip.T5XXLModel):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# make sure empty tokens match
self.special_tokens.pop("end")
class PixArtT5XXL(sd1_clip.SD1ClipModel):
def __init__(self, device="cpu", dtype=None, model_options={}):
super().__init__(device=device, dtype=dtype, name="t5xxl", clip_model=T5XXLModel, model_options=model_options)
class T5XXLTokenizer(sd1_clip.SDTokenizer):
def __init__(self, embedding_directory=None, tokenizer_data={}):
tokenizer_path = os.path.join(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))),
"tokenizers", "t5_tokenizer",
)
super().__init__(tokenizer_path, embedding_directory=embedding_directory, pad_with_end=False, embedding_size=4096, embedding_key='t5xxl', tokenizer_class=T5TokenizerFast, has_start_token=False, pad_to_max_length=False, max_length=99999999, min_length=1)
class PixArtTokenizer(sd1_clip.SD1Tokenizer):
def __init__(self, embedding_directory=None, tokenizer_data={}):
super().__init__(embedding_directory=embedding_directory, tokenizer_data=tokenizer_data, clip_name="t5xxl", tokenizer=T5XXLTokenizer)
# TODO: don't duplicate this?
def pixart_te(dtype_t5=None, t5xxl_scaled_fp8=None):
class PixArtTEModel_(PixArtT5XXL):
def __init__(self, device="cpu", dtype=None, model_options={}):
if t5xxl_scaled_fp8 is not None and "t5xxl_scaled_fp8" not in model_options:
model_options = model_options.copy()
model_options["t5xxl_scaled_fp8"] = t5xxl_scaled_fp8
if dtype is None:
dtype = dtype_t5
super().__init__(device=device, dtype=dtype, model_options=model_options)
return PixArtTEModel_
+35
View File
@@ -0,0 +1,35 @@
{
"architectures": [
"Gemma2ForCausalLM"
],
"attention_bias": false,
"attention_dropout": 0.0,
"attn_logit_softcapping": 50.0,
"bos_token_id": 2,
"cache_implementation": "hybrid",
"eos_token_id": [
1,
107
],
"final_logit_softcapping": 30.0,
"head_dim": 256,
"hidden_act": "gelu_pytorch_tanh",
"hidden_activation": "gelu_pytorch_tanh",
"hidden_size": 2304,
"initializer_range": 0.02,
"intermediate_size": 9216,
"max_position_embeddings": 8192,
"model_type": "gemma2",
"num_attention_heads": 8,
"num_hidden_layers": 26,
"num_key_value_heads": 4,
"pad_token_id": 0,
"query_pre_attn_scalar": 256,
"rms_norm_eps": 1e-06,
"rope_theta": 10000.0,
"sliding_window": 4096,
"torch_dtype": "bfloat16",
"transformers_version": "4.42.4",
"use_cache": true,
"vocab_size": 256000
}
+379
View File
@@ -0,0 +1,379 @@
# Copyright 2024 Google Inc. HuggingFace Inc. team. All rights reserved.
#
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
import torch.nn as nn
import importlib
def rotate_half(x):
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
cos = cos.unsqueeze(unsqueeze_dim)
sin = sin.unsqueeze(unsqueeze_dim)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
def repeat_kv(hidden_states, n_rep):
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
if n_rep == 1:
return hidden_states
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
def sdpa_attention_forward(config, query, key, value, mask=None, **kwargs):
key = repeat_kv(key, config["num_key_value_groups"])
value = repeat_kv(value, config["num_key_value_groups"])
causal_mask = mask
if mask is not None:
causal_mask = causal_mask[:, :, :, : key.shape[-2]]
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
# Reference: https://github.com/pytorch/pytorch/issues/112577.
if query.device.type == "cuda" and causal_mask is not None:
query = query.contiguous()
key = key.contiguous()
value = value.contiguous()
# We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
# in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
is_causal = True if causal_mask is None and query.shape[1] > 1 else False
attn_output = torch.nn.functional.scaled_dot_product_attention(
query,
key,
value,
attn_mask=causal_mask,
dropout_p=0.0,
is_causal=is_causal,
scale=config["scaling"],
)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, None
def eager_attention_forward(config, query, key, value, mask, **kwargs):
key_states = repeat_kv(key, config["num_key_value_groups"])
value_states = repeat_kv(value, config["num_key_value_groups"])
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * config["scaling"]
if config["attn_logit_softcapping"] is not None:
attn_weights = attn_weights / config["attn_logit_softcapping"]
attn_weights = torch.tanh(attn_weights)
attn_weights = attn_weights * config["attn_logit_softcapping"]
if mask is not None: # no matter the length, we just slice it
causal_mask = mask[:, :, :, : key_states.shape[-2]]
attn_weights = attn_weights + causal_mask
# upcast attention to fp32
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
#attn_weights = nn.functional.dropout(attn_weights, p=0, training=config.training)
attn_output = torch.matmul(attn_weights, value_states)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
# torch 2.0 can't pass scale arg to sdpa
if int((torch.__version__).split(".")[1]) >= 1:
attention_forward = sdpa_attention_forward
else:
attention_forward = eager_attention_forward
class Gemma2RMSNorm(nn.Module):
def __init__(self, dim, eps=1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.zeros(dim))
def _norm(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x):
output = self._norm(x.float())
# Llama does x.to(float16) * w whilst Gemma2 is (x * w).to(float16)
# See https://github.com/huggingface/transformers/pull/29402
output = output * (1.0 + self.weight.float())
return output.type_as(x)
def extra_repr(self):
return f"{tuple(self.weight.shape)}, eps={self.eps}"
class Gemma2MLP(nn.Module):
def __init__(self, config, dtype=None, device=None, operations=None):
super().__init__()
self.config = config
self.hidden_size = config["hidden_size"]
self.intermediate_size = config["intermediate_size"]
self.gate_proj = operations.Linear(self.hidden_size, self.intermediate_size, bias=False, dtype=dtype, device=device)
self.up_proj = operations.Linear(self.hidden_size, self.intermediate_size, bias=False, dtype=dtype, device=device)
self.down_proj = operations.Linear(self.intermediate_size, self.hidden_size, bias=False, dtype=dtype, device=device)
if config["hidden_activation"] != "gelu_pytorch_tanh":
raise NotImplementedError("Unknown act mode")
self.act_fn = torch.nn.GELU()
def forward(self, x):
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
class Gemma2RotaryEmbedding(nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000):
super().__init__()
self.dim = dim
self.max_position_embeddings = max_position_embeddings
self.base = base
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float() / self.dim))
self.register_buffer("inv_freq", tensor=inv_freq, persistent=False)
@torch.no_grad()
def forward(self, x, position_ids, seq_len=None):
# x: [bs, num_attention_heads, seq_len, head_size]
self.inv_freq.to(x.device)
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
position_ids_expanded = position_ids[:, None, :].float()
# Force float32 since bfloat16 loses precision on long contexts
# See https://github.com/huggingface/transformers/pull/29285
device_type = x.device.type
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
with torch.autocast(device_type=device_type, enabled=False):
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
emb = torch.cat((freqs, freqs), dim=-1)
cos = emb.cos()
sin = emb.sin()
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
class Gemma2Attention(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config, layer_idx=None, dtype=None, device=None, operations=None):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.attention_dropout = config["attention_dropout"]
self.hidden_size = config["hidden_size"]
self.num_heads = config["num_attention_heads"]
self.head_dim = config["head_dim"]
self.num_key_value_heads = config["num_key_value_heads"]
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
self.max_position_embeddings = config["max_position_embeddings"]
self.rope_theta = config["rope_theta"]
self.is_causal = True
self.scaling = config["query_pre_attn_scalar"]**-0.5
self.sliding_window = config["sliding_window"] if not bool(layer_idx % 2) else None
self.attn_logit_softcapping = config["attn_logit_softcapping"]
if self.hidden_size % self.num_heads != 0:
raise ValueError(
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
f" and `num_heads`: {self.num_heads})."
)
self.q_proj = operations.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config["attention_bias"], dtype=dtype, device=device)
self.k_proj = operations.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config["attention_bias"], dtype=dtype, device=device)
self.v_proj = operations.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config["attention_bias"], dtype=dtype, device=device)
self.o_proj = operations.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config["attention_bias"], dtype=dtype, device=device)
self.rotary_emb = Gemma2RotaryEmbedding(
self.head_dim,
max_position_embeddings=self.max_position_embeddings,
base=self.rope_theta,
)
def forward(self, hidden_states, attention_mask=None, position_ids=None, past_key_value=None, output_attentions=False, use_cache=False, cache_position= None):
bsz, q_len, _ = hidden_states.size()
query_states = self.q_proj(hidden_states)
key_states = self.k_proj(hidden_states)
value_states = self.v_proj(hidden_states)
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
cos, sin = self.rotary_emb(value_states, position_ids)
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
if past_key_value is not None:
# sin and cos are specific to RoPE models; cache_position needed for the static cache
cache_kwargs = {
"sin": sin,
"cos": cos,
"sliding_window": self.sliding_window,
"cache_position": cache_position,
}
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
config = {
"scaling": self.scaling,
"num_key_value_groups": self.num_key_value_groups,
"max_position_embeddings": self.max_position_embeddings,
"attn_logit_softcapping": self.attn_logit_softcapping,
}
attn_output, attn_weights = attention_forward(config, query_states, key_states, value_states, attention_mask, output_attentions=output_attentions)
attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
attn_output = self.o_proj(attn_output)
if not output_attentions:
attn_weights = None
return attn_output, attn_weights, past_key_value
class Gemma2DecoderLayer(nn.Module):
def __init__(self, config, layer_idx, dtype=None, device=None, operations=None):
super().__init__()
self.hidden_size = config["hidden_size"]
self.config = config
self.is_sliding = not bool(layer_idx % 2)
self.self_attn = Gemma2Attention(config=config, layer_idx=layer_idx, dtype=dtype, device=device, operations=operations)
self.mlp = Gemma2MLP(config, dtype=dtype, device=device, operations=operations)
self.input_layernorm = Gemma2RMSNorm(config["hidden_size"], eps=config["rms_norm_eps"])
self.post_attention_layernorm = Gemma2RMSNorm(config["hidden_size"], eps=config["rms_norm_eps"])
self.pre_feedforward_layernorm = Gemma2RMSNorm(config["hidden_size"], eps=config["rms_norm_eps"])
self.post_feedforward_layernorm = Gemma2RMSNorm(config["hidden_size"], eps=config["rms_norm_eps"])
self.sliding_window = config["sliding_window"]
def forward(self, hidden_states, attention_mask=None, position_ids=None, past_key_value=None, output_attentions=False, use_cache=False, cache_position=None):
if self.is_sliding and attention_mask is not None: # efficient SDPA and no padding
# # Flash-attn is a 2D tensor
# if self.config["_attn_implementation == "flash_attention_2":
# if past_key_value is not None: # when decoding
# attention_mask = attention_mask[:, -self.sliding_window :]
# else:
min_dtype = torch.finfo(hidden_states.dtype).min
sliding_window_mask = torch.tril(
torch.ones_like(attention_mask, dtype=torch.bool), diagonal=-self.sliding_window
)
attention_mask = torch.where(sliding_window_mask, min_dtype, attention_mask)
if attention_mask.shape[-1] <= 1: # when decoding
attention_mask = attention_mask[:, :, :, -self.sliding_window :]
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
# Self Attention
hidden_states, self_attn_weights, present_key_value = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_value=past_key_value,
output_attentions=output_attentions,
use_cache=use_cache,
cache_position=cache_position,
)
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.pre_feedforward_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = self.post_feedforward_layernorm(hidden_states)
hidden_states = residual + hidden_states
outputs = (hidden_states,)
if output_attentions:
outputs += (self_attn_weights,)
if use_cache:
outputs += (present_key_value,)
return outputs
def prepare_causal_mask(input_tensor, attention_mask):
dtype, device = input_tensor.dtype, input_tensor.device
batch_size=input_tensor.shape[0]
sequence_length = input_tensor.shape[1]
target_length = attention_mask.shape[-1] if attention_mask is not None else input_tensor.shape[1]
min_dtype = torch.finfo(dtype).min
causal_mask = torch.full(
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
)
if sequence_length != 1:
causal_mask = torch.triu(causal_mask, diagonal=1)
#causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
if attention_mask is not None:
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
mask_length = attention_mask.shape[-1]
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
padding_mask = padding_mask == 0
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
padding_mask, min_dtype
)
return causal_mask
class Gemma2Model(torch.nn.Module):
def __init__(self, config_dict, dtype, device, operations):
super().__init__()
self.padding_idx = 0
self.hidden_size = config_dict["hidden_size"]
self.embed_tokens = operations.Embedding(config_dict["vocab_size"], self.hidden_size, self.padding_idx, device=device, dtype=dtype)
self.num_layers = config_dict["num_hidden_layers"]
self.layers = nn.ModuleList(
[Gemma2DecoderLayer(config_dict, layer_idx, dtype=dtype, device=device, operations=operations) for layer_idx in range(config_dict["num_hidden_layers"])]
)
self.norm = Gemma2RMSNorm(self.hidden_size, eps=config_dict["rms_norm_eps"])
def get_input_embeddings(self):
return self.embed_tokens
def set_input_embeddings(self, value):
self.embed_tokens = value
def forward(self, input_ids=None, attention_mask=None, position_ids=None, intermediate_output=None, final_layer_norm_intermediate=False, *args, **kwargs):
inputs_embeds = self.embed_tokens(input_ids, out_dtype=kwargs.get("dtype", torch.float32))
hidden_states = inputs_embeds
intermediate = None
if attention_mask is not None and position_ids is None:
position_ids = attention_mask.long().cumsum(-1) - 1
position_ids.masked_fill_(attention_mask == 0, 1)
# normalized
# Gemma2 downcasts the below to float16, causing sqrt(3072)=55.4256 to become 55.5
# See https://github.com/huggingface/transformers/pull/29402
normalizer = torch.tensor(self.hidden_size**0.5, dtype=hidden_states.dtype)
hidden_states = hidden_states * normalizer
causal_mask = prepare_causal_mask(inputs_embeds, attention_mask)
if intermediate_output is not None:
if intermediate_output < 0:
intermediate_output = len(self.layers) + intermediate_output
for i, decoder_layer in enumerate(self.layers):
layer_outputs = decoder_layer(
hidden_states,
attention_mask=causal_mask,
position_ids=position_ids,
past_key_value=None,
output_attentions=False,
use_cache=False,
)
if i == intermediate_output:
intermediate = hidden_states.clone()
hidden_states = layer_outputs[0]
hidden_states = self.norm(hidden_states)
if intermediate is not None and final_layer_norm_intermediate:
intermediate = self.norm(intermediate)
return hidden_states, intermediate
+46
View File
@@ -0,0 +1,46 @@
import os
import torch
from comfy import sd1_clip
import comfy.model_management
from .gemma import Gemma2Model
from transformers import GemmaTokenizer as TFGemmaTokenizer
class GemmaClipModel(sd1_clip.SDClipModel):
def __init__(self, device="cpu", dtype=None, model_options={}, **kwargs):
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "config.json")
special_tokens = {"start": 2, "end": 1, "pad": 0}
super().__init__(device=device, layer="last", layer_idx=None, textmodel_json_config=textmodel_json_config, dtype=dtype, special_tokens=special_tokens, model_class=Gemma2Model, enable_attention_masks=True, return_attention_masks=False, model_options=model_options)
class SanaClipModel(sd1_clip.SD1ClipModel):
def __init__(self, device="cpu", dtype=None, model_options={}):
super().__init__(device=device, dtype=dtype, name="gemma", clip_model=GemmaClipModel, model_options=model_options)
class GemmaTokenizer(sd1_clip.SDTokenizer):
def __init__(self, embedding_directory=None, tokenizer_data={}):
tokenizer_path = os.path.join(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))),
"tokenizers", "gemma_tokenizer",
)
# TODO: reenable proper logic here - needs comfy version 44db978 or higher
super().__init__(tokenizer_path, embedding_directory=embedding_directory, pad_with_end=False, embedding_size=2304, embedding_key='gemma', tokenizer_class=TFGemmaTokenizer, has_start_token=False, pad_to_max_length=True, max_length=300, min_length=1)
self.start_token = 2
self.end_token = 1
self.pad_token = 0
def tokenize_with_weights(self, text, return_word_ids=False):
# TODO: see above, this is still just a wrapper for now
tokens = self.tokenizer(
text,
max_length=300,
padding="max_length",
truncation=True,
return_tensors="pt"
)
batched_tokens = [(x.item(), 1.0) for x in tokens.input_ids[0]]
return [batched_tokens]
class SanaTokenizer(sd1_clip.SD1Tokenizer):
def __init__(self, embedding_directory=None, tokenizer_data={}):
super().__init__(embedding_directory=embedding_directory, tokenizer_data=tokenizer_data, clip_name="gemma", tokenizer=GemmaTokenizer)
+81
View File
@@ -0,0 +1,81 @@
import logging
from enum import Enum
import comfy.sd
import comfy.utils
import comfy.text_encoders
import comfy.model_management
from .pixart.tenc import pixart_te, PixArtTokenizer
from .sana.tenc import SanaClipModel, SanaTokenizer
class TencType(Enum):
# offset in case we ever integrate w/ original
PixArt = 1001
MiaoBi = 1002
# HunYuan = 1003 # deprecated
Sana = 1004
tenc_names = {
# for node readout
"PixArt": TencType.PixArt,
"MiaoBi": TencType.MiaoBi,
# "HunYuan": TencType.HunYuan,
"Sana": TencType.Sana,
}
def load_text_encoder(ckpt_paths, embedding_directory=None, clip_type=TencType.PixArt, model_options={}):
# Partial duplicate of ComfyUI/comfy/sd:load_clip
clip_data = []
for p in ckpt_paths:
if p.lower().endswith(".gguf"):
# TODO: cross-node call w/o code duplication
raise NotImplementedError("Planned!")
else:
clip_data.append(comfy.utils.load_torch_file(p, safe_load=True))
return load_text_encoder_state_dicts(clip_data, embedding_directory=embedding_directory, clip_type=clip_type, model_options=model_options)
def load_text_encoder_state_dicts(state_dicts=[], embedding_directory=None, clip_type=TencType.PixArt, model_options={}):
# Partial duplicate of ComfyUI/comfy/sd:load_text_encoder_state_dicts
clip_data = state_dicts
class EmptyClass:
pass
for i in range(len(clip_data)):
if "transformer.resblocks.0.ln_1.weight" in clip_data[i]:
clip_data[i] = comfy.utils.clip_text_transformers_convert(clip_data[i], "", "")
elif "model.layers.25.post_feedforward_layernorm.weight" in clip_data[i]:
clip_data[i] = {k[len("model."):]:v for k,v in clip_data[i].items()}
else:
if "text_projection" in clip_data[i]:
clip_data[i]["text_projection.weight"] = clip_data[i]["text_projection"].transpose(0, 1) #old models saved with the CLIPSave node
clip_target = EmptyClass()
clip_target.params = {}
if clip_type == TencType.PixArt:
clip_target.clip = pixart_te(**comfy.sd.t5xxl_detect(clip_data))
clip_target.tokenizer = PixArtTokenizer
elif clip_type == TencType.Sana:
clip_target.clip = SanaClipModel
clip_target.tokenizer = SanaTokenizer
else:
raise NotImplementedError(f"Unknown tenc: {clip_type}")
parameters = 0
tokenizer_data = {}
for c in clip_data:
parameters += comfy.utils.calculate_parameters(c)
tokenizer_data, model_options = comfy.text_encoders.long_clipl.model_options_long_clip(c, tokenizer_data, model_options)
clip = comfy.sd.CLIP(clip_target, embedding_directory=embedding_directory, parameters=parameters, tokenizer_data=tokenizer_data, model_options=model_options)
for c in clip_data:
m, u = clip.load_sd(c)
if len(m) > 0:
logging.warning("clip missing: {}".format(m))
if len(u) > 0:
logging.debug("clip unexpected: {}".format(u))
return clip
@@ -0,0 +1,34 @@
{
"additional_special_tokens": [
"<start_of_turn>",
"<end_of_turn>"
],
"bos_token": {
"content": "<bos>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
"eos_token": {
"content": "<eos>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
"pad_token": {
"content": "<pad>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
"unk_token": {
"content": "<unk>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
}
}
File diff suppressed because it is too large Load Diff
+35
View File
@@ -0,0 +1,35 @@
import logging
import comfy.utils
import comfy.model_patcher
from comfy import model_management
def load_state_dict_from_config(model_config, sd, model_options={}):
parameters = comfy.utils.calculate_parameters(sd)
load_device = model_management.get_torch_device()
offload_device = comfy.model_management.unet_offload_device()
dtype = model_options.get("dtype", None)
weight_dtype = comfy.utils.weight_dtype(sd)
unet_weight_dtype = list(model_config.supported_inference_dtypes)
if weight_dtype is not None and model_config.scaled_fp8 is None:
unet_weight_dtype.append(weight_dtype)
if dtype is None:
unet_dtype = model_management.unet_dtype(model_params=parameters, supported_dtypes=unet_weight_dtype)
else:
unet_dtype = dtype
manual_cast_dtype = model_management.unet_manual_cast(unet_dtype, load_device, model_config.supported_inference_dtypes)
model_config.set_inference_dtype(unet_dtype, manual_cast_dtype)
model_config.custom_operations = model_options.get("custom_operations", model_config.custom_operations)
if model_options.get("fp8_optimizations", False):
model_config.optimizations["fp8"] = True
model = model_config.get_model(sd, "")
model = model.to(offload_device).eval()
model.load_model_weights(sd, "")
left_over = sd.keys()
if len(left_over) > 0:
logging.info("left over keys in unet: {}".format(left_over))
return comfy.model_patcher.ModelPatcher(model, load_device=load_device, offload_device=offload_device)