sd_unet.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import torch.nn
  2. import ldm.modules.diffusionmodules.openaimodel
  3. from modules import script_callbacks, shared, devices
  4. unet_options = []
  5. current_unet_option = None
  6. current_unet = None
  7. def list_unets():
  8. new_unets = script_callbacks.list_unets_callback()
  9. unet_options.clear()
  10. unet_options.extend(new_unets)
  11. def get_unet_option(option=None):
  12. option = option or shared.opts.sd_unet
  13. if option == "None":
  14. return None
  15. if option == "Automatic":
  16. name = shared.sd_model.sd_checkpoint_info.model_name
  17. options = [x for x in unet_options if x.model_name == name]
  18. option = options[0].label if options else "None"
  19. return next(iter([x for x in unet_options if x.label == option]), None)
  20. def apply_unet(option=None):
  21. global current_unet_option
  22. global current_unet
  23. new_option = get_unet_option(option)
  24. if new_option == current_unet_option:
  25. return
  26. if current_unet is not None:
  27. print(f"Dectivating unet: {current_unet.option.label}")
  28. current_unet.deactivate()
  29. current_unet_option = new_option
  30. if current_unet_option is None:
  31. current_unet = None
  32. if not (shared.cmd_opts.lowvram or shared.cmd_opts.medvram):
  33. shared.sd_model.model.diffusion_model.to(devices.device)
  34. return
  35. shared.sd_model.model.diffusion_model.to(devices.cpu)
  36. devices.torch_gc()
  37. current_unet = current_unet_option.create_unet()
  38. current_unet.option = current_unet_option
  39. print(f"Activating unet: {current_unet.option.label}")
  40. current_unet.activate()
  41. class SdUnetOption:
  42. model_name = None
  43. """name of related checkpoint - this option will be selected automatically for unet if the name of checkpoint matches this"""
  44. label = None
  45. """name of the unet in UI"""
  46. def create_unet(self):
  47. """returns SdUnet object to be used as a Unet instead of built-in unet when making pictures"""
  48. raise NotImplementedError()
  49. class SdUnet(torch.nn.Module):
  50. def forward(self, x, timesteps, context, *args, **kwargs):
  51. raise NotImplementedError()
  52. def activate(self):
  53. pass
  54. def deactivate(self):
  55. pass
  56. def UNetModel_forward(self, x, timesteps=None, context=None, *args, **kwargs):
  57. if current_unet is not None:
  58. return current_unet.forward(x, timesteps, context, *args, **kwargs)
  59. return ldm.modules.diffusionmodules.openaimodel.copy_of_UNetModel_forward_for_webui(self, x, timesteps, context, *args, **kwargs)