extract_controlnet.py 1.1 KB

123456789101112131415161718192021222324252627
  1. import argparse
  2. import torch
  3. from safetensors.torch import load_file, save_file
  4. if __name__ == "__main__":
  5. parser = argparse.ArgumentParser()
  6. parser.add_argument("--src", default=None, type=str, required=True, help="Path to the model to convert.")
  7. parser.add_argument("--dst", default=None, type=str, required=True, help="Path to the output model.")
  8. parser.add_argument("--half", action="store_true", help="Cast to FP16.")
  9. args = parser.parse_args()
  10. assert args.src is not None, "Must provide a model path!"
  11. assert args.dst is not None, "Must provide a checkpoint path!"
  12. if args.src.endswith(".safetensors"):
  13. state_dict = load_file(args.src)
  14. else:
  15. state_dict = torch.load(args.src)
  16. if any([k.startswith("control_model.") for k, v in state_dict.items()]):
  17. dtype = torch.float16 if args.half else torch.float32
  18. state_dict = {k.replace("control_model.", ""): v.to(dtype) for k, v in state_dict.items() if k.startswith("control_model.")}
  19. if args.dst.endswith(".safetensors"):
  20. save_file(state_dict, args.dst)
  21. else:
  22. torch.save({"state_dict": state_dict}, args.dst)