-
Notifications
You must be signed in to change notification settings - Fork 6.1k
Improve single loading file #4041
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
48bb8bb
start improving single file load
patrickvonplaten 05903e2
Fix more
patrickvonplaten 9f4cf10
start improving single file load
patrickvonplaten fcc4e81
Fix sd 2.1
patrickvonplaten bf8b035
further improve from_single_file
patrickvonplaten File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -24,6 +24,7 @@ | |
AutoFeatureExtractor, | ||
BertTokenizerFast, | ||
CLIPImageProcessor, | ||
CLIPTextConfig, | ||
CLIPTextModel, | ||
CLIPTextModelWithProjection, | ||
CLIPTokenizer, | ||
|
@@ -48,7 +49,7 @@ | |
PNDMScheduler, | ||
UnCLIPScheduler, | ||
) | ||
from ...utils import is_omegaconf_available, is_safetensors_available, logging | ||
from ...utils import is_accelerate_available, is_omegaconf_available, is_safetensors_available, logging | ||
from ...utils.import_utils import BACKENDS_MAPPING | ||
from ..latent_diffusion.pipeline_latent_diffusion import LDMBertConfig, LDMBertModel | ||
from ..paint_by_example import PaintByExampleImageEncoder | ||
|
@@ -57,6 +58,10 @@ | |
from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer | ||
|
||
|
||
if is_accelerate_available(): | ||
from accelerate import init_empty_weights | ||
from accelerate.utils import set_module_tensor_to_device | ||
|
||
logger = logging.get_logger(__name__) # pylint: disable=invalid-name | ||
|
||
|
||
|
@@ -770,11 +775,12 @@ def _copy_layers(hf_layers, pt_layers): | |
|
||
|
||
def convert_ldm_clip_checkpoint(checkpoint, local_files_only=False, text_encoder=None): | ||
text_model = ( | ||
CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14", local_files_only=local_files_only) | ||
if text_encoder is None | ||
else text_encoder | ||
) | ||
if text_encoder is None: | ||
config_name = "openai/clip-vit-large-patch14" | ||
config = CLIPTextConfig.from_pretrained(config_name) | ||
|
||
with init_empty_weights(): | ||
text_model = CLIPTextModel(config) | ||
|
||
keys = list(checkpoint.keys()) | ||
|
||
|
@@ -787,7 +793,8 @@ def convert_ldm_clip_checkpoint(checkpoint, local_files_only=False, text_encoder | |
if key.startswith(prefix): | ||
text_model_dict[key[len(prefix + ".") :]] = checkpoint[key] | ||
|
||
text_model.load_state_dict(text_model_dict) | ||
for param_name, param in text_model_dict.items(): | ||
set_module_tensor_to_device(text_model, param_name, "cpu", value=param) | ||
|
||
return text_model | ||
|
||
|
@@ -884,14 +891,26 @@ def convert_paint_by_example_checkpoint(checkpoint): | |
return model | ||
|
||
|
||
def convert_open_clip_checkpoint(checkpoint, prefix="cond_stage_model.model."): | ||
def convert_open_clip_checkpoint( | ||
checkpoint, config_name, prefix="cond_stage_model.model.", has_projection=False, **config_kwargs | ||
): | ||
# text_model = CLIPTextModel.from_pretrained("stabilityai/stable-diffusion-2", subfolder="text_encoder") | ||
text_model = CLIPTextModelWithProjection.from_pretrained( | ||
"laion/CLIP-ViT-bigG-14-laion2B-39B-b160k", projection_dim=1280 | ||
) | ||
# text_model = CLIPTextModelWithProjection.from_pretrained( | ||
# "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k", projection_dim=1280 | ||
# ) | ||
config = CLIPTextConfig.from_pretrained(config_name, **config_kwargs) | ||
|
||
with init_empty_weights(): | ||
text_model = CLIPTextModelWithProjection(config) if has_projection else CLIPTextModel(config) | ||
|
||
keys = list(checkpoint.keys()) | ||
|
||
keys_to_ignore = [] | ||
if config_name == "stabilityai/stable-diffusion-2" and config.num_hidden_layers == 23: | ||
# make sure to remove all keys > 22 | ||
keys_to_ignore += [k for k in keys if k.startswith("cond_stage_model.model.transformer.resblocks.23")] | ||
keys_to_ignore += ["cond_stage_model.model.text_projection"] | ||
|
||
text_model_dict = {} | ||
|
||
if prefix + "text_projection" in checkpoint: | ||
|
@@ -902,8 +921,8 @@ def convert_open_clip_checkpoint(checkpoint, prefix="cond_stage_model.model."): | |
text_model_dict["text_model.embeddings.position_ids"] = text_model.text_model.embeddings.get_buffer("position_ids") | ||
|
||
for key in keys: | ||
# if "resblocks.23" in key: # Diffusers drops the final layer and only uses the penultimate layer | ||
# continue | ||
if key in keys_to_ignore: | ||
continue | ||
if key[len(prefix) :] in textenc_conversion_map: | ||
if key.endswith("text_projection"): | ||
value = checkpoint[key].T | ||
|
@@ -931,7 +950,8 @@ def convert_open_clip_checkpoint(checkpoint, prefix="cond_stage_model.model."): | |
|
||
text_model_dict[new_key] = checkpoint[key] | ||
|
||
text_model.load_state_dict(text_model_dict) | ||
for param_name, param in text_model_dict.items(): | ||
set_module_tensor_to_device(text_model, param_name, "cpu", value=param) | ||
|
||
return text_model | ||
|
||
|
@@ -1061,7 +1081,7 @@ def convert_controlnet_checkpoint( | |
def download_from_original_stable_diffusion_ckpt( | ||
checkpoint_path: str, | ||
original_config_file: str = None, | ||
image_size: int = 512, | ||
image_size: Optional[int] = None, | ||
prediction_type: str = None, | ||
model_type: str = None, | ||
extract_ema: bool = False, | ||
|
@@ -1144,6 +1164,7 @@ def download_from_original_stable_diffusion_ckpt( | |
LDMTextToImagePipeline, | ||
PaintByExamplePipeline, | ||
StableDiffusionControlNetPipeline, | ||
StableDiffusionInpaintPipeline, | ||
StableDiffusionPipeline, | ||
StableDiffusionXLImg2ImgPipeline, | ||
StableDiffusionXLPipeline, | ||
|
@@ -1166,12 +1187,9 @@ def download_from_original_stable_diffusion_ckpt( | |
if not is_safetensors_available(): | ||
raise ValueError(BACKENDS_MAPPING["safetensors"][1]) | ||
|
||
from safetensors import safe_open | ||
from safetensors.torch import load_file as safe_load | ||
|
||
checkpoint = {} | ||
with safe_open(checkpoint_path, framework="pt", device="cpu") as f: | ||
for key in f.keys(): | ||
checkpoint[key] = f.get_tensor(key) | ||
checkpoint = safe_load(checkpoint_path, device="cpu") | ||
else: | ||
if device is None: | ||
device = "cuda" if torch.cuda.is_available() else "cpu" | ||
|
@@ -1183,7 +1201,7 @@ def download_from_original_stable_diffusion_ckpt( | |
if "global_step" in checkpoint: | ||
global_step = checkpoint["global_step"] | ||
else: | ||
logger.warning("global_step key not found in model") | ||
logger.debug("global_step key not found in model") | ||
global_step = None | ||
|
||
# NOTE: this while loop isn't great but this controlnet checkpoint has one additional | ||
|
@@ -1230,9 +1248,15 @@ def download_from_original_stable_diffusion_ckpt( | |
model_type = "SDXL" | ||
else: | ||
model_type = "SDXL-Refiner" | ||
if image_size is None: | ||
image_size = 1024 | ||
|
||
if num_in_channels is not None: | ||
original_config["model"]["params"]["unet_config"]["params"]["in_channels"] = num_in_channels | ||
if num_in_channels is None and pipeline_class == StableDiffusionInpaintPipeline: | ||
num_in_channels = 9 | ||
elif num_in_channels is None: | ||
num_in_channels = 4 | ||
|
||
original_config["model"]["params"]["unet_config"]["params"]["in_channels"] = num_in_channels | ||
|
||
if ( | ||
"parameterization" in original_config["model"]["params"] | ||
|
@@ -1263,7 +1287,6 @@ def download_from_original_stable_diffusion_ckpt( | |
num_train_timesteps = getattr(original_config.model.params, "timesteps", None) or 1000 | ||
|
||
if model_type in ["SDXL", "SDXL-Refiner"]: | ||
image_size = 1024 | ||
scheduler_dict = { | ||
"beta_schedule": "scaled_linear", | ||
"beta_start": 0.00085, | ||
|
@@ -1279,7 +1302,6 @@ def download_from_original_stable_diffusion_ckpt( | |
} | ||
scheduler = EulerDiscreteScheduler.from_config(scheduler_dict) | ||
scheduler_type = "euler" | ||
vae_path = "stabilityai/sdxl-vae" | ||
else: | ||
beta_start = getattr(original_config.model.params, "linear_start", None) or 0.02 | ||
beta_end = getattr(original_config.model.params, "linear_end", None) or 0.085 | ||
|
@@ -1318,25 +1340,45 @@ def download_from_original_stable_diffusion_ckpt( | |
# Convert the UNet2DConditionModel model. | ||
unet_config = create_unet_diffusers_config(original_config, image_size=image_size) | ||
unet_config["upcast_attention"] = upcast_attention | ||
unet = UNet2DConditionModel(**unet_config) | ||
with init_empty_weights(): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we probably need to qualify this with |
||
unet = UNet2DConditionModel(**unet_config) | ||
|
||
converted_unet_checkpoint = convert_ldm_unet_checkpoint( | ||
checkpoint, unet_config, path=checkpoint_path, extract_ema=extract_ema | ||
) | ||
unet.load_state_dict(converted_unet_checkpoint) | ||
|
||
for param_name, param in converted_unet_checkpoint.items(): | ||
set_module_tensor_to_device(unet, param_name, "cpu", value=param) | ||
|
||
# Convert the VAE model. | ||
if vae_path is None: | ||
vae_config = create_vae_diffusers_config(original_config, image_size=image_size) | ||
converted_vae_checkpoint = convert_ldm_vae_checkpoint(checkpoint, vae_config) | ||
|
||
vae = AutoencoderKL(**vae_config) | ||
vae.load_state_dict(converted_vae_checkpoint) | ||
if ( | ||
"model" in original_config | ||
and "params" in original_config.model | ||
and "scale_factor" in original_config.model.params | ||
): | ||
vae_scaling_factor = original_config.model.params.scale_factor | ||
else: | ||
vae_scaling_factor = 0.18215 # default SD scaling factor | ||
|
||
vae_config["scaling_factor"] = vae_scaling_factor | ||
|
||
with init_empty_weights(): | ||
vae = AutoencoderKL(**vae_config) | ||
|
||
for param_name, param in converted_vae_checkpoint.items(): | ||
set_module_tensor_to_device(vae, param_name, "cpu", value=param) | ||
else: | ||
vae = AutoencoderKL.from_pretrained(vae_path) | ||
|
||
if model_type == "FrozenOpenCLIPEmbedder": | ||
text_model = convert_open_clip_checkpoint(checkpoint) | ||
config_name = "stabilityai/stable-diffusion-2" | ||
config_kwargs = {"subfolder": "text_encoder"} | ||
|
||
text_model = convert_open_clip_checkpoint(checkpoint, config_name, **config_kwargs) | ||
tokenizer = CLIPTokenizer.from_pretrained("stabilityai/stable-diffusion-2", subfolder="tokenizer") | ||
|
||
if stable_unclip is None: | ||
|
@@ -1469,7 +1511,12 @@ def download_from_original_stable_diffusion_ckpt( | |
tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14") | ||
text_encoder = convert_ldm_clip_checkpoint(checkpoint, local_files_only=local_files_only) | ||
tokenizer_2 = CLIPTokenizer.from_pretrained("laion/CLIP-ViT-bigG-14-laion2B-39B-b160k", pad_token="!") | ||
text_encoder_2 = convert_open_clip_checkpoint(checkpoint, prefix="conditioner.embedders.1.model.") | ||
|
||
config_name = "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k" | ||
config_kwargs = {"projection_dim": 1280} | ||
text_encoder_2 = convert_open_clip_checkpoint( | ||
checkpoint, config_name, prefix="conditioner.embedders.1.model.", has_projection=True, **config_kwargs | ||
) | ||
|
||
pipe = StableDiffusionXLPipeline( | ||
vae=vae, | ||
|
@@ -1485,7 +1532,12 @@ def download_from_original_stable_diffusion_ckpt( | |
tokenizer = None | ||
text_encoder = None | ||
tokenizer_2 = CLIPTokenizer.from_pretrained("laion/CLIP-ViT-bigG-14-laion2B-39B-b160k", pad_token="!") | ||
text_encoder_2 = convert_open_clip_checkpoint(checkpoint, prefix="conditioner.embedders.0.model.") | ||
|
||
config_name = "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k" | ||
config_kwargs = {"projection_dim": 1280} | ||
text_encoder_2 = convert_open_clip_checkpoint( | ||
checkpoint, config_name, prefix="conditioner.embedders.0.model.", has_projection=True, **config_kwargs | ||
) | ||
|
||
pipe = StableDiffusionXLImg2ImgPipeline( | ||
vae=vae, | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This seems to break downstream if you don't have accelerate and we probably need a
if is_accelerate_available():
checkThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Great catch! I think we should actually just force the user here to install accelerate since this method only exists for PyTorch anyways and there is no harm in installing
accelerate
for PyTorchThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Any chance we can avoid forcing an accelerate install ? We ship nightly HF libraries (transformers, diffusers) and then export out via torch-mlir to SHARK so we don't use PyTorch/Accelerate and would like to avoid adding the dependency to our shipping binaries if possible.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in: #4132