Path: blob/main/scripts/convert_vae_diff_to_onnx.py
1440 views
# Copyright 2022 The HuggingFace Team. All rights reserved.1#2# Licensed under the Apache License, Version 2.0 (the "License");3# you may not use this file except in compliance with the License.4# You may obtain a copy of the License at5#6# http://www.apache.org/licenses/LICENSE-2.07#8# Unless required by applicable law or agreed to in writing, software9# distributed under the License is distributed on an "AS IS" BASIS,10# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11# See the License for the specific language governing permissions and12# limitations under the License.1314import argparse15from pathlib import Path1617import torch18from packaging import version19from torch.onnx import export2021from diffusers import AutoencoderKL222324is_torch_less_than_1_11 = version.parse(version.parse(torch.__version__).base_version) < version.parse("1.11")252627def onnx_export(28model,29model_args: tuple,30output_path: Path,31ordered_input_names,32output_names,33dynamic_axes,34opset,35use_external_data_format=False,36):37output_path.parent.mkdir(parents=True, exist_ok=True)38# PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11,39# so we check the torch version for backwards compatibility40if is_torch_less_than_1_11:41export(42model,43model_args,44f=output_path.as_posix(),45input_names=ordered_input_names,46output_names=output_names,47dynamic_axes=dynamic_axes,48do_constant_folding=True,49use_external_data_format=use_external_data_format,50enable_onnx_checker=True,51opset_version=opset,52)53else:54export(55model,56model_args,57f=output_path.as_posix(),58input_names=ordered_input_names,59output_names=output_names,60dynamic_axes=dynamic_axes,61do_constant_folding=True,62opset_version=opset,63)646566@torch.no_grad()67def convert_models(model_path: str, output_path: str, opset: int, fp16: bool = False):68dtype = torch.float16 if fp16 else torch.float3269if fp16 and torch.cuda.is_available():70device = "cuda"71elif fp16 and not torch.cuda.is_available():72raise ValueError("`float16` model export is only supported on GPUs with CUDA")73else:74device = "cpu"75output_path = Path(output_path)7677# VAE DECODER78vae_decoder = AutoencoderKL.from_pretrained(model_path + "/vae")79vae_latent_channels = vae_decoder.config.latent_channels80# forward only through the decoder part81vae_decoder.forward = vae_decoder.decode82onnx_export(83vae_decoder,84model_args=(85torch.randn(1, vae_latent_channels, 25, 25).to(device=device, dtype=dtype),86False,87),88output_path=output_path / "vae_decoder" / "model.onnx",89ordered_input_names=["latent_sample", "return_dict"],90output_names=["sample"],91dynamic_axes={92"latent_sample": {0: "batch", 1: "channels", 2: "height", 3: "width"},93},94opset=opset,95)96del vae_decoder979899if __name__ == "__main__":100parser = argparse.ArgumentParser()101102parser.add_argument(103"--model_path",104type=str,105required=True,106help="Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).",107)108109parser.add_argument("--output_path", type=str, required=True, help="Path to the output model.")110parser.add_argument(111"--opset",112default=14,113type=int,114help="The version of the ONNX operator set to use.",115)116parser.add_argument("--fp16", action="store_true", default=False, help="Export the models in `float16` mode")117118args = parser.parse_args()119print(args.output_path)120convert_models(args.model_path, args.output_path, args.opset, args.fp16)121print("SD: Done: ONNX")122123124