Buckets:
| import os | |
| from typing import List, Optional | |
| import huggingface_hub | |
| import torch | |
| from toolkit.config_modules import GenerateImageConfig, ModelConfig, NetworkConfig | |
| from toolkit.lora_special import LoRASpecialNetwork | |
| from toolkit.models.base_model import BaseModel | |
| from toolkit.basic import flush | |
| from toolkit.prompt_utils import PromptEmbeds | |
| from toolkit.samplers.custom_flowmatch_sampler import ( | |
| CustomFlowMatchEulerDiscreteScheduler, | |
| ) | |
| from toolkit.accelerator import unwrap_model | |
| from toolkit.memory_management import MemoryManager | |
| from toolkit.metadata import get_meta_for_safetensors | |
| from toolkit.models.v2.text_encoders.qwen3 import Qwen3TextEncoder | |
| from toolkit.models.v2.vae.autoencoder_kl import KLVAE | |
| from safetensors.torch import load_file | |
| try: | |
| from diffusers import ZImagePipeline | |
| # our subclass of the diffusers transformer with the universal loading / | |
| # quantization mixin (see toolkit/models/v2/_mixin.py) | |
| from toolkit.models.v2.diffusion_models.z_image import ZImageTransformer2DModel | |
| except ImportError: | |
| raise ImportError( | |
| "Diffusers is out of date. Update diffusers to the latest version by doing pip uninstall diffusers and then pip install -r requirements.txt" | |
| ) | |
| scheduler_config = { | |
| "num_train_timesteps": 1000, | |
| "use_dynamic_shifting": False, | |
| "shift": 3.0, | |
| } | |
| # repo to pull the vae / text encoder / tokenizer / config from when loading a | |
| # single-file checkpoint | |
| SINGLE_FILE_EXTRAS_REPO = "Tongyi-MAI/Z-Image-Turbo" | |
| class ZImageModel(BaseModel): | |
| arch = "zimage" | |
| def __init__( | |
| self, | |
| device, | |
| model_config: ModelConfig, | |
| dtype="bf16", | |
| custom_pipeline=None, | |
| noise_scheduler=None, | |
| **kwargs, | |
| ): | |
| super().__init__( | |
| device, model_config, dtype, custom_pipeline, noise_scheduler, **kwargs | |
| ) | |
| self.is_flow_matching = True | |
| self.is_transformer = True | |
| self.target_lora_modules = ["ZImageTransformer2DModel"] | |
| # set to True when loading a single-file checkpoint so we save back in that format | |
| self.is_single_file = False | |
| # repo to pull config/vae/te from when loading a single-file checkpoint | |
| self.single_file_extras_repo = SINGLE_FILE_EXTRAS_REPO | |
| # static method to get the noise scheduler | |
| def get_train_scheduler(): | |
| return CustomFlowMatchEulerDiscreteScheduler(**scheduler_config) | |
| def get_bucket_divisibility(self): | |
| return 8 * 2 # 8 for the VAE, 2 for patch size | |
| def load_training_adapter(self, transformer: ZImageTransformer2DModel): | |
| self.print_and_status_update("Loading assistant LoRA") | |
| lora_path = self.model_config.assistant_lora_path | |
| if not os.path.exists(lora_path): | |
| # assume it is a hub path | |
| lora_splits = lora_path.split("/") | |
| if len(lora_splits) != 3: | |
| raise ValueError( | |
| f"Assistant LoRA path {lora_path} is not a valid local path or hub path." | |
| ) | |
| repo_id = "/".join(lora_splits[:2]) | |
| filename = lora_splits[2] | |
| try: | |
| lora_path = huggingface_hub.hf_hub_download( | |
| repo_id=repo_id, | |
| filename=filename, | |
| ) | |
| # upgrade path to | |
| self.model_config.assistant_lora_path = lora_path | |
| except Exception as e: | |
| raise ValueError( | |
| f"Failed to download assistant LoRA from {lora_path}: {e}" | |
| ) | |
| # load the adapter and merge it in. We will inference with a -1.0 multiplier so the adapter effects only work during training. | |
| lora_state_dict = load_file(lora_path) | |
| dim = int( | |
| lora_state_dict[ | |
| "diffusion_model.layers.0.attention.to_k.lora_A.weight" | |
| ].shape[0] | |
| ) | |
| new_sd = {} | |
| for key, value in lora_state_dict.items(): | |
| new_key = key.replace("diffusion_model.", "transformer.") | |
| new_sd[new_key] = value | |
| lora_state_dict = new_sd | |
| network_config = { | |
| "type": "lora", | |
| "linear": dim, | |
| "linear_alpha": dim, | |
| "transformer_only": True, | |
| } | |
| network_config = NetworkConfig(**network_config) | |
| LoRASpecialNetwork.LORA_PREFIX_UNET = "lora_transformer" | |
| network = LoRASpecialNetwork( | |
| text_encoder=None, | |
| unet=transformer, | |
| lora_dim=network_config.linear, | |
| multiplier=1.0, | |
| alpha=network_config.linear_alpha, | |
| train_unet=True, | |
| train_text_encoder=False, | |
| network_config=network_config, | |
| network_type=network_config.type, | |
| transformer_only=network_config.transformer_only, | |
| is_transformer=True, | |
| target_lin_modules=self.target_lora_modules, | |
| is_assistant_adapter=True, | |
| is_ara=True, | |
| ) | |
| network.apply_to(None, transformer, apply_text_encoder=False, apply_unet=True) | |
| self.print_and_status_update("Merging in assistant LoRA") | |
| network.force_to(self.device_torch, dtype=self.torch_dtype) | |
| network._update_torch_multiplier() | |
| network.load_weights(lora_state_dict) | |
| network.merge_in(merge_weight=1.0) | |
| # mark it as not merged so inference ignores it. | |
| network.is_merged_in = False | |
| # add the assistant so sampler will activate it while sampling | |
| self.assistant_lora: LoRASpecialNetwork = network | |
| # deactivate lora during training | |
| self.assistant_lora.multiplier = -1.0 | |
| self.assistant_lora.is_active = False | |
| # tell the model to invert assistant on inference since we want remove lora effects | |
| self.invert_assistant_lora = True | |
| def load_transformer(self, model_path, base_model_path, dtype): | |
| """Load the ZImage transformer through the OstrisModelMixin universal loader | |
| (diffusers folder/repo, local or hub single-file checkpoint, pre-quantized | |
| checkpoint). Returns (transformer, base_model_path) since the base path may | |
| be redirected to the hub repo for single-file checkpoints.""" | |
| if model_path.endswith(".safetensors"): | |
| # single-file checkpoint. Load the weights from the file and pull the | |
| # vae / text encoder / tokenizer / config from the base diffusers repo. | |
| self.is_single_file = True | |
| self.print_and_status_update( | |
| "Model is a single-file checkpoint, loading with safetensors" | |
| ) | |
| if base_model_path == model_path: | |
| # extras default to name_or_path which is the single file, fall back to the hub repo | |
| base_model_path = self.single_file_extras_repo | |
| elif os.path.exists(model_path): | |
| # check if the path is a full checkpoint. | |
| te_folder_path = os.path.join(model_path, "text_encoder") | |
| # if we have the te, this folder is a full checkpoint, use it as the base | |
| if os.path.exists(te_folder_path): | |
| base_model_path = model_path | |
| # quantization happens inside load_model unless an adapter has to be merged | |
| # into the full precision weights first (assistant lora / accuracy recovery | |
| # adapter); those paths quantize after the merge via quantize_model | |
| transformer = ZImageTransformer2DModel.load_model( | |
| model_path, | |
| dtype=dtype, | |
| config_path=base_model_path if self.is_single_file else None, | |
| use_comfy_weights=self.model_config.model_kwargs.get( | |
| "use_comfy_weights", True | |
| ), | |
| # comfy candidate ranking hint only (aitk_post_load quantizes): | |
| # a matching pre-quantized file loads with no requant work | |
| qtype=self.model_config.qtype if self.model_config.quantize else None, | |
| quantize_on_load=False, | |
| ) | |
| flush() | |
| return transformer, base_model_path | |
| def load_model(self): | |
| dtype = self.torch_dtype | |
| self.print_and_status_update("Loading ZImage model") | |
| model_path = self.model_config.name_or_path | |
| base_model_path = self.model_config.extras_name_or_path | |
| self.print_and_status_update("Loading transformer") | |
| transformer, base_model_path = self.load_transformer( | |
| model_path, base_model_path, dtype | |
| ) | |
| # load assistant lora if specified | |
| if self.model_config.assistant_lora_path is not None: | |
| self.load_training_adapter(transformer) | |
| # set qtype to be float8 if it is qfloat8 | |
| if self.model_config.qtype == "qfloat8": | |
| self.model_config.qtype = "float8" | |
| # quantize + offload + placement, all driven by model_config | |
| transformer.aitk_post_load(**self.component_load_kwargs("transformer")) | |
| flush() | |
| self.print_and_status_update("Text Encoder") | |
| tokenizer = Qwen3TextEncoder.load_tokenizer(base_model_path) | |
| text_encoder = Qwen3TextEncoder.load( | |
| base_model_path, **self.component_load_kwargs("te") | |
| ) | |
| self.print_and_status_update("Loading VAE") | |
| vae = KLVAE.load_model(base_model_path, dtype=dtype) | |
| self.noise_scheduler = ZImageModel.get_train_scheduler() | |
| self.print_and_status_update("Making pipe") | |
| kwargs = {} | |
| pipe: ZImagePipeline = ZImagePipeline( | |
| scheduler=self.noise_scheduler, | |
| text_encoder=None, | |
| tokenizer=tokenizer, | |
| vae=vae, | |
| transformer=None, | |
| **kwargs, | |
| ) | |
| # for quantization, it works best to do these after making the pipe | |
| pipe.text_encoder = text_encoder | |
| pipe.transformer = transformer | |
| self.print_and_status_update("Preparing Model") | |
| text_encoder = [pipe.text_encoder] | |
| tokenizer = [pipe.tokenizer] | |
| # leave it on cpu for now | |
| if not self.low_vram: | |
| pipe.transformer = pipe.transformer.to(self.device_torch) | |
| flush() | |
| # just to make sure everything is on the right device and dtype | |
| text_encoder[0].to(self.device_torch) | |
| text_encoder[0].requires_grad_(False) | |
| text_encoder[0].eval() | |
| flush() | |
| # save it to the model class | |
| self.vae = vae | |
| self.text_encoder = text_encoder # list of text encoders | |
| self.tokenizer = tokenizer # list of tokenizers | |
| self.model = pipe.transformer | |
| self.pipeline = pipe | |
| self.print_and_status_update("Model Loaded") | |
| def get_generation_pipeline(self): | |
| scheduler = ZImageModel.get_train_scheduler() | |
| pipeline: ZImagePipeline = ZImagePipeline( | |
| scheduler=scheduler, | |
| text_encoder=unwrap_model(self.text_encoder[0]), | |
| tokenizer=self.tokenizer[0], | |
| vae=unwrap_model(self.vae), | |
| transformer=unwrap_model(self.transformer), | |
| ) | |
| pipeline = pipeline.to(self.device_torch) | |
| return pipeline | |
| def generate_single_image( | |
| self, | |
| pipeline: ZImagePipeline, | |
| gen_config: GenerateImageConfig, | |
| conditional_embeds: PromptEmbeds, | |
| unconditional_embeds: PromptEmbeds, | |
| generator: torch.Generator, | |
| extra: dict, | |
| ): | |
| if self.model.device == torch.device("cpu"): | |
| self.model.to(self.device_torch) | |
| sc = self.get_bucket_divisibility() | |
| gen_config.width = int(gen_config.width // sc * sc) | |
| gen_config.height = int(gen_config.height // sc * sc) | |
| # CFG is 0 normalized for this model | |
| guidance = max(0.0, gen_config.guidance_scale - 1.0) | |
| img = pipeline( | |
| prompt_embeds=conditional_embeds.text_embeds, | |
| negative_prompt_embeds=unconditional_embeds.text_embeds, | |
| height=gen_config.height, | |
| width=gen_config.width, | |
| num_inference_steps=gen_config.num_inference_steps, | |
| guidance_scale=guidance, | |
| latents=gen_config.latents, | |
| generator=generator, | |
| **extra, | |
| ).images[0] | |
| return img | |
| def get_noise_prediction( | |
| self, | |
| latent_model_input: torch.Tensor, | |
| timestep: torch.Tensor, # 0 to 1000 scale | |
| text_embeddings: PromptEmbeds, | |
| **kwargs, | |
| ): | |
| if self.model.device == torch.device("cpu"): | |
| self.model.to(self.device_torch) | |
| latent_model_input = latent_model_input.unsqueeze(2) | |
| latent_model_input_list = list(latent_model_input.unbind(dim=0)) | |
| timestep_model_input = (1000 - timestep) / 1000 | |
| model_out_list = self.transformer( | |
| latent_model_input_list, | |
| timestep_model_input, | |
| text_embeddings.text_embeds, | |
| )[0] | |
| noise_pred = torch.stack([t.float() for t in model_out_list], dim=0) | |
| noise_pred = noise_pred.squeeze(2) | |
| noise_pred = -noise_pred | |
| return noise_pred | |
| def get_prompt_embeds(self, prompt: str) -> PromptEmbeds: | |
| if self.pipeline.text_encoder.device != self.device_torch: | |
| self.pipeline.text_encoder.to(self.device_torch) | |
| prompt_embeds, _ = self.pipeline.encode_prompt( | |
| prompt, | |
| do_classifier_free_guidance=False, | |
| device=self.device_torch, | |
| ) | |
| pe = PromptEmbeds([prompt_embeds, None]) | |
| return pe | |
| def get_model_has_grad(self): | |
| return False | |
| def get_te_has_grad(self): | |
| return False | |
| def get_quantization_exclude_modules(self): | |
| # the patterns live on the transformer class so the mixin quantization | |
| # uses them too (see toolkit/models/classes/z_image.py) | |
| return ZImageTransformer2DModel.get_quantization_exclude_modules() | |
| def save_model(self, output_path, meta, save_dtype): | |
| # comfy-format single-file save (the standard save format regardless | |
| # of how the model was loaded); prequantized layers keep their | |
| # quantized storage | |
| transformer: ZImageTransformer2DModel = unwrap_model(self.model) | |
| if not output_path.endswith(".safetensors"): | |
| output_path += ".safetensors" | |
| transformer.save_model( | |
| output_path, | |
| dtype=save_dtype, | |
| metadata=get_meta_for_safetensors(meta, name=self.arch), | |
| ) | |
| def get_loss_target(self, *args, **kwargs): | |
| noise = kwargs.get("noise") | |
| batch = kwargs.get("batch") | |
| return (noise - batch.latents).detach() | |
| def get_base_model_version(self): | |
| return "zimage" | |
| def get_transformer_block_names(self) -> Optional[List[str]]: | |
| return ["layers"] | |
| lora_keys_use_comfy_prefix = True | |
Xet Storage Details
- Size:
- 14.8 kB
- Xet hash:
- 15ea37b4ec78defb30b821cd031ad13eb80a7d37ee1d6fc082deacfad7f961c9
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.