sd_disable_initialization.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import ldm.modules.encoders.modules
  2. import open_clip
  3. import torch
  4. import transformers.utils.hub
  5. class DisableInitialization:
  6. """
  7. When an object of this class enters a `with` block, it starts:
  8. - preventing torch's layer initialization functions from working
  9. - changes CLIP and OpenCLIP to not download model weights
  10. - changes CLIP to not make requests to check if there is a new version of a file you already have
  11. When it leaves the block, it reverts everything to how it was before.
  12. Use it like this:
  13. ```
  14. with DisableInitialization():
  15. do_things()
  16. ```
  17. """
  18. def __init__(self, disable_clip=True):
  19. self.replaced = []
  20. self.disable_clip = disable_clip
  21. def replace(self, obj, field, func):
  22. original = getattr(obj, field, None)
  23. if original is None:
  24. return None
  25. self.replaced.append((obj, field, original))
  26. setattr(obj, field, func)
  27. return original
  28. def __enter__(self):
  29. def do_nothing(*args, **kwargs):
  30. pass
  31. def create_model_and_transforms_without_pretrained(*args, pretrained=None, **kwargs):
  32. return self.create_model_and_transforms(*args, pretrained=None, **kwargs)
  33. def CLIPTextModel_from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs):
  34. res = self.CLIPTextModel_from_pretrained(None, *model_args, config=pretrained_model_name_or_path, state_dict={}, **kwargs)
  35. res.name_or_path = pretrained_model_name_or_path
  36. return res
  37. def transformers_modeling_utils_load_pretrained_model(*args, **kwargs):
  38. args = args[0:3] + ('/', ) + args[4:] # resolved_archive_file; must set it to something to prevent what seems to be a bug
  39. return self.transformers_modeling_utils_load_pretrained_model(*args, **kwargs)
  40. def transformers_utils_hub_get_file_from_cache(original, url, *args, **kwargs):
  41. # this file is always 404, prevent making request
  42. if url == 'https://huggingface.co/openai/clip-vit-large-patch14/resolve/main/added_tokens.json' or url == 'openai/clip-vit-large-patch14' and args[0] == 'added_tokens.json':
  43. return None
  44. try:
  45. res = original(url, *args, local_files_only=True, **kwargs)
  46. if res is None:
  47. res = original(url, *args, local_files_only=False, **kwargs)
  48. return res
  49. except Exception:
  50. return original(url, *args, local_files_only=False, **kwargs)
  51. def transformers_utils_hub_get_from_cache(url, *args, local_files_only=False, **kwargs):
  52. return transformers_utils_hub_get_file_from_cache(self.transformers_utils_hub_get_from_cache, url, *args, **kwargs)
  53. def transformers_tokenization_utils_base_cached_file(url, *args, local_files_only=False, **kwargs):
  54. return transformers_utils_hub_get_file_from_cache(self.transformers_tokenization_utils_base_cached_file, url, *args, **kwargs)
  55. def transformers_configuration_utils_cached_file(url, *args, local_files_only=False, **kwargs):
  56. return transformers_utils_hub_get_file_from_cache(self.transformers_configuration_utils_cached_file, url, *args, **kwargs)
  57. self.replace(torch.nn.init, 'kaiming_uniform_', do_nothing)
  58. self.replace(torch.nn.init, '_no_grad_normal_', do_nothing)
  59. self.replace(torch.nn.init, '_no_grad_uniform_', do_nothing)
  60. if self.disable_clip:
  61. self.create_model_and_transforms = self.replace(open_clip, 'create_model_and_transforms', create_model_and_transforms_without_pretrained)
  62. self.CLIPTextModel_from_pretrained = self.replace(ldm.modules.encoders.modules.CLIPTextModel, 'from_pretrained', CLIPTextModel_from_pretrained)
  63. self.transformers_modeling_utils_load_pretrained_model = self.replace(transformers.modeling_utils.PreTrainedModel, '_load_pretrained_model', transformers_modeling_utils_load_pretrained_model)
  64. self.transformers_tokenization_utils_base_cached_file = self.replace(transformers.tokenization_utils_base, 'cached_file', transformers_tokenization_utils_base_cached_file)
  65. self.transformers_configuration_utils_cached_file = self.replace(transformers.configuration_utils, 'cached_file', transformers_configuration_utils_cached_file)
  66. self.transformers_utils_hub_get_from_cache = self.replace(transformers.utils.hub, 'get_from_cache', transformers_utils_hub_get_from_cache)
  67. def __exit__(self, exc_type, exc_val, exc_tb):
  68. for obj, field, original in self.replaced:
  69. setattr(obj, field, original)
  70. self.replaced.clear()